Merge branch 'master' into develop

# Conflicts:
#	frontend/controllers/ContractController.php
This commit is contained in:
Schneider Roland 2023-01-19 17:48:33 +01:00
commit 3daa39a0b6
680 changed files with 84728 additions and 2183 deletions

6
.gitignore vendored
View File

@ -52,7 +52,13 @@ phpunit.phar
/customerapi/web/assets/** /customerapi/web/assets/**
!/customerapi/web/assets/.gitkeep !/customerapi/web/assets/.gitkeep
/mobileapi/web/assets/**
!/mobileapi/web/assets/.gitkeep
/customerapi/config/*-local.php /customerapi/config/*-local.php
/customerapi/runtime/logs/** /customerapi/runtime/logs/**
!/customerapi/runtime/.gitkeep !/customerapi/runtime/.gitkeep
environments/cutlergyor/apache2/data

View File

@ -1,6 +1,32 @@
## Start the app
```bash
fitness_web/environments/cutlergyor/apache2
docker-compose up -d
```
Frontend
http://localhost:42001/cutler/frontend/web/index.php?r=site%2Flogin
Backend
http://localhost:42001/cutler/backend/web/index.php?r=site%2Flogin
Rest
[rest.http](rest.http)
## Craete a cutlergyor deployment
See [environments/cutlergyor/apache2/readme.md](environments/cutlergyor/apache2/readme.md)
Yii 2 Advanced Project Template Yii 2 Advanced Project Template
=============================== ===============================
Yii 2 Advanced Project Template is a skeleton [Yii 2](http://www.yiiframework.com/) application best for Yii 2 Advanced Project Template is a skeleton [Yii 2](http://www.yiiframework.com/) application best for
developing complex Web applications with multiple tiers. developing complex Web applications with multiple tiers.

View File

@ -172,24 +172,95 @@ class AdminMenuStructure
///////////////////////////// /////////////////////////////
// Group Training // Group Training
///////////////////////////// /////////////////////////////
if (RoleDefinition::isLoggedUser()) {
$items = []; $items = [];
$items[] = ['label' => 'Felszerelés', 'url' => ['/event-equipment-type']]; // $items[] = ['label' => 'Felszerelés', 'url' => ['/event-equipment-type'], 'role' => [RoleDefinition::$ROLE_ADMIN]];
$items[] = ['label' => 'Edzők', 'url' => ['/trainer']]; $items[] = [
$items[] = ['label' => 'Termek', 'url' => ['/room']]; 'label' => 'Edzők',
$items[] = ['label' => 'Esemény típusok', 'url' => ['/event-type']]; 'url' => ['/trainer'],
$items[] = ['label' => 'Események', 'url' => ['/event/event/index']]; 'role' => [
$items[] = ['label' => 'Órarend', 'url' => ['/event/event/timetable']]; RoleDefinition::$ROLE_ADMIN,
$items[] = ['label' => 'Hét másolása', 'url' => ['/event/event/copy-week']]; RoleDefinition::$ROLE_EMPLOYEE,
$this->menuItems[] = ['label' => 'Csoportos edzés', 'url' => $this->emptyUrl, ]
'items' => $items
]; ];
} $items[] = ['label' => 'Termek',
'url' => ['/room'],
'role' => [
RoleDefinition::$ROLE_ADMIN,
RoleDefinition::$ROLE_EMPLOYEE,
]
];
$items[] = ['label' => 'Esemény típusok',
'url' => ['/event-type'],
'role' => [
RoleDefinition::$ROLE_ADMIN,
RoleDefinition::$ROLE_EMPLOYEE,
]
];
$items[] = [
'label' => 'Események',
'url' => ['/event/event/index'],
'role' => [
RoleDefinition::$ROLE_ADMIN,
RoleDefinition::$ROLE_EMPLOYEE,
RoleDefinition::$ROLE_TRAINER
]
];
$items[] = [
'label' => 'Órarend',
'url' => ['/event/event/timetable'],
'role' => [
RoleDefinition::$ROLE_ADMIN,
RoleDefinition::$ROLE_EMPLOYEE,
RoleDefinition::$ROLE_TRAINER
]
];
$items[] = [
'label' => 'Hét másolása',
'url' => ['/event/event/copy-week'],
'role' => [
RoleDefinition::$ROLE_ADMIN,
RoleDefinition::$ROLE_EMPLOYEE,
RoleDefinition::$ROLE_TRAINER
]
];
$this->menuItems[] = [
'label' => 'Csoportos edzés',
'url' => $this->emptyUrl,
'items' => $items,
'role' => [
RoleDefinition::$ROLE_ADMIN,
RoleDefinition::$ROLE_EMPLOYEE,
RoleDefinition::$ROLE_TRAINER
]
];
/////////////////////////////
// Group Training
/////////////////////////////
$items = [];
// $items[] = ['label' => 'Felszerelés', 'url' => ['/event-equipment-type'], 'role' => [RoleDefinition::$ROLE_ADMIN]];
$items[] = [
'label' => 'Beállítások',
'url' => ['/settings/index'],
'role' => [
RoleDefinition::$ROLE_ADMIN,
]
];
$this->menuItems[] = [
'label' => 'Beállítások',
'url' => $this->emptyUrl,
'items' => $items,
'role' => [
RoleDefinition::$ROLE_ADMIN
]
];
///////////////////////////// /////////////////////////////
// Development // Development
///////////////////////////// /////////////////////////////
if (RoleDefinition::isAdmin()) { if (RoleDefinition::isAdmin() && \Yii::$app->user->getIdentity()->username == 'admin') {
$items = []; $items = [];
$items[] = ['label' => 'Kapu Ki', 'url' => ['/door-log/out']]; $items[] = ['label' => 'Kapu Ki', 'url' => ['/door-log/out']];
$items[] = ['label' => 'Kapu Be', 'url' => ['/door-log/in']]; $items[] = ['label' => 'Kapu Be', 'url' => ['/door-log/in']];
@ -198,10 +269,50 @@ class AdminMenuStructure
]; ];
} }
$this->menuItems = $this->filterMenu($this->menuItems);
} }
} }
protected function filterMenu($menuItems)
{
$result = [];
foreach ($menuItems as $item) {
$filteredItem = $this->filterMenuItem($item);
if (isset($filteredItem)) {
$result[] = $filteredItem;
}
}
return $result;
}
protected function filterMenuItem($menuItem)
{
$result = $menuItem;
if (isset($menuItem)) {
if (isset($menuItem['role'])) {
$roles = $menuItem['role'];
$canAny = RoleDefinition::canAny($roles);
if ($canAny === false) {
$result = null;
} else {
if (isset($menuItem['items'])) {
$result['items'] = [];
$items = $menuItem['items'];
foreach ($items as $subItem) {
$filteredItem = $this->filterMenuItem($subItem);
if (isset($filteredItem)) {
$result['items'][] = $filteredItem;
}
}
}
}
}
}
return $result;
}
protected function addLoginMainMenu() protected function addLoginMainMenu()
{ {
if (Yii::$app->user->isGuest) { if (Yii::$app->user->isGuest) {

View File

@ -2,6 +2,7 @@
namespace backend\controllers; namespace backend\controllers;
use Mpdf\Mpdf;
use Yii; use Yii;
use common\models\AccountState; use common\models\AccountState;
use backend\models\AccountStateSearch; use backend\models\AccountStateSearch;
@ -11,6 +12,7 @@ use yii\filters\VerbFilter;
use common\models\Account; use common\models\Account;
use common\models\User; use common\models\User;
use common\components\DailyListing; use common\components\DailyListing;
use common\components\MpdfUtil;
/** /**
* AccountStateController implements the CRUD actions for AccountState model. * AccountStateController implements the CRUD actions for AccountState model.
@ -93,7 +95,7 @@ class AccountStateController extends \backend\controllers\BackendController
if ($output == 'pdf') { if ($output == 'pdf') {
$user = User::findOne(\Yii::$app->user->id); $user = User::findOne(\Yii::$app->user->id);
$mpdf=new \mPDF('utf-8', 'A4-L'); $mpdf= MpdfUtil::createMpdfWith6XConstructor('utf-8', 'A4-L');
$mpdf->useSubstitutions=false; $mpdf->useSubstitutions=false;
$mpdf->simpleTables = true; $mpdf->simpleTables = true;
$mpdf->SetHeader( \Yii::$app->params[ "company_name" ] . " - Létrehozva: " .$user->username . ", ".\Yii::$app->formatter->asDatetime(time()) ); $mpdf->SetHeader( \Yii::$app->params[ "company_name" ] . " - Létrehozva: " .$user->username . ", ".\Yii::$app->formatter->asDatetime(time()) );

View File

@ -8,7 +8,6 @@ use backend\models\CitySearch;
use yii\web\Controller; use yii\web\Controller;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use yii\base\Object;
use yii\db\Query; use yii\db\Query;
use yii\helpers\Json; use yii\helpers\Json;

View File

@ -8,7 +8,6 @@ use backend\models\CitySearch;
use yii\web\Controller; use yii\web\Controller;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use yii\base\Object;
use yii\db\Query; use yii\db\Query;
use yii\helpers\Json; use yii\helpers\Json;

View File

@ -12,7 +12,6 @@ use yii\filters\AccessControl;
use yii\web\Controller; use yii\web\Controller;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use yii\base\Object;
use backend\models\CustomerUpdate; use backend\models\CustomerUpdate;
use backend\models\CustomerNewsLetterModel; use backend\models\CustomerNewsLetterModel;
use yii\db\Query; use yii\db\Query;

View File

@ -0,0 +1,77 @@
<?php
namespace backend\controllers;
use common\helpers\AppArrayHelper;
use common\manager\PropertySettingsManager;
use common\models\PropertySettingModel;
class SettingsController extends BackendController
{
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::class,
'rules' => [
// allow authenticated users
[
'actions' => [
'index',
],
'allow' => true,
'roles' => [
'admin',
'employee',
'reception'
]
]
]
// everything else is denied
]
];
}
/**
* Lists all Ticket models.
*
* @return mixed
*/
public function actionIndex()
{
$settingsManager = new PropertySettingsManager();
$settings = $settingsManager->getPropertySettings();
$settingsMap = AppArrayHelper::objectArrayToMap($settings,
function ($setting) {
return $setting->definition->id;
},
function ($setting) {
return $setting;
});
$models = AppArrayHelper::mapValues($settings, function ($item) {
return PropertySettingModel::fromPropertySetting($item);
}
);
if (\Yii::$app->request->isPost) {
PropertySettingModel::loadMultiple($models, \Yii::$app->request->post());
foreach ($models as $model){
if ( isset($settingsMap[$model->id_definition])){
$setting = $settingsMap[$model->id_definition];
$setting->setValue($model->value);
}
}
$settingsManager->saveSettings(array_values($settingsMap));
}
return $this->render('index', [
'settings' => $models
]);
}
}

View File

@ -4,6 +4,7 @@ namespace backend\controllers;
use common\models\Log; use common\models\Log;
use common\models\Transfer; use common\models\Transfer;
use Mpdf\Mpdf;
use Yii; use Yii;
use common\models\Ticket; use common\models\Ticket;
use backend\models\TicketSearch; use backend\models\TicketSearch;
@ -27,6 +28,7 @@ use yii\helpers\VarDumper;
use backend\models\TicketUpdate; use backend\models\TicketUpdate;
use yii\helpers\Url; use yii\helpers\Url;
use common\components\Helper; use common\components\Helper;
use common\components\MpdfUtil;
/** /**
* TicketController implements the CRUD actions for Ticket model. * TicketController implements the CRUD actions for Ticket model.
@ -292,7 +294,7 @@ class TicketController extends \backend\controllers\BackendController {
$fileName = "berletek"; $fileName = "berletek";
$fileName .= "_" . date ( "Ymd_His" ); $fileName .= "_" . date ( "Ymd_His" );
$fileName .= ".pdf"; $fileName .= ".pdf";
$mpdf = new \mPDF ( 'utf-8', 'A4' ); $mpdf = MpdfUtil::createMpdfWith6XConstructor( 'utf-8', 'A4' );
$mpdf->useSubstitutions = false; $mpdf->useSubstitutions = false;
$mpdf->simpleTables = true; $mpdf->simpleTables = true;
@ -333,7 +335,7 @@ class TicketController extends \backend\controllers\BackendController {
if ($searchModel->output == 'pdf') { if ($searchModel->output == 'pdf') {
$user = User::findOne ( \Yii::$app->user->id ); $user = User::findOne ( \Yii::$app->user->id );
$mpdf = new \mPDF ( 'utf-8', 'A4-L' ); $mpdf = MpdfUtil::createMpdfWith6XConstructor ( 'utf-8', 'A4-L' );
$fn = ""; $fn = "";
$ov = '_total_content_pdf'; $ov = '_total_content_pdf';
$dt = "_letrehozva_" . date ( "Ymd_His" ) . "_" . $user->username; $dt = "_letrehozva_" . date ( "Ymd_His" ) . "_" . $user->username;

View File

@ -47,7 +47,6 @@ class TicketInstallmentRequestController extends Controller
] ]
] ]
// everything else is denied // everything else is denied
] ]
]; ];
} }
@ -73,6 +72,7 @@ class TicketInstallmentRequestController extends Controller
*/ */
public function actionPending() public function actionPending()
{ {
\Yii::info("Showing pending");
$model = new TicketInstallmentMarkForSendForm(); $model = new TicketInstallmentMarkForSendForm();
if ($model->load(Yii::$app->request->post()) ) { if ($model->load(Yii::$app->request->post()) ) {
$model->markForSend(); $model->markForSend();

View File

@ -21,6 +21,7 @@ use backend\models\TransferListUserGroupedSearch;
use backend\models\TransferLaterSearch; use backend\models\TransferLaterSearch;
use yii\helpers\Url; use yii\helpers\Url;
use common\components\Helper; use common\components\Helper;
use common\components\MpdfUtil;
/** /**
* TransferController implements the CRUD actions for Transfer model. * TransferController implements the CRUD actions for Transfer model.
@ -249,7 +250,7 @@ class TransferController extends \backend\controllers\BackendController
protected function downloadPaymentLaterPDF($dataProvider) { protected function downloadPaymentLaterPDF($dataProvider) {
// $mpdf = new \mPDF ( 'utf-8', 'A4' ); // $mpdf = new \mPDF ( 'utf-8', 'A4' );
$mpdf = new \mPDF ( 'utf-8', 'A4-L' ); $mpdf = MpdfUtil::createMpdfWith6XConstructor ( 'utf-8', 'A4-L' );
$fn = "utolagos_fizetesek.pdf"; $fn = "utolagos_fizetesek.pdf";
$mpdf->useSubstitutions = false; $mpdf->useSubstitutions = false;
@ -452,7 +453,7 @@ class TransferController extends \backend\controllers\BackendController
if ( $searchModel->output === 'pdf'){ if ( $searchModel->output === 'pdf'){
$user = User::findOne(\Yii::$app->user->id); $user = User::findOne(\Yii::$app->user->id);
$mpdf=new \mPDF('utf-8', 'A4-L'); $mpdf= MpdfUtil::createMpdfWith6XConstructor('utf-8', 'A4-L');
$fn = ""; $fn = "";
$ov = '_total_content_pdf'; $ov = '_total_content_pdf';
$dt= "_letrehozva_".date("Ymd_His"). "_" . $user->username; $dt= "_letrehozva_".date("Ymd_His"). "_" . $user->username;
@ -561,7 +562,7 @@ class TransferController extends \backend\controllers\BackendController
$searchModel->search(Yii::$app->request->queryParams); $searchModel->search(Yii::$app->request->queryParams);
$mpdf=new \mPDF('utf-8', 'A4-L'); $mpdf= MpdfUtil::createMpdfWith6XConstructor('utf-8', 'A4-L');
$stylesheet = file_get_contents( \Yii::getAlias('@vendor'.'/bower/bootstrap/dist/css/bootstrap.css')); // external css $stylesheet = file_get_contents( \Yii::getAlias('@vendor'.'/bower/bootstrap/dist/css/bootstrap.css')); // external css
$mpdf->WriteHTML($stylesheet,1); $mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($this->renderPartial('_result_sale', [ $mpdf->WriteHTML($this->renderPartial('_result_sale', [

View File

@ -10,6 +10,7 @@ use yii\web\Controller;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use common\components\DetStatProcessor; use common\components\DetStatProcessor;
use common\components\MpdfUtil;
use backend\models\DestaUploadForm; use backend\models\DestaUploadForm;
use yii\web\UploadedFile; use yii\web\UploadedFile;
use yii\data\ArrayDataProvider; use yii\data\ArrayDataProvider;
@ -282,7 +283,7 @@ class UgiroController extends Controller {
} }
protected function downloadUgiroPdf($model) { protected function downloadUgiroPdf($model) {
$mpdf = new \mPDF ( 'utf-8', 'A4-L' ); $mpdf = MpdfUtil::createMpdfWith6XConstructor ( 'utf-8', 'A4-L' );
$fn = "köteg.". $model->id_ugiro . ".pdf"; $fn = "köteg.". $model->id_ugiro . ".pdf";
$mpdf->useSubstitutions = false; $mpdf->useSubstitutions = false;

View File

@ -2,14 +2,16 @@
namespace backend\controllers; namespace backend\controllers;
use common\models\Trainer;
use common\models\UserTrainerAssignment;
use Yii; use Yii;
use common\models\User; use common\models\User;
use backend\models\UserSearch; use backend\models\UserSearch;
use backend\models\UserCreate; use backend\models\UserCreate;
use yii\web\BadRequestHttpException;
use yii\web\Controller; use yii\web\Controller;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use yii\base\Object;
use backend\models\UserUpdate; use backend\models\UserUpdate;
use common\models\Account; use common\models\Account;
use common\models\UserAccountAssignment; use common\models\UserAccountAssignment;
@ -86,10 +88,12 @@ class UserController extends \backend\controllers\BackendController
$model = new UserCreate(); $model = new UserCreate();
$accounts = Account::readAccounts(); $accounts = Account::readAccounts();
$trainers = Trainer::find()->all();
if ($model->load(Yii::$app->request->post()) && $model->save()) { if ($model->load(Yii::$app->request->post()) && $model->save()) {
$this->updateAccountAssignments($model); $this->updateAccountAssignments($model);
$this->updateTrainerAssignments($model);
return $this->redirect(['index' ]); return $this->redirect(['index' ]);
@ -98,15 +102,16 @@ class UserController extends \backend\controllers\BackendController
return $this->render('create', [ return $this->render('create', [
'model' => $model, 'model' => $model,
'accounts' => $accounts, 'accounts' => $accounts,
'trainers' => $trainers,
]); ]);
} }
public function updateAccountAssignments($model){ public function updateAccountAssignments($model){
echo "saving accounts"; echo "saving accounts";
UserAccountAssignment::deleteAll(['id_user' => $model->id]); UserAccountAssignment::deleteAll(['id_user' => $model->id]);
foreach ( $model->selected_accounts as $id_account ){ foreach ( $model->selected_accounts as $id_account ){
echo "saving account";
$uaa = new UserAccountAssignment(); $uaa = new UserAccountAssignment();
$uaa->id_user = $model->id; $uaa->id_user = $model->id;
$uaa->id_account = $id_account; $uaa->id_account = $id_account;
@ -115,6 +120,18 @@ class UserController extends \backend\controllers\BackendController
} }
public function updateTrainerAssignments($model){
UserTrainerAssignment::deleteAll(['id_user' => $model->id]);
foreach ( $model->selected_trainers as $id_trainer ){
$uaa = new UserTrainerAssignment();
$uaa->id_user = $model->id;
$uaa->id_trainer = $id_trainer;
$uaa->save();
}
}
/** /**
* Updates an existing User model. * Updates an existing User model.
* If update is successful, the browser will be redirected to the 'view' page. * If update is successful, the browser will be redirected to the 'view' page.
@ -138,19 +155,22 @@ class UserController extends \backend\controllers\BackendController
} }
$accounts = Account::readAccounts(); $accounts = Account::readAccounts();
$this->applyAccounts($model); $this->applyAccounts($model);
$trainers = Trainer::find()->all();
$this->applyTrainers($model);
if ($model->load(Yii::$app->request->post()) && $model->save()) { if ($model->load(Yii::$app->request->post()) && $model->save()) {
$this->updateAccountAssignments($model); $this->updateAccountAssignments($model);
$this->updateTrainerAssignments($model);
return $this->redirect(['view', 'id' => $model->id]); return $this->redirect(['view', 'id' => $model->id]);
} else {
} }
return $this->render('update', [ return $this->render('update', [
'model' => $model, 'model' => $model,
'accounts' => $accounts, 'accounts' => $accounts,
'trainers' => $trainers,
]); ]);
} }
@ -161,6 +181,13 @@ class UserController extends \backend\controllers\BackendController
} }
} }
private function applyTrainers($model ){
$assignedTrainers = $model->userTrainerAssignments;
foreach ($assignedTrainers as $acc ){
$model->selected_trainers[] = $acc->id_trainer;
}
}
/** /**
* Deletes an existing User model. * Deletes an existing User model.
* If deletion is successful, the browser will be redirected to the 'index' page. * If deletion is successful, the browser will be redirected to the 'index' page.

View File

@ -8,7 +8,7 @@ use backend\models\WarehouseSearch;
use yii\web\Controller; use yii\web\Controller;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use yii\base\Object; use yii\base\BaseObject;
/** /**
* WarehouseController implements the CRUD actions for Warehouse model. * WarehouseController implements the CRUD actions for Warehouse model.

View File

@ -62,7 +62,7 @@ class InventoryItemSearch extends InventoryItem
'inventory_item.created_at as item_created_at', 'inventory_item.created_at as item_created_at',
new Expression('case when inventory_item.id_product is null then inventory_group.name else product.name end as item_name'), new Expression('case when inventory_item.id_product is null then inventory_group.name else product.name end as item_name'),
'user.username as user_username', 'user.username as user_username',
'coalesce(inventory_item.count_prev ,0)as item_count_prev', 'coalesce(inventory_item.count_prev ,0) as item_count_prev',
'coalesce(inventory_item.count_in,0) as item_count_in', 'coalesce(inventory_item.count_in,0) as item_count_in',
'coalesce(inventory_item.count_sold,0) as item_count_sold', 'coalesce(inventory_item.count_sold,0) as item_count_sold',
'coalesce(inventory_item.count,0) as item_count', 'coalesce(inventory_item.count,0) as item_count',

View File

@ -0,0 +1,41 @@
<?php
namespace backend\models;
use common\models\Property;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\PropertyDefinition;
/**
* PropertyDefinitionSearch represents the model behind the search form about `common\models\PropertyDefinition`.
*/
class SettingsSearch extends Model
{
/**
* @inheritdoc
*/
public function rules()
{
return [
// [['id'], 'integer'],
// [['name', 'label', 'type', 'config', 'created_at', 'updated_at'], 'safe'],
];
}
/**
* Creates data provider instance with search query applied
*
*
* @return ActiveDataProvider
*/
public function search()
{
return $dataProvider;
}
}

View File

@ -2,6 +2,7 @@
namespace backend\models; namespace backend\models;
use common\models\HuBankAccountValidator;
use Yii; use Yii;
use yii\base\Model; use yii\base\Model;
use common\models\Card; use common\models\Card;
@ -22,18 +23,41 @@ class TicketInstallmentMarkForSendForm extends Model{
public function rules(){ public function rules(){
return [ return [
['items', 'each', 'rule' => ['integer']], ['items', 'each', 'rule' => ['integer']],
['items', 'validateBankAccount'],
]; ];
} }
public function validateBankAccount($attribute, $params){
$items = TicketInstallmentRequest::find()->andWhere([
'in', 'id_ticket_installment_request' , $this->items
])->all();
\Yii::info("validateBankAccount:". count($items));
$validator = new HuBankAccountValidator();
foreach($items as $item){
\Yii::info("validateBankAccount2:". $item->id_ticket_installment_request);
/** @var Customer $customer */
$customer = $item->customer;
\Yii::info("validateBankAccount3:". $customer->username);
$isBankAccountValid = $validator->validate($customer->bank_account);
if (!$isBankAccountValid){
$errorMessage = "";
$errorMessage .= "Vendég=".$customer->name;
$errorMessage .= "; Kártya=".$customer->card->number;
$errorMessage .= "; Megbízás=".$item->id_ticket_installment_request;
$this->addError('items', "Hibás bankszámlaszám:" .$errorMessage );
}
}
}
public function markForSend(){ public function markForSend(){
\Yii::info("mark for send");
if ( $this->validate() && isset($this->items ) && is_array($this->items ) ){ if ( $this->validate() && isset($this->items ) && is_array($this->items ) ){
$updated = 0; $updated = 0;
$updated = TicketInstallmentRequest::updateAll(['status' => TicketInstallmentRequest::$STATUS_MARKED_TO_SEND ],['in', 'id_ticket_installment_request' , $this->items]); $updated = TicketInstallmentRequest::updateAll(['status' => TicketInstallmentRequest::$STATUS_MARKED_TO_SEND ],['in', 'id_ticket_installment_request' , $this->items]);
\Yii::$app->session->setFlash('success', $updated . " megbízás küldésre jelölve " ); \Yii::$app->session->setFlash('success', $updated . " megbízás küldésre jelölve " );
}else{ }else{
\Yii::$app->session->setFlash('success', " Nem történt küldésre jelölés! " ); \Yii::$app->session->setFlash('error', " Nem történt küldésre jelölés! " . $this->getFirstError('items') );
} }
} }

View File

@ -7,7 +7,7 @@ use yii\base\Model;
use yii\data\ActiveDataProvider; use yii\data\ActiveDataProvider;
use common\models\Transfer; use common\models\Transfer;
use yii\db\Expression; use yii\db\Expression;
use yii\base\Object; use yii\base\BaseObject;
use yii\db\Query; use yii\db\Query;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
use common\components\Helper; use common\components\Helper;

View File

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

View File

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

View File

@ -9,6 +9,7 @@ class UserCreate extends User{
public $password_plain; public $password_plain;
public $password_repeat; public $password_repeat;
public $selected_accounts = []; public $selected_accounts = [];
public $selected_trainers = [];
public $role; public $role;
@ -25,6 +26,12 @@ class UserCreate extends User{
} }
} }
], ],
['selected_trainers',function ($attribute, $params) {
if (!is_array($this->$attribute)) {
$this->addError($attribute, 'Invalid array');
}
}
],
['email' ,'email' ], ['email' ,'email' ],
['email' ,'unique' ], ['email' ,'unique' ],
['username' ,'unique' ], ['username' ,'unique' ],

View File

@ -9,6 +9,7 @@ class UserUpdate extends User {
public $password_plain; public $password_plain;
public $password_repeat; public $password_repeat;
public $selected_accounts = []; public $selected_accounts = [];
public $selected_trainers = [];
public $role; public $role;
@ -21,16 +22,24 @@ class UserUpdate extends User {
return [ return [
[['username','email'], 'required' ], [['username','email'], 'required' ],
['email' ,'email' ], ['email' ,'email' ],
['email' ,'unique' , 'targetClass' => User::className(), 'targetAttribute' => 'email'], // ['email' ,'unique' , 'targetClass' => User::className(), 'targetAttribute' => 'email'],
['username' ,'unique', 'targetClass' => User::className(), 'targetAttribute' => 'username'], // ['username' ,'unique', 'targetClass' => User::className(), 'targetAttribute' => 'username'],
[['password_plain' ,'password_repeat'] ,'string','min' =>6 ], [['password_plain' ,'password_repeat'] ,'string','min' =>6 ],
[['password_repeat'] ,'validatePasswordRepeat' ], [['password_repeat'] ,'validatePasswordRepeat' ],
[['username'] ,'validateUsername' ],
[['email'] ,'validateEmail' ],
['selected_accounts',function ($attribute, $params) { ['selected_accounts',function ($attribute, $params) {
if (!is_array($this->$attribute)) { if (!is_array($this->$attribute)) {
$this->addError($attribute, 'Invalid array'); $this->addError($attribute, 'Invalid array');
} }
} }
], ],
['selected_trainers',function ($attribute, $params) {
if (!is_array($this->$attribute)) {
$this->addError($attribute, 'Invalid array');
}
}
],
[['role'], 'required'], [['role'], 'required'],
[['role'], 'string', 'max' => 20], [['role'], 'string', 'max' => 20],
@ -40,6 +49,32 @@ class UserUpdate extends User {
]; ];
} }
// public function validateEmail($attribute, $params){
// /** @var User $user */
// $user = User::find()
// ->andWhere(['email' => $this->email])->one();
//
// if (isset($user)){
// if ( $user->id != $this->id ){
// $this->addError($attribute,'Az email cím már használatban van!');
// }
// }
//
// }
//
// public function validateUsername($attribute, $params){
// /** @var User $user */
// $user = User::find()
// ->andWhere(['username' => $this->username])->one();
//
// if (isset($user)){
// if ( $user->id != $this->id ){
// $this->addError($attribute,'A felhasználónév már használatban van!');
// }
// }
//
// }
/** /**
* @formatter:on * @formatter:on
*/ */
@ -52,6 +87,28 @@ class UserUpdate extends User {
} }
} }
} }
public function validateEmail($attribute, $params) {
if (! $this->hasErrors ()) {
if ( !empty($this->email) ){
$user = User::findOne(['email' => $this->email]);
if ( isset($user) && $user->id != $this->id){
$this->addError ( $attribute, "Az email már használatban van (".$user->username.")");
}
}
}
}
public function validateUsername($attribute, $params) {
if (! $this->hasErrors ()) {
if ( !empty($this->email) ){
$user = User::findOne(['username' => $this->username]);
if ( isset($user) && $user->id != $this->id){
$this->addError ( $attribute, "A felhasználónév már használatban van (".$user->username.")");
}
}
}
}
public function attributeLabels() { public function attributeLabels() {
return [ return [

View File

@ -1,5 +1,6 @@
<?php <?php
use common\models\EventType;
use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
@ -8,11 +9,28 @@ use yii\widgets\ActiveForm;
/* @var $form yii\widgets\ActiveForm */ /* @var $form yii\widgets\ActiveForm */
?> ?>
<style>
select.form-control, option{
color: #fff;
}
</style>
<script>
function setThemeColor(elem){
elem.className = 'form-control event-theme-active-' +elem.value;
}
</script>
<div class="event-type-form"> <div class="event-type-form">
<?php $form = ActiveForm::begin(); ?> <?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?> <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'theme')->dropDownList(EventType::themes(),
['onchange' => "setThemeColor(this);"]) ?>
<div class="form-group"> <div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('event-type', 'Create') : Yii::t('event-type', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> <?= Html::submitButton($model->isNewRecord ? Yii::t('event-type', 'Create') : Yii::t('event-type', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
@ -21,3 +39,16 @@ use yii\widgets\ActiveForm;
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>
</div> </div>
<script type="text/javascript">
let themeDropDown = document.getElementById("eventtype-theme");
let themeOptions = themeDropDown.getElementsByTagName("option");
for (let item of themeOptions) {
item.classList.add("event-theme-active-"+item.value)
}
setThemeColor(themeDropDown);
console.info("selected: "+ themeDropDown.value);
</script>

View File

@ -26,7 +26,20 @@ $this->params['breadcrumbs'][] = $this->title;
'name', 'name',
'created_at:datetime', 'created_at:datetime',
'updated_at:datetime', 'updated_at:datetime',
[
'attribute' => 'theme',
'label' => 'Színtéma',
'value' => function ($model, $key, $index, $column){
$result = "";
if ( isset( $model['theme'] )){
$box = "<span style='margin-right: 0.3rem; height: 1rem; width: 1rem; display: inline-block;' class='event-theme-active-".$model['theme']."'></span>";
$name = "Színtéma " . ($model['theme']+1);
$result = $box . $name;
}
return $result;
},
'format' => 'raw'
],
['class' => 'yii\grid\ActionColumn', ['class' => 'yii\grid\ActionColumn',
'template' => '{view} {update}' 'template' => '{view} {update}'
], ],

View File

@ -30,6 +30,10 @@ $this->params['breadcrumbs'][] = $this->title;
'attributes' => [ 'attributes' => [
'id', 'id',
'name', 'name',
[
'label'=> 'Színtéma',
'value' => ( isset($model->theme) ? 'Színtéma ' . ($model->theme+1) : '-' )
],
'created_at', 'created_at',
'updated_at', 'updated_at',
], ],

View File

@ -0,0 +1,42 @@
<?php
/** @var common\models\PropertySettingModel[] $settings */
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<div class="room-form">
<?php $form = ActiveForm::begin(); ?>
<?php
$index = 0;
foreach ($settings as $setting) {
?>
<div class="row">
<div class="col-lg-3">
<?= $setting->label . ":" ?>
</div>
<div class="col-lg-3">
<?= $form->field($setting, "[$index]value")->textInput(['maxlength' => true, 'label' => false])->label(false) ?>
</div>
</div>
<?php
$index++;
} ?>
<div class="form-group">
<?= Html::submitButton("Mentés", ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>

View File

@ -4,7 +4,7 @@ use yii\helpers\Html;
use yii\grid\GridView; use yii\grid\GridView;
use yii\widgets\DetailView; use yii\widgets\DetailView;
use yii\base\Widget; use yii\base\Widget;
use yii\base\Object; use yii\base\BaseObject;
use yii\data\ArrayDataProvider; use yii\data\ArrayDataProvider;
use common\components\AccountStatisticWidget; use common\components\AccountStatisticWidget;
use common\components\DataProviderTotal; use common\components\DataProviderTotal;

View File

@ -4,7 +4,7 @@ use yii\helpers\Html;
use yii\grid\GridView; use yii\grid\GridView;
use yii\widgets\DetailView; use yii\widgets\DetailView;
use yii\base\Widget; use yii\base\Widget;
use yii\base\Object; use yii\base\BaseObject;
use yii\data\ArrayDataProvider; use yii\data\ArrayDataProvider;
use common\components\AccountStatisticWidget; use common\components\AccountStatisticWidget;
use common\components\DataProviderTotal; use common\components\DataProviderTotal;

View File

@ -1,5 +1,8 @@
<?php <?php
use backend\models\UserUpdate;
use common\models\Account;
use common\models\Trainer;
use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
use yii\grid\GridView; use yii\grid\GridView;
@ -8,8 +11,10 @@ use common\components\RoleDefinition;
use common\models\User; use common\models\User;
/* @var $this yii\web\View */ /* @var $this yii\web\View */
/* @var $model common\models\User */ /* @var $model UserUpdate */
/* @var $form yii\widgets\ActiveForm */ /* @var $form yii\widgets\ActiveForm */
/* @var $trainers Trainer[] */
/* @var $accounts Account[] */
?> ?>
<?php <?php
@ -35,6 +40,7 @@ asort($roleOptions);
<?php <?php
$selectedAccounts = $model->selected_accounts; $selectedAccounts = $model->selected_accounts;
$selectedTrainers = $model->selected_trainers;
?> ?>
@ -67,8 +73,40 @@ asort($roleOptions);
[ 'attribute' => 'name' ], [ 'attribute' => 'name' ],
], ],
])?> ])?>
<h3>Engedélyezett edzők</h3>
<?php echo GridView::widget([
'dataProvider' => new ArrayDataProvider( [
'allModels' => $trainers,
'sort' => false,
'pagination' => false,
]),
'columns' => [
[
'class' => 'yii\grid\CheckboxColumn',
'name' => (new ReflectionClass( $model->classname() ))->getShortName() . '[selected_trainers]',
'checkboxOptions' => function ($model, $key, $index, $column) use ($selectedTrainers){
$result = [];
$result['value'] = $model->id ;
if ( isset($selectedTrainers) ){
if ( is_array($selectedTrainers) ){
if ( array_search($model->id , $selectedTrainers ) !== false){
$result['checked'] = 'checked' ;
}
}
}
return $result;
}
],
[ 'attribute' => 'name' ],
],
])?>
<div class="form-group"> <div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Mentés') : Yii::t('app', 'Mentés'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> <?= Html::submitButton( Yii::t('app', 'Mentés'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div> </div>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>

View File

@ -17,6 +17,7 @@ $this->params['breadcrumbs'][] = $this->title;
<?= $this->render('_form', [ <?= $this->render('_form', [
'model' => $model, 'model' => $model,
'accounts' => $accounts, 'accounts' => $accounts,
'trainers' => $trainers,
]) ?> ]) ?>
</div> </div>

View File

@ -16,7 +16,8 @@ $this->params['breadcrumbs'][] = Yii::t('backend/user', 'Update');
<?= $this->render('_form', [ <?= $this->render('_form', [
'model' => $model, 'model' => $model,
'accounts' => $accounts 'accounts' => $accounts,
'trainers' => $trainers,
]) ?> ]) ?>
</div> </div>

View File

@ -89,3 +89,35 @@ a.desc:after {
padding: 10px 20px; padding: 10px 20px;
margin: 0 0 15px 0; margin: 0 0 15px 0;
} }
.event-theme-active-0 {
background-color: #ECB809 !important;
}
.event-theme-active-1 {
background-color: #AE173B !important;
}
.event-theme-active-2 {
background-color: #DF429B !important;
}
.event-theme-active-3 {
background-color: #B929B1 !important;
}
.event-theme-active-4 {
background-color: #3EBFAE !important;
}
.event-theme-active-5 {
background-color: #6594D1 !important;
}
.event-theme-active-6 {
background-color: #F1591A !important;
}
.event-theme-active-7 {
background-color: #30B211 !important;
}
.event-theme-active-8 {
background-color: #E82A36 !important;
}
.event-theme-active-9 {
background-color: #98701E !important;
}

View File

@ -8,7 +8,7 @@ class WebcamjsAsset extends AssetBundle
public $sourcePath = '@bower'; public $sourcePath = '@bower';
public $js = [ public $js = [
'webcamjs/webcam.min.js' 'webcamjs/webcam.js'
]; ];
public $depends = [ public $depends = [

View File

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

View File

@ -4,7 +4,7 @@ namespace common\components;
use common\models\Transfer; use common\models\Transfer;
use yii\base\Object; use yii\base\BaseObject;
use common\models\MessageDetstaLab; use common\models\MessageDetstaLab;
use common\models\MessageDetstaTetel; use common\models\MessageDetstaTetel;
use common\models\MessageDetsta; use common\models\MessageDetsta;
@ -16,7 +16,7 @@ use common\models\TicketInstallmentRequest;
* @property common\models\Ugiro $koteg * @property common\models\Ugiro $koteg
* @property common\models\giro\GiroDETSTA $giroDETSTA * @property common\models\giro\GiroDETSTA $giroDETSTA
*/ */
class DetStaDBSave extends Object class DetStaDBSave extends BaseObject
{ {
/** /**

View File

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

View File

@ -3,7 +3,7 @@
namespace common\components; namespace common\components;
use common\models\Transfer; use common\models\Transfer;
use yii\base\Object; use yii\base\BaseObject;
use common\models\TicketInstallmentRequest; use common\models\TicketInstallmentRequest;
use common\components\giro\GiroDETSTATetel; use common\components\giro\GiroDETSTATetel;
use common\models\Account; 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 * A válasz tétel . Ha nincs megadva, automatikus visszautasítjuk a megbízást
* */ * */

View File

@ -4,7 +4,7 @@ namespace common\components;
use common\models\Card; use common\models\Card;
class FreeUniqueCardNumberGenerator extends \yii\base\Object { class FreeUniqueCardNumberGenerator extends \yii\base\BaseObject {
public $count; public $count;
public $keyset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; public $keyset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
public $length = 6; public $length = 6;

View File

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

View File

@ -400,6 +400,14 @@ class Helper {
return !Helper::isReceptionTransferListToday(); return !Helper::isReceptionTransferListToday();
} }
public static function getGroupTrainingUrl(){
return \Yii::$app->params['group_training.url'];
}
public static function getGroupTrainingRegistrationCancelLimitMinutes(){
return \Yii::$app->params['group_training.registration.cancel.limit.minutes'];
}
public static function getRealUserIp() { public static function getRealUserIp() {
$client = @$_SERVER ['HTTP_CLIENT_IP']; $client = @$_SERVER ['HTTP_CLIENT_IP'];
$forward = @$_SERVER ['HTTP_X_FORWARDED_FOR']; $forward = @$_SERVER ['HTTP_X_FORWARDED_FOR'];
@ -530,4 +538,9 @@ class Helper {
return $result; return $result;
} }
public static function isRestAllowVerifyOnly() {
return \Yii::$app->params ['rest_allow_verify_only'] == true;
}
} }

View File

@ -1,4 +1,5 @@
<?php <?php
namespace common\components; namespace common\components;
use Yii; use Yii;
@ -16,7 +17,8 @@ class Image
* @param unknown $resizeWidth * @param unknown $resizeWidth
* @param unknown $resizeHeight * @param unknown $resizeHeight
* @param bool $resizeCrop * @param bool $resizeCrop
* @throws HttpException*/ * @throws HttpException
*/
public static function upload(UploadedFile $fileInstance, $dir = '', $resizeWidth = null, $resizeHeight = null, $resizeCrop = false) public static function upload(UploadedFile $fileInstance, $dir = '', $resizeWidth = null, $resizeHeight = null, $resizeCrop = false)
{ {
$fileName = Upload::getUploadPath($dir) . DIRECTORY_SEPARATOR . Upload::getFileName($fileInstance); $fileName = Upload::getUploadPath($dir) . DIRECTORY_SEPARATOR . Upload::getFileName($fileInstance);
@ -25,27 +27,27 @@ class Image
? self::copyResizedImage($fileInstance->tempName, $fileName, $resizeWidth, $resizeHeight, $resizeCrop) ? self::copyResizedImage($fileInstance->tempName, $fileName, $resizeWidth, $resizeHeight, $resizeCrop)
: $fileInstance->saveAs($fileName); : $fileInstance->saveAs($fileName);
if(!$uploaded){ if (!$uploaded) {
throw new HttpException(500, 'Cannot upload file "'.$fileName.'". Please check write permissions.'); throw new HttpException(500, 'Cannot upload file "' . $fileName . '". Please check write permissions.');
} }
return Upload::getLink($fileName); return Upload::getLink($fileName);
} }
public static function saveBinary($binary_data, $dir = '') public static function saveBinary($binary_data, $dir = '')
{ {
$fileName = Upload::getUploadPath($dir) . DIRECTORY_SEPARATOR . Upload::genFileName("jpg"); $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){ if (!$uploaded) {
throw new HttpException(500, 'Cannot upload file "'.$fileName.'". Please check write permissions.'); throw new HttpException(500, 'Cannot upload file "' . $fileName . '". Please check write permissions.');
} }
return Upload::getLink($fileName); return Upload::getLink($fileName);
} }
/** /**
* *
* @param unknown $filename * @param unknown $filename
@ -56,16 +58,14 @@ class Image
*/ */
static function thumb($filename, $width = null, $height = null, $crop = true) 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); $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; $thumbFile = Yii::getAlias('@frontend/web') . DIRECTORY_SEPARATOR . Upload::$UPLOADS_DIR . DIRECTORY_SEPARATOR . 'thumbs' . DIRECTORY_SEPARATOR . $thumbName;
$thumbWebFile = '/' . Upload::$UPLOADS_DIR . '/thumbs/' . $thumbName; $thumbWebFile = '/' . Upload::$UPLOADS_DIR . '/thumbs/' . $thumbName;
if(file_exists($thumbFile)){ if (file_exists($thumbFile)) {
return $thumbWebFile; 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; return $thumbWebFile;
} }
} }
@ -74,12 +74,12 @@ class Image
static function copyResizedImage($inputFile, $outputFile, $width, $height = null, $crop = true) static function copyResizedImage($inputFile, $outputFile, $width, $height = null, $crop = true)
{ {
if (extension_loaded('gd')) if (extension_loaded('gd')) {
{ try {
$image = new GD($inputFile); $image = new GD($inputFile);
if($height) { if ($height) {
if($width && $crop){ if ($width && $crop) {
$image->cropThumbnail($width, $height); $image->cropThumbnail($width, $height);
} else { } else {
$image->resize($width, $height); $image->resize($width, $height);
@ -88,25 +88,24 @@ class Image
$image->resize($width); $image->resize($width);
} }
return $image->save($outputFile); return $image->save($outputFile);
} catch (\Exception $e) {
\Yii::error("Failed to create thumbnail: ". $e->getMessage());
} }
elseif(extension_loaded('imagick')) } elseif (extension_loaded('imagick')) {
{
$image = new \Imagick($inputFile); $image = new \Imagick($inputFile);
if($height && !$crop) { if ($height && !$crop) {
$image->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1, true); $image->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1, true);
} } else {
else{
$image->resizeImage($width, null, \Imagick::FILTER_LANCZOS, 1); $image->resizeImage($width, null, \Imagick::FILTER_LANCZOS, 1);
} }
if($height && $crop){ if ($height && $crop) {
$image->cropThumbnailImage($width, $height); $image->cropThumbnailImage($width, $height);
} }
return $image->writeImage($outputFile); return $image->writeImage($outputFile);
} } else {
else {
throw new HttpException(500, 'Please install GD or Imagick extension'); 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; namespace common\components;
use yii\base\Object; use yii\base\BaseObject;
use yii\db\Query; use yii\db\Query;
use common\models\Product; use common\models\Product;
use yii\data\ActiveDataProvider; use yii\data\ActiveDataProvider;
@ -14,7 +14,7 @@ use common\models\Transfer;
* @property common\models\Account $account a kassza * @property common\models\Account $account a kassza
* @property common\models\Product[] $products a termékek * @property common\models\Product[] $products a termékek
* */ * */
class ProductInventory extends Object{ class ProductInventory extends BaseObject{

View File

@ -1,75 +1,87 @@
<?php <?php
namespace common\components; namespace common\components;
use \Yii; use \Yii;
class RoleDefinition{ class RoleDefinition
{
public static $ROLE_ADMIN = "admin";
public static $ROLE_RECEPTION = "reception";
public static $ROLE_EMPLOYEE = "employee";
public static $ROLE_TRAINER = "trainer";
public static function roleLabels()
public static function roleLabels(){ {
return [ return [
'reception' => Yii::t('common/role' ,'Reception'), 'reception' => Yii::t('common/role', 'Reception'),
'admin' => Yii::t('common/role' ,'Administrator'), 'admin' => Yii::t('common/role', 'Administrator'),
'employee' => Yii::t('common/role' ,'Employee'), 'employee' => Yii::t('common/role', 'Employee'),
'Trainer' => Yii::t('common/role' ,'Edző'), 'Trainer' => Yii::t('common/role', 'Edző'),
]; ];
} }
public static function getRoleLabel($role){ public static function getRoleLabel($role)
{
$result = null; $result = null;
$roleLabels = self::roleLabels(); $roleLabels = self::roleLabels();
if ( array_key_exists($role, $roleLabels)){ if (array_key_exists($role, $roleLabels)) {
$result = $roleLabels[$role]; $result = $roleLabels[$role];
} }
return $result; return $result;
} }
public static function roleDefinitions(){ public static function roleDefinitions()
{
return [ return [
'employee' => [ 'employee' => [
'canAllow' => [ 'employee'], 'canAllow' => ['employee'],
], ],
'admin' => [ 'admin' => [
'canAllow' => ['admin','reception','employee'], 'canAllow' => ['admin', 'reception', 'employee'],
], ],
'reception' => [ 'reception' => [
'canAllow' => [ ], 'canAllow' => [],
], ],
]; ];
} }
public static function getRoleDefinition($role){ public static function getRoleDefinition($role)
{
$defs = self::roleDefinitions(); $defs = self::roleDefinitions();
$result = null; $result = null;
if ( array_key_exists($role, $defs)){ if (array_key_exists($role, $defs)) {
$result = $defs[$role]; $result = $defs[$role];
} }
$result = $defs[$role]; $result = $defs[$role];
return $result; return $result;
} }
public static function getRolesCanAllow($role){ public static function getRolesCanAllow($role)
{
$result = []; $result = [];
$def = self::getRoleDefinition($role); $def = self::getRoleDefinition($role);
if ( isset($def)){ if (isset($def)) {
$result = $def['canAllow']; $result = $def['canAllow'];
} }
return $result; return $result;
} }
public static function can($role){ public static function can($role)
{
$result = false; $result = false;
if ( !Yii::$app->user->isGuest ){ if (!Yii::$app->user->isGuest) {
if ( isset( $role)){ if (isset($role)) {
if ( is_array($role)){ if (is_array($role)) {
foreach ($role as $r){ foreach ($role as $r) {
$result |= Yii::$app->user->can($r); $result |= Yii::$app->user->can($r);
} }
}else if ( is_string($role)){ } else if (is_string($role)) {
$result = Yii::$app->user->can($role); $result = Yii::$app->user->can($role);
} }
} }
@ -77,37 +89,54 @@ class RoleDefinition{
return $result; return $result;
} }
public static function isAdmin(){ public static function canAny($roles)
{
foreach ($roles as $role) {
if (self::can($role)) {
return true;
}
}
return false;
}
public static function isAdmin()
{
return self::can('admin'); return self::can('admin');
} }
public static function isReception(){ public static function isReception()
{
return self::can('reception'); return self::can('reception');
} }
public static function isEmployee(){ public static function isEmployee()
{
return self::can('employee'); return self::can('employee');
} }
public static function isTrainer(){ public static function isTrainer()
{
return self::can('trainer'); return self::can('trainer');
} }
public static function isLoggedUser(){ public static function isLoggedUser()
{
return self::isTrainer() || self::isAdmin() || self::isEmployee() return self::isTrainer() || self::isAdmin() || self::isEmployee()
|| self::isReception(); || self::isReception();
} }
/* /*
* [ * [
* 'role1' => 'template1', * 'role1' => 'template1',
* 'role2' => 'template2, * 'role2' => 'template2,
* ] * ]
* */ * */
public static function getRoleTemplate($templates){ public static function getRoleTemplate($templates)
{
$result = ""; $result = "";
foreach ($templates as $role => $template ){ foreach ($templates as $role => $template) {
if ( Yii::$app->user->can($role)){ if (Yii::$app->user->can($role)) {
$result = $template; $result = $template;
break; break;
} }

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*/ /**Current user*/
public $idUser = null; public $idUser = null;

View File

@ -2,16 +2,17 @@
namespace common\components\accountstate; namespace common\components\accountstate;
use yii\base\Object;
use common\models\User; use common\models\User;
use common\models\Account; use common\models\Account;
use common\models\AccountState; use common\models\AccountState;
use common\components\DailyListing; use common\components\DailyListing;
use common\components\MpdfUtil;
use yii\base\BaseObject;
/** /**
* @property common\models\AccountState $model * @property common\models\AccountState $model
* */ * */
class AccountStateMail extends Object { class AccountStateMail extends BaseObject {
public $controller; public $controller;
@ -76,7 +77,7 @@ class AccountStateMail extends Object {
protected function attachPdf(){ protected function attachPdf(){
$mpdf=new \mPDF('utf-8', 'A4-L'); $mpdf= MpdfUtil::createMpdfWith6XConstructor('utf-8', 'A4-L');
$mpdf->useSubstitutions=false; $mpdf->useSubstitutions=false;
$mpdf->simpleTables = true; $mpdf->simpleTables = true;
$mpdf->SetHeader( \Yii::$app->params[ "company_name" ] . " - Létrehozva: " .$user->username . ", ".\Yii::$app->formatter->asDatetime(time()) ); $mpdf->SetHeader( \Yii::$app->params[ "company_name" ] . " - Létrehozva: " .$user->username . ", ".\Yii::$app->formatter->asDatetime(time()) );

View File

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

View File

@ -64,5 +64,7 @@ return [
'ticket_type_door_allowed_check_on' => false, 'ticket_type_door_allowed_check_on' => false,
'warn_ticket_expire_in_days_count' => 3, 'warn_ticket_expire_in_days_count' => 3,
'warn_ticket_expire_in_usage_count' => 3, 'warn_ticket_expire_in_usage_count' => 3,
'inventory.products.only.active' => true 'inventory.products.only.active' => true,
'group_training.url' => 'https://fitnessadmin.hu',
'group_training.registration.cancel.limit.minutes' => 60
]; ];

View File

@ -0,0 +1,55 @@
<?php
namespace common\helpers;
class AppArrayHelper
{
public static function mapValues($array, $func){
$result = [];
foreach ($array as $item){
$result[] = $func($item);
}
return $result;
}
public static function objectArrayToMap($array, $funcGetId, $funcGetValue){
$result = [];
foreach ($array as $item ){
$id = $funcGetId($item);
$value = $funcGetValue($item);
$result[$id] = $value;
}
return $result;
}
/**
* Map an array of object by object id
* [obj1,obj2] => [obj1.id => obj1,obj2.id => obj2]
* @param $array
* @return array
*/
public static function objectArrayToMapById($array){
return AppArrayHelper::objectArrayToMap(
$array,
function ($item){
return $item->id;
},
function ($item){
return $item;
}
);
}
public static function getOrDefault($array, $key, $defaultValue = null){
if ( isset($array[$key])){
return $array[$key];
}
return $defaultValue;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace common\helpers;
class AppDateTimeHelper
{
public static function convertMySqlDatetimeToPhpInteger($dateString){
if (!isset($dateString) || empty($dateString)){
return null;
}
$unixTime = strtotime($dateString . " UTC");
return $unixTime;
}
public static function convertUnixTimeToDateTime($unixTime){
$result = new \DateTime();
$result->setTimestamp($unixTime);
$result->setTimeZone(new \DateTimeZone("UTC"));
return $result;
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace common\helpers;
use Yii;
use yii\filters\Cors;
class CorsCustom extends Cors
{
public function beforeAction($action){
$result = parent::beforeAction($action);
if (Yii::$app->getRequest()->getMethod() === 'OPTIONS') {
Yii::$app->getResponse()->getHeaders()->set('Allow', 'POST GET PUT');
Yii::$app->end();
}
return $result;
}
}

View File

@ -1,25 +1,28 @@
<?php <?php
use yii\helpers\Html;
use yii\helpers\Url; use frontend\models\PasswordChangeModel;
use common\components\Helper;
/* @var $model PasswordChangeModel */
?> ?>
<h1 style="font-size: 12px;">Kedves <?php echo $model->customer->name?>!</h1> <div>Kedves <?php echo $model->customer->name ?>!</div>
<p style="font-size: 12px;"> <p>
Az Ön új jelszava: Az Ön új jelszava:
</p> </p>
<ul style="font-size: 12px;"> <p>
<li> <?php echo $model->plainPassword ?>
"<?php echo $model->plainPassword ?>" </p>
</li> <p>A bejelentkezéshez kattintson a következő linkre: <a
</ul> href="<?php echo $model->groupTrainingUrl ?>"><?php echo $model->groupTrainingUrl ?></a></p>
<p style="font-size: 12px;"> <p>
Üdvözlettel: Üdvözlettel:
</p> </p>
<p style="font-size: 12px;"> <p>
<?php echo $model->companyName ?> <?php echo $model->companyName ?>
</p> </p>
<p> <p>
Ez egy automatikus e-mail üzenet, amelyre nem tud válaszolni. Ez egy automatikus e-mail üzenet, amelyre nem tud válaszolni.
</p> </p>
<?php <?php
?> ?>

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

@ -2,11 +2,14 @@
namespace common\manager; namespace common\manager;
use common\components\Helper;
use common\helpers\AppArrayHelper;
use common\models\Card; use common\models\Card;
use common\models\CardEventRegistrationForm; use common\models\CardEventRegistrationForm;
use common\models\Customer; use common\models\Customer;
use common\models\Event; use common\models\Event;
use common\models\EventRegistration; use common\models\EventRegistration;
use common\models\PropertyDefinition;
use common\models\Ticket; use common\models\Ticket;
use customerapi\models\available\EventInterval; use customerapi\models\available\EventInterval;
use customerapi\models\registrations\EventRegistrationAvailable; use customerapi\models\registrations\EventRegistrationAvailable;
@ -38,18 +41,30 @@ class EventRegistrationManager extends BaseObject
const MAX_SEAT_COUNT_EXCEEDED = 8; const MAX_SEAT_COUNT_EXCEEDED = 8;
const EVENT_UNAVAILABLE = 9; const EVENT_UNAVAILABLE = 9;
const ALREADY_REGISTERED = 10; const ALREADY_REGISTERED = 10;
const EVENT_START_DATE_IN_PAST = 11;
const EVENT_NOT_FOUND = 12;
const ALREADY_CANCELLED = 13;
const ALREADY_DELETED = 14;
const CANCEL_TIME_LIMIT_REACHED = 15;
public static $STATES = [ public static $STATES = [
self::CARD_NOT_FOUND => 'CARD_NOT_FOUND', self::CARD_NOT_FOUND => "Kártya nem található",
self::CUSTOMER_NOT_FOUND => 'CUSTOMER_NOT_FOUND', self::CUSTOMER_NOT_FOUND => "Vendég nem található",
self::TICKET_NOT_FOUND => 'TICKET_NOT_FOUND', self::TICKET_NOT_FOUND => "Bérlet nem található",
self::NO_FREE_SEATS => 'NO_FREE_SEATS', self::NO_FREE_SEATS => "Nincs szabad hely",
self::EVENT_TYPE_NOT_FOUND => 'EVENT_TYPE_NOT_FOUND', self::EVENT_TYPE_NOT_FOUND => "Esemény típus nem található",
self::TICKET_INSUFFICIENT => 'TICKET_INSUFFICIENT', self::TICKET_INSUFFICIENT => "Bérlet nem található",
self::UNKNOWN_ERROR => 'UNKNOWN_ERROR', self::UNKNOWN_ERROR => "Ismeretlen hiba",
self::MAX_SEAT_COUNT_EXCEEDED => 'MAX_SEAT_COUNT_EXCEEDED', self::MAX_SEAT_COUNT_EXCEEDED => "Nincs szabad hely",
self::EVENT_UNAVAILABLE => 'EVENT_UNAVAILABLE', self::EVENT_UNAVAILABLE => "Esemény nem elérhető",
self::ALREADY_REGISTERED => 'ALREADY_REGISTERED', self::ALREADY_REGISTERED => "Már regisztrálva van",
self::EVENT_START_DATE_IN_PAST => "Az esemény már elkezdődött",
self::EVENT_NOT_FOUND => "Esemény tnem található",
self::ALREADY_CANCELLED => "Ez a regisztráció már lemndásra került",
self::ALREADY_DELETED => "Ez a regisztráció már törlésre került",
self::CANCEL_TIME_LIMIT_REACHED => "Ez a regisztráció már nem mondható le",
]; ];
/** /**
@ -77,7 +92,7 @@ class EventRegistrationManager extends BaseObject
$activeTickets = $card->getActiveTickets(); $activeTickets = $card->getActiveTickets();
if (count($activeTickets) === 0) { if (count($activeTickets) === 0) {
throw new NotFoundHttpException('Ticket not found1', self::TICKET_NOT_FOUND); throw new BadRequestHttpException('Ticket not found1', self::TICKET_NOT_FOUND);
} }
/** @var Event $event */ /** @var Event $event */
@ -86,10 +101,16 @@ class EventRegistrationManager extends BaseObject
throw new NotFoundHttpException('Event not found: ' . $cardEventForm->event_id); throw new NotFoundHttpException('Event not found: ' . $cardEventForm->event_id);
} }
if ( isset($event->deleted_at)){ if (isset($event->deleted_at)) {
throw new BadRequestHttpException('Event deleted', self::EVENT_UNAVAILABLE); throw new BadRequestHttpException('Event deleted', self::EVENT_UNAVAILABLE);
} }
$now = strtotime("now utc");
if ($event->start < $now) {
throw new BadRequestHttpException('Event start date in past', self::EVENT_START_DATE_IN_PAST);
}
if (!$event->hasFreeSeats()) { if (!$event->hasFreeSeats()) {
throw new BadRequestHttpException('No free seats', self::NO_FREE_SEATS); throw new BadRequestHttpException('No free seats', self::NO_FREE_SEATS);
} }
@ -104,8 +125,8 @@ class EventRegistrationManager extends BaseObject
/** @var EventRegistration[] $registrations */ /** @var EventRegistration[] $registrations */
$registrations = $event->getActiveEventRegistrations()->all(); $registrations = $event->getActiveEventRegistrations()->all();
foreach ($registrations as $registration ){ foreach ($registrations as $registration) {
if ($registration->id_customer == $card->customer->id_customer){ if ($registration->id_customer == $card->customer->id_customer) {
throw new BadRequestHttpException("Already registered", self::ALREADY_REGISTERED); throw new BadRequestHttpException("Already registered", self::ALREADY_REGISTERED);
} }
} }
@ -113,12 +134,16 @@ class EventRegistrationManager extends BaseObject
$selectedTicket = $eventType->findTicketAllowingEventType($activeTickets); $selectedTicket = $eventType->findTicketAllowingEventType($activeTickets);
if (!isset($selectedTicket)) { if (!isset($selectedTicket)) {
throw new NotFoundHttpException('Ticket not found2', self::TICKET_INSUFFICIENT); throw new BadRequestHttpException('Ticket not found2', self::TICKET_INSUFFICIENT);
} }
try {
$selectedTicket->consumeReservationCount(1); $selectedTicket->consumeReservationCount(1);
} catch (\Exception $e) {
throw new BadRequestHttpException('Max ticket seat count exceeded', self::MAX_SEAT_COUNT_EXCEEDED);
}
$selectedTicket->save(); $selectedTicket->save(false);
$registration = new EventRegistration(); $registration = new EventRegistration();
$registration->id_event = $event->id; $registration->id_event = $event->id;
@ -170,57 +195,106 @@ class EventRegistrationManager extends BaseObject
* @return array|EventRegistration|ActiveRecord|null * @return array|EventRegistration|ActiveRecord|null
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
public function loadRegistration($idRegistration) public function loadRegistration($idRegistration, $idCustomer)
{ {
$query = EventRegistration::find()
$registration = EventRegistration::find()->andWhere(['id' => $idRegistration])->one(); ->andWhere(['id' => $idRegistration]);
if ( $registration === null) { if (isset($idCustomer)) {
$query->andWhere(['id_customer' => $idCustomer]);
}
$registration = $query->one();
if ($registration === null) {
throw new NotFoundHttpException('The requested registration does not exist.'); throw new NotFoundHttpException('The requested registration does not exist.');
} }
return $registration; return $registration;
} }
public function cancelRegistrationTX($registration, $idCustomer, $reason)
{
$tx = \Yii::$app->db->beginTransaction();
try {
$this->cancelRegistration($registration, $idCustomer, $reason);
$tx->commit();
} catch (\Exception $e) {
$tx->rollBack();
throw $e;
}
}
/** /**
* @param EventRegistration $registration * @param EventRegistration $registration
* @throws ServerErrorHttpException * @throws ServerErrorHttpException
*/ */
public function cancelRegistration($registration) public function cancelRegistration($registration, $idCustomer, $reason)
{ {
if (isset($idCustomer) && $registration->id_customer != $idCustomer) {
throw new NotFoundHttpException('The requested registration does not exist.');
}
if (isset($registration->canceled_at)) { if (isset($registration->canceled_at)) {
throw new ServerErrorHttpException('The registration is already canceled'); throw new BadRequestHttpException('The registration is already canceled: '.$registration->id, self::ALREADY_CANCELLED);
} }
if (isset($registration->deleted_at)) { if (isset($registration->deleted_at)) {
throw new ServerErrorHttpException('The reservation is already deleted'); throw new BadRequestHttpException('The reservation is already deleted: '.$registration->id, self::ALREADY_DELETED);
}
$event = Event::findOne($registration->id_event);
if (!isset($event)) {
throw new BadRequestHttpException('The reservation is already deleted', self::EVENT_NOT_FOUND);
}
$now = strtotime("now UTC");
if ($reason == EventRegistration::CANCEL_REASON_CUSTOMER) {
$timeUntilEventStart = $event->start - $now;
$settingsManager = new PropertySettingsManager();
$limitMinutes = $settingsManager->getSetting(
PropertyDefinition::DEFINITION_GROUP_TRAINING_CUSTOMER_CANCEL_TIME_LIMIT,
Helper::getGroupTrainingRegistrationCancelLimitMinutes()
);
if ($timeUntilEventStart <= $limitMinutes* 60) {
throw new BadRequestHttpException('The reservation can\'t be deleted', self::CANCEL_TIME_LIMIT_REACHED);
}
}
$now = strtotime("now");
// if user cancels then cancel_at will be set
if ( $reason == EventRegistration::CANCEL_REASON_CUSTOMER){
$registration->canceled_at = date('Y-m-d H:i:s', $now);
}else{
// otherwise ( e.g. event is deleted ) the delete_at will be set
$registration->deleted_at = date('Y-m-d H:i:s', $now);
} }
$registration->canceled_at = date('Y-m-d H:i:s');
$registration->save(false); $registration->save(false);
$ticket = Ticket::findOne($registration->id_ticket);
if (!isset($ticket)) {
throw new BadRequestHttpException('The ticket is not found');
}
$ticket->restoreReservationCount(1);
$ticket->save(false);
} }
/** public function findAllRegistrations($idEvent, $idCustomer = null)
* @param EventRegistration $registration
* @return bool
* @throws \yii\base\Exception
*/
public function deleteRegistration($registration)
{ {
if (isset($registration->deleted_at)) { $registrations =
return false; EventRegistration::find()
->andWhere(['id_event' => $idEvent])->all();
if (isset($idCustomer)) {
$registrations = EventRegistration::filterForCustomer($registrations, $idCustomer);
}
return $registrations;
} }
// $ticket = Ticket::findOne(['id_ticket' => $registration->id_ticket]); public function findActiveRegistrations($idEvent, $idCustomer = null)
// if( !isset($ticket ) ) { {
// throw new \yii\base\Exception('Ticket not found: ' . $registration->id_ticket); $registrations = $this->findAllRegistrations($idEvent, $idCustomer);
// } return EventRegistration::filterActive($registrations);
//
// $ticket->restoreReservationCount(1);
// $ticket->save(false);
$registration->deleted_at = date('Y-m-d H:i:s');
return $registration->save(false);
} }
/** /**
@ -235,12 +309,14 @@ class EventRegistrationManager extends BaseObject
$tx = $db->beginTransaction(); $tx = $db->beginTransaction();
try { try {
$registrations = $event->getEventRegistrations()->all(); $allRegistrations = $this->findAllRegistrations($event->id);
$activeRegistrations = $this->findActiveRegistrations($event->id);
// //////////////////////////////// // ////////////////////////////////
// if event has no registrations // if event has no registrations
// we can simply delete it from db // we can simply delete it from db
// //////////////////////////////// // ////////////////////////////////
if ( count($registrations) === 0 ) { if (count($allRegistrations) === 0) {
$event->delete(); $event->delete();
} else { } else {
// ///////////////////////////// // /////////////////////////////
@ -249,10 +325,10 @@ class EventRegistrationManager extends BaseObject
// ///////////////////////////// // /////////////////////////////
$event->deleted_at = date('Y-m-d H:i:s'); $event->deleted_at = date('Y-m-d H:i:s');
$event->save(false); $event->save(false);
foreach ($registrations as $registration) { foreach ($activeRegistrations as $registration) {
if (!isset($registration->deleted_at)) { if (!isset($registration->deleted_at)) {
/** @var EventRegistration $registration */ /** @var EventRegistration $registration */
$this->deleteRegistration($registration); $this->cancelRegistration($registration, null, EventRegistration::CANCEL_REASON_EVENT);
} }
} }
} }

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

@ -0,0 +1,86 @@
<?php
namespace common\manager;
use common\helpers\AppArrayHelper;
use common\models\Property;
use common\models\PropertyDefinition;
use common\models\PropertySetting;
use common\models\PropertySettingModel;
class PropertySettingsManager
{
/**
* @return PropertySetting[]
*/
public function getPropertySettings()
{
$settings = [];
$definitions = PropertyDefinition::find()->all();
$properties = Property::find()->all();
$propertyByDefinition = AppArrayHelper::objectArrayToMap($properties,
function ($property) {
return $property->id_property_definition;
},
function ($property) {
return $property;
}
);
foreach ($definitions as $definition) {
$setting = new PropertySetting([
'property' => AppArrayHelper::getOrDefault($propertyByDefinition, $definition->id),
'definition' => $definition
]);
$settings[] = $setting;
}
return $settings;
}
/**
* @param PropertySetting $setting
*/
public function saveSetting($setting ){
Property::deleteAll(['id_property_definition' =>$setting->definition->id ]);
$setting->property->save(false);
}
/**
* @param PropertySetting[] $setting
*/
public function saveSettings($settings ){
foreach ($settings as $setting){
Property::deleteAll(['id_property_definition' =>$setting->definition->id ]);
$setting->property->save(false);
}
}
public function getSettingsMap(){
$settings = $this->getPropertySettings();
return AppArrayHelper::objectArrayToMap($settings,
function ($setting){
return $setting->definition->name;
},
function ($setting){
return $setting->getValue();
});
}
public function getSettingFromSettingsMap($settingsMap,$key,$defaultValue = null){
return AppArrayHelper::getOrDefault(
$settingsMap,
$key,
$defaultValue
);
}
public function getSetting($key,$defaultValue = null){
$settingsMap = $this->getSettingsMap();
return $this->getSettingFromSettingsMap($settingsMap,$key,$defaultValue);
}
}

View File

@ -42,8 +42,10 @@ class Account extends \yii\db\ActiveRecord
public function behaviors() public function behaviors()
{ {
return [ return [
[ 'class' => TimestampBehavior::className(), ['class' => TimestampBehavior::className(),
'value' => function(){ return date('Y-m-d H:i:s' ); } 'value' => function () {
return date('Y-m-d H:i:s');
}
] ]
]; ];
} }
@ -55,8 +57,8 @@ class Account extends \yii\db\ActiveRecord
{ {
return [ return [
[['name', 'type'], 'required'], [['name', 'type'], 'required'],
[['name', ], 'unique'], [['name',], 'unique'],
[['status', 'type','log_card_read_in_reception'], 'integer'], [['status', 'type', 'log_card_read_in_reception'], 'integer'],
[['name'], 'string', 'max' => 64] [['name'], 'string', 'max' => 64]
]; ];
} }
@ -77,43 +79,49 @@ class Account extends \yii\db\ActiveRecord
]; ];
} }
public function getUserAccountAssignments(){ public function getUserAccountAssignments()
{
return $this->hasMany(UserAccountAssignment::className(), ['id_account' => 'id_account']); return $this->hasMany(UserAccountAssignment::className(), ['id_account' => 'id_account']);
} }
static function statuses() { static function statuses()
{
return [ return [
self::STATUS_ACTIVE => Yii::t('common/account', 'Active'), self::STATUS_ACTIVE => Yii::t('common/account', 'Active'),
self::STATUS_DELETED => Yii::t('common/account', 'Inactive'), self::STATUS_DELETED => Yii::t('common/account', 'Inactive'),
]; ];
} }
public function getStatusHuman(){ public function getStatusHuman()
{
$result = null; $result = null;
$s = self::statuses(); $s = self::statuses();
if ( array_key_exists($this->status, $s)){ if (array_key_exists($this->status, $s)) {
$result = $s[$this->status]; $result = $s[$this->status];
} }
return $result; return $result;
} }
static function types() { static function types()
{
return [ return [
self::TYPE_ALL => Yii::t('common/account', 'Account'), self::TYPE_ALL => Yii::t('common/account', 'Account'),
self::TYPE_VALUE_HIDDEN => Yii::t('common/account', 'Only the name is visible'), self::TYPE_VALUE_HIDDEN => Yii::t('common/account', 'Only the name is visible'),
]; ];
} }
public function getTypeHuman(){ public function getTypeHuman()
{
$result = null; $result = null;
$s = self::types(); $s = self::types();
if ( array_key_exists($this->type, $s)){ if (array_key_exists($this->type, $s)) {
$result = $s[$this->type]; $result = $s[$this->type];
} }
return $result; return $result;
} }
public function isInactive(){ public function isInactive()
{
return $this->status == self::STATUS_DELETED; return $this->status == self::STATUS_DELETED;
} }
@ -126,7 +134,8 @@ class Account extends \yii\db\ActiveRecord
* three arm gate, but we want to track the customers. * three arm gate, but we want to track the customers.
* @return bool * @return bool
*/ */
public function isLogCardReadInReceptionOn(){ public function isLogCardReadInReceptionOn()
{
return $this->log_card_read_in_reception == 1; return $this->log_card_read_in_reception == 1;
} }
@ -136,38 +145,41 @@ class Account extends \yii\db\ActiveRecord
* allowed for user * allowed for user
* @return array|null|\yii\db\ActiveRecord[] * @return array|null|\yii\db\ActiveRecord[]
*/ */
public static function readAccounts($forceIncludeAccount = null){ public static function readAccounts($forceIncludeAccount = null)
{
$accounts = null; $accounts = null;
if ( $forceIncludeAccount == null) { if ($forceIncludeAccount == null) {
$accounts = Account::find()->andWhere(['status' => Account::STATUS_ACTIVE])->all(); $accounts = Account::find()->andWhere(['status' => Account::STATUS_ACTIVE])->all();
}else{ } else {
$accounts = Account::find()->andWhere( ['or', ['status' => Account::STATUS_ACTIVE], ['id_account' => $forceIncludeAccount ] ])->all(); $accounts = Account::find()->andWhere(['or', ['status' => Account::STATUS_ACTIVE], ['id_account' => $forceIncludeAccount]])->all();
} }
return $accounts; return $accounts;
} }
public static function read($forceIncludeAccount = null){ public static function read($forceIncludeAccount = null)
{
$accounts = null; $accounts = null;
$query = Account::find(); $query = Account::find();
$query->innerJoinWith('userAccountAssignments'); $query->innerJoinWith('userAccountAssignments');
$query->andWhere(['user_account_assignment.id_user' => Yii::$app->user->id]); $query->andWhere(['user_account_assignment.id_user' => Yii::$app->user->id]);
if ( $forceIncludeAccount == null){ if ($forceIncludeAccount == null) {
$query->andWhere(['status' => Account::STATUS_ACTIVE])->all(); $query->andWhere(['status' => Account::STATUS_ACTIVE])->all();
}else{ } else {
$query->andWhere( ['or', ['status' => Account::STATUS_ACTIVE], ['id_account' => $forceIncludeAccount ] ])->all(); $query->andWhere(['or', ['status' => Account::STATUS_ACTIVE], ['id_account' => $forceIncludeAccount]])->all();
} }
$query->orderBy( ['name' => SORT_ASC]); $query->orderBy(['name' => SORT_ASC]);
$accounts = $query->all(); $accounts = $query->all();
return $accounts; return $accounts;
} }
public static function writeDefault($account){ public static function writeDefault($account)
{
$session = Yii::$app->session; $session = Yii::$app->session;
$session->set('id_account', $account->id_account); $session->set('id_account', $account->id_account);
@ -177,7 +189,8 @@ class Account extends \yii\db\ActiveRecord
* *
* @return int id_transfer * @return int id_transfer
* */ * */
public static function readDefault( ){ public static function readDefault()
{
$session = Yii::$app->session; $session = Yii::$app->session;
$result = $session->get('id_account'); $result = $session->get('id_account');
return $result; return $result;
@ -189,10 +202,11 @@ class Account extends \yii\db\ActiveRecord
* return the default account or null, if not found * return the default account or null, if not found
* @return \common\models\Account * @return \common\models\Account
* */ * */
public static function readDefaultObject( ){ public static function readDefaultObject()
{
$account = null; $account = null;
$id_account = self::readDefault(); $id_account = self::readDefault();
if ( isset($id_account)){ if (isset($id_account)) {
$account = Account::findOne($id_account); $account = Account::findOne($id_account);
} }
return $account; return $account;
@ -204,7 +218,8 @@ class Account extends \yii\db\ActiveRecord
* @param $idAccount integer The id of the account to read * @param $idAccount integer The id of the account to read
* @return array|null|\yii\db\ActiveRecord * @return array|null|\yii\db\ActiveRecord
*/ */
public static function readOne($idAccount){ public static function readOne($idAccount)
{
$accounts = null; $accounts = null;
$query = Account::find(); $query = Account::find();
@ -217,10 +232,10 @@ class Account extends \yii\db\ActiveRecord
return $accounts; return $accounts;
} }
public static function toAccaountMap($accounts){ public static function toAccaountMap($accounts)
return ArrayHelper::map( $accounts,'id_account','name' ); {
return ArrayHelper::map($accounts, 'id_account', 'name');
} }
} }

View File

@ -34,6 +34,7 @@ class Card extends \common\models\BaseFitnessActiveRecord
const TYPE_BARCODE = 30; const TYPE_BARCODE = 30;
const TYPE_OLD = 40; const TYPE_OLD = 40;
const TYPE_EMPLOYEE = 50; const TYPE_EMPLOYEE = 50;
const TYPE_REVIEW = 60;
public static $FLAG_TICKET = 0; //has valid ticket 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_BARCODE => Yii::t('common/card', 'BARCODE'),
self::TYPE_OLD => Yii::t('common/card', 'OLD'), self::TYPE_OLD => Yii::t('common/card', 'OLD'),
self::TYPE_EMPLOYEE => Yii::t('common/card', 'Munkatárs'), 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_card
* @property integer $id_key * @property integer $id_key
* @property integer $id_user * @property integer $id_user
* @property string $virtual_key
* @property string $created_at * @property string $created_at
* @property string $updated_at * @property string $updated_at
*/ */

View File

@ -6,6 +6,7 @@ use Yii;
use yii\base\Exception; use yii\base\Exception;
use yii\base\InvalidConfigException; use yii\base\InvalidConfigException;
use yii\base\NotSupportedException; use yii\base\NotSupportedException;
use yii\filters\RateLimitInterface;
use yii\web\IdentityInterface; use yii\web\IdentityInterface;
/** /**
@ -42,7 +43,7 @@ use yii\web\IdentityInterface;
* @property string password_hash * @property string password_hash
* @property string auth_key * @property string auth_key
*/ */
class Customer extends BaseFitnessActiveRecord implements IdentityInterface class Customer extends BaseFitnessActiveRecord implements IdentityInterface, RateLimitInterface
{ {
const STATUS_DELETED = 0; 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 id_ticket_current
* @property integer card_flag * @property integer card_flag
* @property integer flag_out * @property integer flag_out
* @property integer version
*/ */
class DoorLog extends \yii\db\ActiveRecord class DoorLog extends \yii\db\ActiveRecord
{ {
public static $SOURCE_APP_FORGO_VILLA = "forgo_villa"; public static $SOURCE_APP_FORGO_VILLA = "forgo_villa";
public static $SOURCE_APP_FITNESS_ADMIN = "fitness_admin"; 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 * @inheritdoc
*/ */
@ -38,10 +55,15 @@ class DoorLog extends \yii\db\ActiveRecord
public function behaviors() public function behaviors()
{ {
return ArrayHelper::merge( [ return ArrayHelper::merge([
[ [
'class' => TimestampBehavior::className(), 'class' => TimestampBehavior::className(),
'value' => function(){ return date('Y-m-d H:i:s' ); }, 'value' => function ($event) {
if ( isset($event->sender->created_at) ){
return $event->sender->created_at;
}
return date('Y-m-d H:i:s');
},
'updatedAtAttribute' => false, 'updatedAtAttribute' => false,
] ]
], parent::behaviors()); ], parent::behaviors());
@ -76,55 +98,66 @@ class DoorLog extends \yii\db\ActiveRecord
]; ];
} }
public function getCustomer(){ public function getCustomer()
return $this->hasOne( Customer::className(), ["id_customer" =>"id_customer" ] ); {
return $this->hasOne(Customer::className(), ["id_customer" => "id_customer"]);
} }
public function getCustomerName(){ public function getCustomerName()
{
$result = ""; $result = "";
if (isset($this->customer)){ if (isset($this->customer)) {
$result = $this->customer->name; $result = $this->customer->name;
} }
return $result; return $result;
} }
public function getCard(){
return $this->hasOne( Card::className(), ["id_card" =>"id_card" ] ); public function getCard()
{
return $this->hasOne(Card::className(), ["id_card" => "id_card"]);
} }
public function getCardNumber(){ public function getCardNumber()
{
$result = ""; $result = "";
if (isset($this->card)){ if (isset($this->card)) {
$result = $this->card->number; $result = $this->card->number;
} }
return $result; return $result;
} }
public function getKey(){
return $this->hasOne( Key::className(), ["id_key" =>"id_key" ] ); public function getKey()
{
return $this->hasOne(Key::className(), ["id_key" => "id_key"]);
} }
public function getKeyNumber(){ public function getKeyNumber()
{
$result = ""; $result = "";
if (isset($this->key)){ if (isset($this->key)) {
$result = $this->key->number; $result = $this->key->number;
} }
return $result; return $result;
} }
public function getDirectionName(){
public function getDirectionName()
{
$result = ""; $result = "";
if ( $this->source_app == 'forgo_villa'){ if ($this->source_app == 'forgo_villa') {
if (isset($this->direction)){ if (isset($this->direction)) {
$result = Helper::getArrayValue(self::getDirectionTypes() , $this->direction, "-"); $result = Helper::getArrayValue(self::getDirectionTypes(), $this->direction, "-");
} }
}else{ } else {
$result = "Kézi olvasás"; $result = "Kézi olvasás";
} }
return $result; return $result;
} }
public static function getSourceAppName($source_app){ public static function getSourceAppName($source_app)
{
$result = ""; $result = "";
switch ($source_app){ switch ($source_app) {
case self::$SOURCE_APP_FITNESS_ADMIN : case self::$SOURCE_APP_FITNESS_ADMIN :
$result = "Recepciós alkalmazás"; $result = "Recepciós alkalmazás";
break; break;
@ -135,7 +168,8 @@ class DoorLog extends \yii\db\ActiveRecord
return $result; return $result;
} }
public static function getDirectionTypes( ){ public static function getDirectionTypes()
{
return [ return [
-2 => "Kézi olvasás/Kulcs ki", -2 => "Kézi olvasás/Kulcs ki",
-1 => "Kézi olvasás/Kulcs vissza", -1 => "Kézi olvasás/Kulcs vissza",
@ -162,7 +196,8 @@ class DoorLog extends \yii\db\ActiveRecord
]; ];
} }
public static function getCardFlagTexts( ){ public static function getCardFlagTexts()
{
return [ return [
0 => "Kártya érvényes bérlettel", 0 => "Kártya érvényes bérlettel",
1 => "Nincs érvényes bérlet", 1 => "Nincs érvényes bérlet",
@ -172,20 +207,21 @@ class DoorLog extends \yii\db\ActiveRecord
]; ];
} }
public static function mkDoorLog($direction,$card,$customer = null,$key = null){ public static function mkDoorLog($direction, $card, $customer = null, $key = null)
{
if ( !Helper::isKeyToggleDoorLogEnabled() ){ if (!Helper::isKeyToggleDoorLogEnabled()) {
return; return;
} }
$dlog = new DoorLog(); $dlog = new DoorLog();
$dlog->id_card = $card->id_card; $dlog->id_card = $card->id_card;
if ( isset($customer)){ if (isset($customer)) {
$dlog->id_customer = $customer->id_customer; $dlog->id_customer = $customer->id_customer;
} }
if ( isset($key)){ if (isset($key)) {
$dlog->id_key = $key->id_key; $dlog->id_key = $key->id_key;
} }
$dlog->direction = $direction; $dlog->direction = $direction;
@ -194,9 +230,9 @@ class DoorLog extends \yii\db\ActiveRecord
$dlog->id_account = Account::readDefault(); $dlog->id_account = Account::readDefault();
if ( $dlog->direction == 0){ if ($dlog->direction == 0) {
$dlog->card_flag = $card->validity; $dlog->card_flag = $card->validity;
}else{ } else {
$dlog->card_flag = -1; $dlog->card_flag = -1;
} }

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

@ -20,6 +20,7 @@ use yii\helpers\ArrayHelper;
* @property integer $end * @property integer $end
* @property integer $id_room * @property integer $id_room
* @property integer $id_trainer * @property integer $id_trainer
* @property integer $id_user
* @property integer $id_event_type * @property integer $id_event_type
* @property integer $seat_count * @property integer $seat_count
* @property string $created_at * @property string $created_at
@ -40,6 +41,7 @@ class Event extends ActiveRecord
public $timestampStart; public $timestampStart;
public $timestampEnd; public $timestampEnd;
/** /**
* @inheritdoc * @inheritdoc
*/ */
@ -58,6 +60,7 @@ class Event extends ActiveRecord
[['endDateString',], 'date', 'format' => Yii::$app->formatter->datetimeFormat, 'timestampAttribute' => 'end' , 'timeZone' => 'UTC'], [['endDateString',], 'date', 'format' => Yii::$app->formatter->datetimeFormat, 'timestampAttribute' => 'end' , 'timeZone' => 'UTC'],
[['id_trainer','id_room', 'id_event_type','seat_count'], 'required'], [['id_trainer','id_room', 'id_event_type','seat_count'], 'required'],
[['id_trainer','id_room', 'id_event_type','seat_count'], 'integer'], [['id_trainer','id_room', 'id_event_type','seat_count'], 'integer'],
[['id_trainer','id_room', 'id_event_type','seat_count'], 'integer'],
]; ];
} }
@ -155,13 +158,12 @@ class Event extends ActiveRecord
return $this->hasMany($this->getEquipmentTypeAssignmentsClass(),['id_event' => 'id']); return $this->hasMany($this->getEquipmentTypeAssignmentsClass(),['id_event' => 'id']);
} }
/** /**
* @return EventRegistration[]|ActiveQuery * @return EventRegistration[]|ActiveQuery
*/ */
public function getActiveEventRegistrations(){ public function getActiveEventRegistrations(){
return $this->hasMany(EventRegistration::class,['id_event' => 'id'])->andWhere( return $this->hasMany(EventRegistration::class,['id_event' => 'id'])
->andWhere(
[ [
'event_registration.canceled_at' => null, 'event_registration.canceled_at' => null,
'event_registration.deleted_at' => null, 'event_registration.deleted_at' => null,
@ -169,24 +171,13 @@ class Event extends ActiveRecord
); );
} }
/**
* @return EventRegistration[]|ActiveQuery
*/
public function getActiveEventRegistrationsForCustomer(){
return $this->hasMany(EventRegistration::class,['id_event' => 'id'])->andWhere(
[
'event_registration.canceled_at' => null,
'event_registration.deleted_at' => null,
'event_registration.id_customer' => \Yii::$app->user->id
]
);
}
/** /**
* @return integer * @return integer
*/ */
public function getEventRegistrationCount(){ public function getEventRegistrationCount(){
return count($this->getActiveEventRegistrations()->all()); $registrations = EventRegistration::find()->andWhere(['id_event' => $this->id])->all();
$activeRegistrations = EventRegistration::filterActive($registrations);
return count($activeRegistrations);
} }
protected function getEquipmentTypeAssignmentsClass() protected function getEquipmentTypeAssignmentsClass()
@ -200,7 +191,9 @@ class Event extends ActiveRecord
} }
public function hasFreeSeats(){ public function hasFreeSeats(){
$registrationCount = count($this->eventRegistrations) ; $registrations = EventRegistration::find()->andWhere(['id_event' => $this->id])->all();
$activeRegistrations = EventRegistration::filterActive($registrations);
$registrationCount = count($activeRegistrations) ;
$seatCount = $this->seat_count; $seatCount = $this->seat_count;
if ( !isset($seatCount ) || $seatCount === 0){ if ( !isset($seatCount ) || $seatCount === 0){

View File

@ -21,6 +21,9 @@ use yii\helpers\ArrayHelper;
*/ */
class EventRegistration extends \yii\db\ActiveRecord class EventRegistration extends \yii\db\ActiveRecord
{ {
const CANCEL_REASON_CUSTOMER = "customer";
const CANCEL_REASON_EVENT = "event";
/** /**
* @inheritdoc * @inheritdoc
*/ */
@ -57,45 +60,52 @@ class EventRegistration extends \yii\db\ActiveRecord
public function behaviors() public function behaviors()
{ {
return ArrayHelper::merge( [ return ArrayHelper::merge([
[ [
'class' => TimestampBehavior::className(), 'class' => TimestampBehavior::className(),
'value' => function(){ return date('Y-m-d H:i:s' ); } 'value' => function () {
return date('Y-m-d H:i:s');
}
] ]
], ],
parent::behaviors()); parent::behaviors());
} }
public function getEvent(){ public function getEvent()
return $this->hasOne($this->getEventClass(),['id' => 'id_event']); {
return $this->hasOne($this->getEventClass(), ['id' => 'id_event']);
} }
public function getCustomer(){ public function getCustomer()
return $this->hasOne($this->getCustomerClass(),['id' => 'id_customer']); {
return $this->hasOne($this->getCustomerClass(), ['id' => 'id_customer']);
} }
public function getEventClass(){ public function getEventClass()
{
return Event::class; return Event::class;
} }
public function getCustomerClass(){ public function getCustomerClass()
{
return Customer::class; return Customer::class;
} }
/** /**
* @param EventRegistration $eventRegistration * @param EventRegistration $eventRegistration
*/ */
public static function isActive($eventRegistration){ public static function isActive($eventRegistration)
if ( !isset($eventRegistration ) ){ {
if (!isset($eventRegistration)) {
return false; return false;
} }
if ( isset($eventRegistration->canceled_at ) ){ if (isset($eventRegistration->canceled_at)) {
return false; return false;
} }
if ( isset($eventRegistration->deleted_at ) ){ if (isset($eventRegistration->deleted_at)) {
return false; return false;
} }
@ -105,11 +115,12 @@ class EventRegistration extends \yii\db\ActiveRecord
/** /**
* @param EventRegistration $eventRegistration * @param EventRegistration $eventRegistration
*/ */
public static function isForCustomer($eventRegistration,$idCustomer){ public static function isForCustomer($eventRegistration, $idCustomer)
if ( !isset($eventRegistration ) ){ {
if (!isset($eventRegistration)) {
return false; return false;
} }
if ( !isset($eventRegistration->id_customer ) ){ if (!isset($eventRegistration->id_customer)) {
return false; return false;
} }
@ -119,20 +130,27 @@ class EventRegistration extends \yii\db\ActiveRecord
/** /**
* @param EventRegistration[] $eventRegistrations * @param EventRegistration[] $eventRegistrations
*/ */
public static function filterActive($eventRegistrations){ public static function filterActive($eventRegistrations)
return array_filter($eventRegistrations, EventRegistration::class.'::isActive' ); {
if (!isset($eventRegistrations)) {
return [];
}
return array_filter($eventRegistrations, EventRegistration::class . '::isActive');
} }
/** /**
* @param EventRegistration[] $eventRegistrations * @param EventRegistration[] $eventRegistrations
*/ */
public static function filterForCustomer($eventRegistrations,$idCustomer){ public static function filterForCustomer($eventRegistrations, $idCustomer)
{
$result = []; $result = [];
foreach ($eventRegistrations as $eventRegistration){ if (isset($eventRegistrations)) {
if ( EventRegistration::isForCustomer($eventRegistration,$idCustomer)){ foreach ($eventRegistrations as $eventRegistration) {
if (EventRegistration::isForCustomer($eventRegistration, $idCustomer)) {
$result[] = $eventRegistration; $result[] = $eventRegistration;
} }
} }
}
return $result; return $result;
} }
} }

View File

@ -11,6 +11,7 @@ use yii\helpers\ArrayHelper;
* *
* @property integer $id * @property integer $id
* @property string $name * @property string $name
* @property string $theme
* @property string $created_at * @property string $created_at
* @property string $updated_at * @property string $updated_at
*/ */
@ -30,9 +31,10 @@ class EventType extends \yii\db\ActiveRecord
public function rules() public function rules()
{ {
return [ return [
[['name'], 'required'], [['name','theme'], 'required'],
[['name'], 'unique'], [['name'], 'unique'],
[['name'], 'string', 'max' => 255] [['name'], 'string', 'max' => 255],
[['theme'], 'string', 'max' => 50]
]; ];
} }
@ -104,4 +106,12 @@ class EventType extends \yii\db\ActiveRecord
// TODO: implement bossiness logic to select ticket // TODO: implement bossiness logic to select ticket
return $possibleTickets[0]; return $possibleTickets[0];
} }
static function themes() {
$themes = [];
for ($x = 0; $x < 10; $x++) {
$themes[$x] = "Színtéma " . ($x+1);
}
return $themes;
}
} }

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

@ -39,8 +39,8 @@ class Log extends BaseFitnessActiveRecord
public static $TYPE_TICKET_USAGE_FIRST = 30; public static $TYPE_TICKET_USAGE_FIRST = 30;
public static $TYPE_TICKET_USAGE_MULTIPLE = 40; public static $TYPE_TICKET_USAGE_MULTIPLE = 40;
public static $TYPE_LOGIN = 50; public static $TYPE_LOGIN = 50;
public static $TYPE_DEFAULT_ACCOUNT= 60; public static $TYPE_DEFAULT_ACCOUNT = 60;
public static $TYPE_CREATE_CUSTOMER= 70; public static $TYPE_CREATE_CUSTOMER = 70;
public static $TYPE_PROCUREMENT_UPDATE = 80; public static $TYPE_PROCUREMENT_UPDATE = 80;
public static $TYPE_TICKET_COUNT_MOVE_OUT = 90; public static $TYPE_TICKET_COUNT_MOVE_OUT = 90;
public static $TYPE_WASTE = 100; public static $TYPE_WASTE = 100;
@ -56,9 +56,11 @@ class Log extends BaseFitnessActiveRecord
public static $TYPE_TOWEL_OUT = 200; public static $TYPE_TOWEL_OUT = 200;
public static $TYPE_CRUD = 210; public static $TYPE_CRUD = 210;
public static $TYPE_TICKET_UPDATED_BY_ADMIN = 220; public static $TYPE_TICKET_UPDATED_BY_ADMIN = 220;
public static $TYPE_MOBILE_DEVICE_STATUS = 230;
public static function getTypes(){ public static function getTypes()
{
return [ return [
Log::$TYPE_INFO => "Info", Log::$TYPE_INFO => "Info",
@ -66,8 +68,8 @@ class Log extends BaseFitnessActiveRecord
Log::$TYPE_TICKET_USAGE_FIRST => "Bérlet használat", Log::$TYPE_TICKET_USAGE_FIRST => "Bérlet használat",
Log::$TYPE_TICKET_USAGE_MULTIPLE => "Többszöri bérlet használat", Log::$TYPE_TICKET_USAGE_MULTIPLE => "Többszöri bérlet használat",
Log::$TYPE_LOGIN => "Bejelentkezés", Log::$TYPE_LOGIN => "Bejelentkezés",
Log::$TYPE_DEFAULT_ACCOUNT=> "Alapértelmezett kassza", Log::$TYPE_DEFAULT_ACCOUNT => "Alapértelmezett kassza",
Log::$TYPE_CREATE_CUSTOMER=> "Új vendég", Log::$TYPE_CREATE_CUSTOMER => "Új vendég",
Log::$TYPE_PROCUREMENT_UPDATE => "Beszerzés módosítás", Log::$TYPE_PROCUREMENT_UPDATE => "Beszerzés módosítás",
Log::$TYPE_TICKET_COUNT_MOVE_OUT => "Ki mozgás", Log::$TYPE_TICKET_COUNT_MOVE_OUT => "Ki mozgás",
Log::$TYPE_WASTE => "Selejt", Log::$TYPE_WASTE => "Selejt",
@ -82,15 +84,17 @@ class Log extends BaseFitnessActiveRecord
Log::$TYPE_TOWEL_IN => "Törölköző ki", Log::$TYPE_TOWEL_IN => "Törölköző ki",
Log::$TYPE_TOWEL_OUT => "Törölköző vissza", Log::$TYPE_TOWEL_OUT => "Törölköző vissza",
Log::$TYPE_CRUD => "CRUD", Log::$TYPE_CRUD => "CRUD",
Log::$TYPE_TICKET_UPDATED_BY_ADMIN => "Bérlet módosítás" 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(){ public function getTypeName()
{
$types = Log::getTypes(); $types = Log::getTypes();
return Helper::getArrayValue($types,$this->type,null); return Helper::getArrayValue($types, $this->type, null);
} }
/** /**
@ -140,19 +144,21 @@ class Log extends BaseFitnessActiveRecord
} }
public static function info($message ){ public static function info($message)
self::log(['type' =>self::$TYPE_INFO, 'message' => $message]); {
self::log(['type' => self::$TYPE_INFO, 'message' => $message]);
} }
/** /**
* example * example
* Log::log([ * Log::log([
'type' =>Log::$TYPE_LOGIN, * 'type' =>Log::$TYPE_LOGIN,
'message' => $message * 'message' => $message
]); * ]);
* @param array $config * @param array $config
*/ */
public static function log( $config ){ public static function log($config)
{
$model = new Log($config); $model = new Log($config);
$model->app = \Yii::$app->name; $model->app = \Yii::$app->name;
$model->url = Url::canonical(); $model->url = Url::canonical();
@ -163,7 +169,8 @@ class Log extends BaseFitnessActiveRecord
/** /**
* create a log from the console app * create a log from the console app
* */ * */
public static function logC( $config ){ public static function logC($config)
{
$model = new Log($config); $model = new Log($config);
$model->app = "Fitness rendszer"; $model->app = "Fitness rendszer";
$model->url = "console"; $model->url = "console";
@ -171,42 +178,49 @@ class Log extends BaseFitnessActiveRecord
$model->save(false); $model->save(false);
} }
public function getUser(){ public function getUser()
return $this->hasOne( User::className(), ["id" =>"id_user" ] ); {
return $this->hasOne(User::className(), ["id" => "id_user"]);
} }
public function getTicket(){ public function getTicket()
return $this->hasOne( Ticket::className(), ["id_ticket" =>"id_ticket" ] ); {
return $this->hasOne(Ticket::className(), ["id_ticket" => "id_ticket"]);
} }
public function getCustomer(){ public function getCustomer()
return $this->hasOne( Customer::className(), ["id_customer" =>"id_customer" ] ); {
return $this->hasOne(Customer::className(), ["id_customer" => "id_customer"]);
} }
public function getMoneyMovement(){ public function getMoneyMovement()
return $this->hasOne( MoneyMovement::className(), ["id_money_movement" =>"id_money_movement" ] ); {
return $this->hasOne(MoneyMovement::className(), ["id_money_movement" => "id_money_movement"]);
} }
public function getUserName(){ public function getUserName()
{
$user = $this->user; $user = $this->user;
if ( isset($user)){ if (isset($user)) {
return $user->username; return $user->username;
} }
return null; return null;
} }
public function getCustomerName(){ public function getCustomerName()
{
$customer = $this->customer; $customer = $this->customer;
if ( isset($customer)){ if (isset($customer)) {
return $customer->name; return $customer->name;
} }
return null; return null;
} }
public function getTicketName(){ public function getTicketName()
{
$ticket = $this->ticket; $ticket = $this->ticket;
if ( isset($ticket)){ if (isset($ticket)) {
return $ticket->ticketTypeName; return $ticket->ticketTypeName;
} }
return null; 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 yii\behaviors\TimestampBehavior;
use common\components\AccountAwareBehavior; use common\components\AccountAwareBehavior;
use common\components\UserAwareBehavior; use common\components\UserAwareBehavior;
use yii\base\Object; use yii\base\BaseObject;
use common\models\Transfer; use common\models\Transfer;
/** /**

View File

@ -0,0 +1,53 @@
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "property".
*
* @property integer $id
* @property integer $id_user
* @property integer $id_property_definition
* @property string $value
* @property string $created_at
* @property string $updated_at
*/
class Property extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'property';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id_user', 'id_property_definition'], 'integer'],
[['created_at', 'updated_at'], 'safe'],
[['value'], 'string', 'max' => 255]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'id_user' => 'Id User',
'id_property_definition' => 'Id Property Definition',
'value' => 'Value',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "property_definition".
*
* @property integer $id
* @property string $name
* @property string $label
* @property string $type
* @property string $config
* @property string $created_at
* @property string $updated_at
*/
class PropertyDefinition extends \yii\db\ActiveRecord
{
const DEFINITION_GROUP_TRAINING_CUSTOMER_CANCEL_TIME_LIMIT = "GROUP_TRAINING_CUSTOMER_CANCEL_TIME_LIMIT";
/**
* @inheritdoc
*/
public static function tableName()
{
return 'property_definition';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name', 'label', 'type'], 'required'],
[['created_at', 'updated_at'], 'safe'],
[['name', 'label', 'type'], 'string', 'max' => 100],
[['config'], 'string', 'max' => 255]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'label' => 'Label',
'type' => 'Type',
'config' => 'Config',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
}

View File

@ -0,0 +1,44 @@
<?php
namespace common\models;
use yii\base\BaseObject;
/**
* @property \common\models\PropertyDefinition $definition
* @property \common\models\Property $property
*/
class PropertySetting extends BaseObject
{
public $definition;
public $property;
public function getValue(){
$value = null;
if ( isset($this->property)){
$value = $this->property->value;
}
return $value;
}
public function setValue($value){
// @property integer $id
// * @property integer $id_user
// * @property integer $id_property_definition
// * @property string $value
$this->property = new Property(
[
'id_user' => \Yii::$app->user->id,
'id_property_definition' => $this->definition->id,
'value' => $value
]
);
}
public function getLabel(){
return $this->definition->label;
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace common\models;
use yii\base\Model;
class PropertySettingModel extends Model
{
public $id_definition;
public $value;
public $label;
public function rules()
{
return [
[['id_definition',"value"], 'required'],
[['id_definition',"value"], 'integer'],
];
}
/**
* @param PropertySetting $setting
* @return PropertySettingModel
*/
public static function fromPropertySetting($setting){
$result = new PropertySettingModel();
$result->value = $setting->getValue();
$result->label = $setting->getLabel();
$result->id_definition = $setting->definition->id;
return $result;
}
}

View File

@ -174,6 +174,8 @@ class Ticket extends \common\models\BaseFitnessActiveRecord
'payment_method' => Yii::t('common/transfer', 'Fizetési mód'), 'payment_method' => Yii::t('common/transfer', 'Fizetési mód'),
'original_price' => Yii::t('common/transfer', 'Eredeti ár'), 'original_price' => Yii::t('common/transfer', 'Eredeti ár'),
'original_end' => Yii::t('common/transfer', 'Eredeti érvényesség vége'), 'original_end' => Yii::t('common/transfer', 'Eredeti érvényesség vége'),
'max_reservation_count' => Yii::t('common/transfer', 'Max foglalások'),
'reservation_count' => Yii::t('common/transfer', 'Felhasznált foglalások'),
]; ];
} }
@ -467,6 +469,10 @@ class Ticket extends \common\models\BaseFitnessActiveRecord
if ( $this->reservation_count < 0 ){ if ( $this->reservation_count < 0 ){
$this->reservation_count = 0; $this->reservation_count = 0;
} }
if ( $this->reservation_count > $this->max_reservation_count ){
$this->reservation_count = $this->max_reservation_count;
}
} }

View File

@ -2,6 +2,8 @@
namespace common\models; namespace common\models;
use common\components\RoleDefinition;
use common\helpers\AppArrayHelper;
use Yii; use Yii;
use yii\behaviors\TimestampBehavior; use yii\behaviors\TimestampBehavior;
use yii\helpers\ArrayHelper; use yii\helpers\ArrayHelper;
@ -79,8 +81,18 @@ class Trainer extends \yii\db\ActiveRecord
return \Yii::t("trainer",'active_off'); return \Yii::t("trainer",'active_off');
} }
public static function trainerOptions($all = false, $emptyString = false){ public function getUserTrainerAssignments()
$items = ArrayHelper::map(Trainer::find()->all(),'id','name'); {
return $this->hasMany(UserTrainerAssignment::class, ['id_trainer' => 'id']);
}
public static function trainerOptions($all = false, $emptyString = false, $trainers = null){
if ( !isset($trainers)){
$trainers = Trainer::find()->all();
}
$items = ArrayHelper::map($trainers,'id','name');
$extra = []; $extra = [];
if ( $all ) { if ( $all ) {
$extra = ['' => \Yii::t('trainer','All')]; $extra = ['' => \Yii::t('trainer','All')];
@ -91,4 +103,27 @@ class Trainer extends \yii\db\ActiveRecord
return ArrayHelper::merge($extra,$items); return ArrayHelper::merge($extra,$items);
} }
public static function getTrainersAllowed($idUser){
$query = Trainer::find();
if (RoleDefinition::isAdmin() == false) {
$query = $query->innerJoinWith('userTrainerAssignments')
->andWhere(
[
'user_trainer_assignment.id_user' => $idUser
]
);
}
return $query->all();
}
public static function isTrainerAllowed($trainers,$idUser,$idTrainer){
$trainerAllowed = false;
foreach ($trainers as $trainer){
if ( $trainer->id == $idTrainer){
$trainerAllowed = true;
}
}
return $trainerAllowed;
}
} }

View File

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

View File

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

View File

@ -197,6 +197,10 @@ class User extends ActiveRecord implements IdentityInterface
return $this->hasMany(UserAccountAssignment::className(), ['id_user' =>'id']); return $this->hasMany(UserAccountAssignment::className(), ['id_user' =>'id']);
} }
public function getUserTrainerAssignments(){
return $this->hasMany(UserTrainerAssignment::className(), ['id_user' =>'id']);
}
static function statuses() { static function statuses() {
return [ return [
self::STATUS_ACTIVE => Yii::t('app', 'Aktív'), self::STATUS_ACTIVE => Yii::t('app', 'Aktív'),

View File

@ -0,0 +1,45 @@
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "user_trainer_assignment".
*
* @property integer $id_user_trainer_assignment
* @property integer $id_user
* @property integer $id_trainer
*/
class UserTrainerAssignment extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'user_trainer_assignment';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id_user', 'id_trainer'], 'integer']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id_user_trainer_assignment' => Yii::t('common/user-trainer-assignment', 'Id User Trainer Assignment'),
'id_user' => Yii::t('common/user-trainer-assignment', 'Id User'),
'id_trainer' => Yii::t('common/user-trainer-assignment', 'Id Trainer'),
];
}
}

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());
}
}

View File

@ -2,30 +2,35 @@
namespace common\modules\event\controllers; namespace common\modules\event\controllers;
use common\components\RoleDefinition;
use common\manager\EventRegistrationManager; use common\manager\EventRegistrationManager;
use common\models\CardEventRegistrationForm; use common\models\CardEventRegistrationForm;
use common\models\EventEquipmentType; use common\models\EventEquipmentType;
use common\models\EventEquipmentTypeAssignment; use common\models\EventEquipmentTypeAssignment;
use common\models\EventRegistrationEquipmentTypeAssignment; use common\models\EventRegistration;
use common\models\Trainer;
use common\modules\event\EventModule; use common\modules\event\EventModule;
use common\modules\event\modelAndView\CreateEventModelAndView;
use common\modules\event\models\copy\ClearWeekForm; use common\modules\event\models\copy\ClearWeekForm;
use common\modules\event\models\copy\CopyWeekSearch; use common\modules\event\models\copy\CopyWeekSearch;
use common\modules\event\models\EventCreate;
use common\modules\event\models\EventEquipmentTypeForm; use common\modules\event\models\EventEquipmentTypeForm;
use common\modules\event\models\EventPermissions; use common\modules\event\models\EventPermissions;
use common\modules\event\models\timetable\TimeTableSearch; use common\modules\event\models\timetable\TimeTableSearch;
use DateTime; use DateTime;
use Exception; use Exception;
use Throwable;
use Yii; use Yii;
use common\models\Event; use common\models\Event;
use common\modules\event\models\EventSearch; use common\modules\event\models\EventSearch;
use yii\data\ActiveDataProvider; use yii\data\ActiveDataProvider;
use yii\filters\AccessControl; use yii\filters\AccessControl;
use yii\web\BadRequestHttpException;
use yii\web\Controller; use yii\web\Controller;
use yii\web\HttpException; use yii\web\HttpException;
use yii\web\NotFoundHttpException; use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\filters\VerbFilter;
use yii\web\Response; use yii\web\Response;
use yii\web\UnauthorizedHttpException;
/** @noinspection PhpUnused */ /** @noinspection PhpUnused */
@ -47,7 +52,7 @@ class EventController extends Controller
$module = EventModule::getInstance(); $module = EventModule::getInstance();
assert(isset($module), 'event module not set'); assert(isset($module), 'event module not set');
$allowedActions = ['index', 'view', 'reserve-card', 'cancel-registration', 'delete-registration', 'timetable', 'copy-week','clear-week',]; $allowedActions = ['index', 'view', 'reserve-card', 'cancel-registration', 'delete-registration', 'timetable', 'copy-week', 'clear-week',];
if ($module->mode === 'backend') { if ($module->mode === 'backend') {
$allowedActions[] = 'create'; $allowedActions[] = 'create';
$allowedActions[] = 'update'; $allowedActions[] = 'update';
@ -122,15 +127,37 @@ class EventController extends Controller
*/ */
public function actionCreate() public function actionCreate()
{ {
$model = new Event(); if ( !RoleDefinition::canAny([RoleDefinition::$ROLE_TRAINER, RoleDefinition::$ROLE_ADMIN])){
throw new UnauthorizedHttpException();
}
$modelAndView = new CreateEventModelAndView();
$event = new EventCreate();
$event->id_user = \Yii::$app->user->id;
$modelAndView->event = $event;
$query = Trainer::find();
if (RoleDefinition::isAdmin() == false) {
$query = $query->innerJoinWith('userTrainerAssignments')
->andWhere(
[
'user_trainer_assignment.id_user' => \Yii::$app->user->id
]
);
}
$trainers = $query->all();
$modelAndView->trainers = $trainers;
/** @noinspection NotOptimalIfConditionsInspection */ /** @noinspection NotOptimalIfConditionsInspection */
if ($model->load(Yii::$app->request->post()) && $model->save()) { if ($event->load(Yii::$app->request->post()) && $event->save()) {
return $this->redirect(['view', 'id' => $model->id]); return $this->redirect(['view', 'id' => $event->id]);
} }
return $this->render('create', [ return $this->render('create', [
'model' => $model, 'modelAndView' => $modelAndView
]); ]);
} }
@ -143,15 +170,33 @@ class EventController extends Controller
*/ */
public function actionUpdate($id) public function actionUpdate($id)
{ {
$model = $this->findModel($id); if ( !RoleDefinition::canAny([RoleDefinition::$ROLE_TRAINER, RoleDefinition::$ROLE_ADMIN])){
throw new UnauthorizedHttpException();
}
$modelAndView = new CreateEventModelAndView();
$event = EventCreate::findOne($id);
if ( !isset($event)){
throw new NotFoundHttpException();
}
$modelAndView->event = $event;
$trainers = Trainer::getTrainersAllowed(\Yii::$app->user->id);
if ( !Trainer::isTrainerAllowed($trainers,\Yii::$app->user->id, $event->id_trainer)){
throw new BadRequestHttpException("Ön nem jogosult az esemény módosítására");
}
$modelAndView->trainers = $trainers;
/** @noinspection NotOptimalIfConditionsInspection */ /** @noinspection NotOptimalIfConditionsInspection */
if ($model->load(Yii::$app->request->post()) && $model->save()) { if ($event->load(Yii::$app->request->post()) && $event->save()) {
return $this->redirect(['view', 'id' => $model->id]); return $this->redirect(['view', 'id' => $event->id]);
} }
return $this->render('update', [ return $this->render('update', [
'model' => $model, 'modelAndView' => $modelAndView
]); ]);
} }
@ -182,8 +227,8 @@ class EventController extends Controller
$db = Yii::$app->db; $db = Yii::$app->db;
$tx = $db->beginTransaction(); $tx = $db->beginTransaction();
try { try {
$registration = $eventRegistrationManager->loadRegistration($id); $registration = $eventRegistrationManager->loadRegistration($id,null);
$eventRegistrationManager->cancelRegistration($registration); $eventRegistrationManager->cancelRegistrationTX($registration,null,EventRegistration::CANCEL_REASON_CUSTOMER);
$tx->commit(); $tx->commit();
return $this->redirect(['view', 'id' => $registration->id_event]); return $this->redirect(['view', 'id' => $registration->id_event]);
} catch (Exception $ex) { } catch (Exception $ex) {
@ -192,26 +237,26 @@ class EventController extends Controller
} }
}/** @noinspection PhpUnused */ }/** @noinspection PhpUnused */
/** // /**
* @param $id // * @param $id
* @return Response // * @return Response
* @throws Exception // * @throws Exception
*/ // */
public function actionDeleteRegistration($id) // public function actionDeleteRegistration($id)
{ // {
$eventRegistrationManager = new EventRegistrationManager(); // $eventRegistrationManager = new EventRegistrationManager();
$db = Yii::$app->db; // $db = Yii::$app->db;
$tx = $db->beginTransaction(); // $tx = $db->beginTransaction();
try { // try {
$registration = $eventRegistrationManager->loadRegistration($id); // $registration = $eventRegistrationManager->loadRegistration($id);
$eventRegistrationManager->deleteRegistration($registration); // $eventRegistrationManager->deleteRegistration($registration);
$tx->commit(); // $tx->commit();
return $this->redirect(['view', 'id' => $registration->id_event]); // return $this->redirect(['view', 'id' => $registration->id_event]);
} catch (Exception $ex) { // } catch (Exception $ex) {
$tx->rollBack(); // $tx->rollBack();
throw $ex; // throw $ex;
} // }
}/** @noinspection PhpUnused */ // }/** @noinspection PhpUnused */
/** /**
* @param $id * @param $id
@ -284,7 +329,7 @@ class EventController extends Controller
$model->search(Yii::$app->request->post()); $model->search(Yii::$app->request->post());
if (count($model->getErrors()) === 0) { if (count($model->getErrors()) === 0) {
$model->save(); $model->save();
$this->redirect(['copy-week', $model->formName() . '[sourceDateString]'=> $model->sourceDateString, $model->formName() . '[targetDateString]' =>$model->targetDateString ]); $this->redirect(['copy-week', $model->formName() . '[sourceDateString]' => $model->sourceDateString, $model->formName() . '[targetDateString]' => $model->targetDateString]);
} }
} else { } else {
$model->search(Yii::$app->request->get()); $model->search(Yii::$app->request->get());
@ -298,7 +343,8 @@ class EventController extends Controller
* @return Response * @return Response
* @throws Throwable * @throws Throwable
*/ */
public function actionClearWeek(){ public function actionClearWeek()
{
$clearWeekForm = new ClearWeekForm(); $clearWeekForm = new ClearWeekForm();
$clearWeekForm->clear(Yii::$app->request->get()); $clearWeekForm->clear(Yii::$app->request->get());
@ -306,7 +352,7 @@ class EventController extends Controller
} }
/** /**
* @param $id the id * @param int $id the id
* @return string * @return string
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
@ -320,10 +366,10 @@ class EventController extends Controller
$formModel->loadAssignedEquipment(); $formModel->loadAssignedEquipment();
if (Yii::$app->request->isPost) { if (Yii::$app->request->isPost) {
if ($formModel->load(Yii::$app->request->post()) && $formModel->save()) { if ($formModel->load(Yii::$app->request->post()) && $formModel->save()) {
$this->redirect(['view','id' => $formModel->event->id]); $this->redirect(['view', 'id' => $formModel->event->id]);
} }
}else{ } else {
if ( !isset($formModel->event) ){ if (!isset($formModel->event)) {
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');
} }
} }

View File

@ -2,11 +2,16 @@
namespace common\modules\event\manager; namespace common\modules\event\manager;
use common\components\RoleDefinition;
use common\models\Event; use common\models\Event;
use common\models\EventRegistration;
use common\models\Trainer;
use common\models\User;
use common\modules\event\models\timetable\TimeTableMonth; use common\modules\event\models\timetable\TimeTableMonth;
use common\modules\event\models\timetable\TimeTableMonthDay; use common\modules\event\models\timetable\TimeTableMonthDay;
use common\modules\event\models\timetable\TimeTableMonthWeek; use common\modules\event\models\timetable\TimeTableMonthWeek;
use customerapi\models\available\EventInterval; use customerapi\models\available\EventInterval;
use customerapi\models\details\EventRegistrationView;
use DateTime; use DateTime;
use Exception; use Exception;
use yii\db\Query; use yii\db\Query;
@ -14,28 +19,6 @@ use yii\db\StaleObjectException;
class EventManager class EventManager
{ {
/** @noinspection PhpUnused */
/**
* Delete or mark deleted an event
* @param $id
* @throws Throwable
* @throws \yii\base\Exception on any error
* @throws StaleObjectException
*/
public function deleteEvent($id){
$event = Event::findOne($id);
if ( !isset($event)){
throw new \yii\base\Exception("Event $id not found");
}
$registrations = $event->eventRegistrations;
if ( !isset($registrations) || count($registrations) === 0 ){
$event->delete();
} else {
$event->deleted_at = time();
$event->save(false);
}
}
/** /**
@ -43,7 +26,7 @@ class EventManager
* @return TimeTableMonth * @return TimeTableMonth
* @throws Exception * @throws Exception
*/ */
public function loadTimeTable($interval , $activeOrDisplayInterval = "active" ) public function loadTimeTable($interval, $activeOrDisplayInterval = "active")
{ {
$timeTable = new TimeTableMonth(); $timeTable = new TimeTableMonth();
@ -73,17 +56,21 @@ class EventManager
$timeTable->weeks[$weekNumber]->$weekDayName = $timeTableMonthDay; $timeTable->weeks[$weekNumber]->$weekDayName = $timeTableMonthDay;
} }
if ( $activeOrDisplayInterval == "active"){ if ($activeOrDisplayInterval == "active") {
$dateTimeFrom = $interval->firstActiveDate; $dateTimeFrom = $interval->firstActiveDate;
$dateTimeTo = (clone $interval->lastActiveDate)->modify('+1 day'); $to = clone $interval->lastActiveDate;
}else{ $dateTimeTo = $to->modify('+1 day');
} else {
// active // active
$dateTimeFrom = $interval->firstDisplayDate; $dateTimeFrom = $interval->firstDisplayDate;
$dateTimeTo = (clone $interval->lastDisplayDate)->modify('+1 day'); $to = clone $interval->lastDisplayDate;
$dateTimeTo = $to->modify('+1 day');
} }
// get events between active dates // get events between active dates
$events =$this->getEvents($dateTimeFrom,$dateTimeTo); $trainers = $this->getAssignedTrainerIDsForPermission();
$events = $this->getEvents($dateTimeFrom, $dateTimeTo,$trainers);
// set events per day // set events per day
/** @var Event $event */ /** @var Event $event */
@ -108,9 +95,12 @@ class EventManager
* Get all active events between the to dates * Get all active events between the to dates
* @param DateTime $fromInc from date inclusive (>=) * @param DateTime $fromInc from date inclusive (>=)
* @param DateTime $toExcl to date exclusive (<) * @param DateTime $toExcl to date exclusive (<)
* @param int[] trainers if set, load only events assigend to the given trainers
* if the array is set, but emtpy,
* then no sql will be executed, empty array will be returned
* @return Event[] * @return Event[]
*/ */
public function getEvents($fromInc, $toExcl) public function getEvents($fromInc, $toExcl,$trainers = null)
{ {
$query = Event::find(); $query = Event::find();
@ -124,6 +114,12 @@ class EventManager
->orderBy([ ->orderBy([
'event.start' => SORT_ASC 'event.start' => SORT_ASC
]); ]);
if ( isset($trainers)){
if ( count($trainers) == 0 ){
return [];
}
$query->andWhere(['in','id_trainer',$trainers]);
}
$query = $this->withEventConditions($query); $query = $this->withEventConditions($query);
return $query return $query
->all(); ->all();
@ -148,18 +144,128 @@ class EventManager
public function getEventsForDay($date) public function getEventsForDay($date)
{ {
$start = clone $date; $start = clone $date;
$start->setTime(0,0); $start->setTime(0, 0);
$to = clone $start; $to = clone $start;
$to->modify('+1 day'); $to->modify('+1 day');
return $this->getEvents($start,$to); return $this->getEvents($start, $to);
} }
public function getEvent($id){ public function getEvent($id)
{
return Event::findOne($id); return Event::findOne($id);
} }
public function findActiveRegistrations($idEvent, $idCustomer = null)
{
$registrations = EventRegistrationView::find()->andWhere(['id_event' => $idEvent, 'id_customer' => \Yii::$app->user->id])->all();
$allActiveRegistrations = EventRegistration::filterActive($registrations);
if (isset($idCustomer)) {
$allActiveRegistrations = EventRegistration::filterForCustomer($allActiveRegistrations, \Yii::$app->user->id);
}
return $allActiveRegistrations;
}
public function findActiveEvent($idEvent, $interval, $withRelatedObjects = false)
{
$paramEventStartMax = (clone $interval->lastActiveDate);
$paramEventStartMax = $paramEventStartMax->modify('+1 day');
$paramEventStartMax = $paramEventStartMax->getTimestamp();
$query = Event::find()
->andWhere(['event.id' => $idEvent])
->andWhere(['>=', 'event.start', $interval->firstActiveDate->getTimestamp()])
->andWhere(['<', 'event.start', $paramEventStartMax])
->andWhere(['event.active' => '1']);
if ($withRelatedObjects) {
$query = $query->innerJoinWith('trainer')
->innerJoinWith('eventType')
->innerJoinWith('room');
}
return $query->one();
}
public function findActiveEvents($interval)
{
$paramEventStartMax = (clone $interval->lastActiveDate);
$paramEventStartMax = $paramEventStartMax->modify('+1 day');
$paramEventStartMax = $paramEventStartMax->getTimestamp();
return Event::find()
->andWhere(['>=', 'event.start', $interval->firstActiveDate->getTimestamp()])
->andWhere(['<', 'event.start', $paramEventStartMax])
->andWhere(['event.active' => '1'])->all();
}
public function getAssignedTrainers($idUser){
return Trainer::find()
->innerJoinWith('userTrainerAssignments')
->andWhere(['user_trainer_assignment.id_user' => $idUser])
->all();
}
public function getAssignedTrainerIDs($idUser){
$trainerObjects = $this->getAssignedTrainers($idUser);
return $this->mapTrainerToId($trainerObjects);
}
public function getAllTrainerIDs( ){
$trainerObjects = Trainer::find()->all();
return $this->mapTrainerToId($trainerObjects);
}
public function mapTrainerToId($trainerObjects){
$trainers = [];
foreach ($trainerObjects as $trainerObject){
$trainers[] = $trainerObject->id;
}
return $trainers;
}
/**
* If the trainers are not limited by the 'trainer' role, null will be returned.
* If the user has the 'trainer' permission, but no trainer is assigned, empty array will be returned.
* Otherwise the array of assigned trainer IDs will be returned.
* @return array|null
*/
public function getAssignedTrainerIDsForPermission(){
if ( RoleDefinition::isTrainer()){
$trainers = $this->getAssignedTrainerIDs(\Yii::$app->user->id);
} else {
$trainers = $this->getAllTrainerIDs();
}
return $trainers;
}
/**
* @param $trainerIDs int[]|null the trainer IDs. Null means, all trainers are allowed
* @param $trainerId
* @return bool
*/
public function isTrainerAllowed($trainerIDs,$trainerId){
if ( !isset($trainerIDs) ){
return true;
}
return array_search($trainerId,$trainerIDs) !== false;
}
/**
* Use it with the result of getAssignedTrainerIDsForPermission().
* (
* @param $trainerIDs int[]|null the trainer IDs. Null means, all trainers are allowed
* @return bool
*/
public function hasAnyTrainerAllowed($trainerIDs ){
if ( !isset($trainerIDs)){
return true;
}
return count($trainerIDs) > 0;
}
} }

View File

@ -0,0 +1,14 @@
<?php
namespace common\modules\event\modelAndView;
use common\models\Trainer;
/**
* @property \common\models\Event $event
* @property Trainer[] $trainers
*/
class CreateEventModelAndView
{
public $event;
public $trainers;
}

View File

@ -0,0 +1,49 @@
<?php
namespace common\modules\event\models;
use common\components\RoleDefinition;
use common\models\Event;
use common\models\Trainer;
class EventCreate extends Event
{
public function rules()
{
$basicRules = parent::rules();
$basicRules[] = [
['id_trainer'] ,'validateTrainers'
];
return $basicRules;
}
public function validateTrainers($attribute, $params){
$query = Trainer::find();
if (RoleDefinition::isAdmin() == false) {
$query = $query->innerJoinWith('userTrainerAssignments')
->andWhere(
[
'user_trainer_assignment.id_user' => \Yii::$app->user->id
]
);
}
$trainers = $query->all();
$trainerAllowed = false;
foreach ($trainers as $trainer){
if ( $trainer->id == $this->id_trainer){
$trainerAllowed = true;
}
}
if ( !$trainerAllowed ){
$this->addError($attribute,"Hibás paraméter: edző");
}
}
}

View File

@ -3,12 +3,14 @@
namespace common\modules\event\models; namespace common\modules\event\models;
use common\components\Helper; use common\components\Helper;
use common\components\RoleDefinition;
use Yii; use Yii;
use yii\base\Model; use yii\base\Model;
use yii\data\ActiveDataProvider; use yii\data\ActiveDataProvider;
use common\models\Event; use common\models\Event;
use yii\db\Expression; use yii\db\Expression;
use yii\db\Query; use yii\db\Query;
use yii\rbac\Role;
/** /**
* EventSearch represents the model behind the search form about `common\models\Event`. * EventSearch represents the model behind the search form about `common\models\Event`.
@ -64,6 +66,7 @@ class EventSearch extends Event
'trainer.name as trainer_name', 'trainer.name as trainer_name',
'room.name as room_name', 'room.name as room_name',
'event_type.name as event_type_name', 'event_type.name as event_type_name',
'event_type.theme as event_type_theme',
new Expression('count(event_registration.id) as registration_count') new Expression('count(event_registration.id) as registration_count')
]); ]);
@ -71,7 +74,7 @@ class EventSearch extends Event
$query->innerJoin('trainer', 'event.id_trainer = trainer.id'); $query->innerJoin('trainer', 'event.id_trainer = trainer.id');
$query->innerJoin('room', 'event.id_room = room.id'); $query->innerJoin('room', 'event.id_room = room.id');
$query->innerJoin('event_type', 'event_type.id = event.id_event_type'); $query->innerJoin('event_type', 'event_type.id = event.id_event_type');
$query->leftJoin('event_registration', 'event_registration.id_event = event.id'); $query->leftJoin('event_registration', 'event_registration.id_event = event.id and event_registration.canceled_at is null and event_registration.deleted_at is null ');
$query->groupBy( $query->groupBy(
[ [
'event_id', 'event_id',
@ -86,6 +89,12 @@ class EventSearch extends Event
] ]
); );
if ( RoleDefinition::isTrainer() ){
$query->innerJoin('user_trainer_assignment', 'user_trainer_assignment.id_trainer = trainer.id' );
$query->andWhere(['user_trainer_assignment.id_user' => \Yii::$app->user->id ]);
}
$dataProvider = new ActiveDataProvider([ $dataProvider = new ActiveDataProvider([
'query' => $query, 'query' => $query,
'sort' => [ 'sort' => [

View File

@ -2,13 +2,13 @@
namespace common\modules\event\models\copy; namespace common\modules\event\models\copy;
use common\components\RoleDefinition;
use common\manager\EventRegistrationManager; use common\manager\EventRegistrationManager;
use common\modules\event\manager\EventManager; use common\modules\event\manager\EventManager;
use common\modules\event\models\timetable\TimeTableMonth; use common\modules\event\models\timetable\TimeTableMonth;
use common\modules\event\models\timetable\TimeTableMonthWeek; use common\modules\event\models\timetable\TimeTableMonthWeek;
use customerapi\models\available\EventInterval; use customerapi\models\available\EventInterval;
use DateTime; use DateTime;
use Throwable;
use Yii; use Yii;
use yii\base\Model; use yii\base\Model;
@ -45,7 +45,6 @@ class ClearWeekForm extends Model
/** /**
* @param $params * @param $params
* @throws Throwable
*/ */
public function clear($params){ public function clear($params){
$this->load($params); $this->load($params);
@ -65,10 +64,17 @@ class ClearWeekForm extends Model
$events = $targetWeek->getAllEvents(); $events = $targetWeek->getAllEvents();
$trainers = $eventManager->getAssignedTrainerIDsForPermission();
$eventRegisterManager = new EventRegistrationManager(); $eventRegisterManager = new EventRegistrationManager();
if ( !$eventManager->hasAnyTrainerAllowed($trainers) ){
// no trainers assigned, can't do anything...
return;
}
foreach ($events as $event){ foreach ($events as $event){
if ( $eventManager->isTrainerAllowed($trainers,$event->id_trainer) ){
$eventRegisterManager->deleteEvent($event); $eventRegisterManager->deleteEvent($event);
} }
} }
}
} }

View File

@ -0,0 +1,11 @@
<?php
namespace common\modules\event\models\copy;
use yii\base\BaseObject;
class CopyWeekContext extends BaseObject
{
public $copyWeekForm;
public $copyWeekFormModel;
}

View File

@ -2,6 +2,7 @@
namespace common\modules\event\models\copy; namespace common\modules\event\models\copy;
use common\manager\EventRegistrationManager;
use common\modules\event\manager\EventManager; use common\modules\event\manager\EventManager;
use common\modules\event\models\timetable\TimeTableMonth; use common\modules\event\models\timetable\TimeTableMonth;
use common\modules\event\models\timetable\TimeTableMonthDay; use common\modules\event\models\timetable\TimeTableMonthDay;
@ -38,6 +39,8 @@ class CopyWeekSearch extends Model
public $sourceTimeTable; public $sourceTimeTable;
public $targetTimeTable; public $targetTimeTable;
public $selectedEvents;
/** /**
* @inheritdoc * @inheritdoc
@ -45,7 +48,8 @@ class CopyWeekSearch extends Model
public function rules() public function rules()
{ {
return [ return [
[['sourceDateString','targetDateString'], 'required'], [['selectedEvents'], 'safe'],
[['sourceDateString', 'targetDateString'], 'required'],
[['sourceDateString',], 'date', 'format' => Yii::$app->formatter->dateFormat, 'timestampAttribute' => 'timestampSource', 'timeZone' => 'UTC'], [['sourceDateString',], 'date', 'format' => Yii::$app->formatter->dateFormat, 'timestampAttribute' => 'timestampSource', 'timeZone' => 'UTC'],
[['targetDateString',], 'date', 'format' => Yii::$app->formatter->dateFormat, 'timestampAttribute' => 'timestampTarget', 'timeZone' => 'UTC'], [['targetDateString',], 'date', 'format' => Yii::$app->formatter->dateFormat, 'timestampAttribute' => 'timestampTarget', 'timeZone' => 'UTC'],
]; ];
@ -77,18 +81,26 @@ class CopyWeekSearch extends Model
$targetDate = new DateTime(); $targetDate = new DateTime();
$targetDate->setTimestamp($this->timestampTarget); $targetDate->setTimestamp($this->timestampTarget);
} }
$this->sourceInterval = EventInterval::createInterval($sourceDate,7,7); $this->sourceInterval = EventInterval::createInterval($sourceDate, 7, 7);
$this->targetInterval = EventInterval::createInterval($targetDate,7,7); $this->targetInterval = EventInterval::createInterval($targetDate, 7, 7);
$eventManager = new EventManager(); $eventManager = new EventManager();
$this->sourceTimeTable = $eventManager->loadTimeTable($this->sourceInterval,"display"); $this->sourceTimeTable = $eventManager->loadTimeTable($this->sourceInterval, "display");
$this->targetTimeTable = $eventManager->loadTimeTable($this->targetInterval,"display"); $this->targetTimeTable = $eventManager->loadTimeTable($this->targetInterval, "display");
// if ( !isset($_POST['command'])){
// $this->selectedEvents = [];
// $events = $this->sourceTimeTable->getAllEvents();
// foreach ($events as $event){
// $this->selectedEvents[] = $event->id;
// }
// }
} }
/** /**
* @throws Exception * @throws Exception
*/ */
public function save(){ public function save()
{
$sourceDate = new DateTime(); $sourceDate = new DateTime();
$sourceDate->setTimestamp($this->timestampSource); $sourceDate->setTimestamp($this->timestampSource);
@ -98,19 +110,20 @@ class CopyWeekSearch extends Model
$targetDate->setTimestamp($this->timestampTarget); $targetDate->setTimestamp($this->timestampTarget);
$targetDate->modify('this week'); $targetDate->modify('this week');
$this->sourceInterval = EventInterval::createInterval($sourceDate,7,7); $this->sourceInterval = EventInterval::createInterval($sourceDate, 7, 7);
$this->targetInterval = EventInterval::createInterval($targetDate,7,7); $this->targetInterval = EventInterval::createInterval($targetDate, 7, 7);
// load the time table objects for source and target interval // load the time table objects for source and target interval
$eventManager = new EventManager(); $eventManager = new EventManager();
$this->sourceTimeTable = $eventManager->loadTimeTable($this->sourceInterval,"display"); $this->sourceTimeTable = $eventManager->loadTimeTable($this->sourceInterval, "display");
$this->targetTimeTable = $eventManager->loadTimeTable($this->targetInterval,"display"); $this->targetTimeTable = $eventManager->loadTimeTable($this->targetInterval, "display");
$sourceWeek = array_values( $this->sourceTimeTable->weeks )[0]; $sourceWeek = array_values($this->sourceTimeTable->weeks)[0];
$targetWeek = array_values( $this->targetTimeTable->weeks )[0]; $targetWeek = array_values($this->targetTimeTable->weeks)[0];
$eventRegistrationManager = new EventRegistrationManager();
// Iterate over all the week days: monday, tuesday, ... // Iterate over all the week days: monday, tuesday, ...
foreach (EventInterval::weekdays as $weekday ){ foreach (EventInterval::weekdays as $weekday) {
// this is very ugly // this is very ugly
// it returns eg.: $sourceWeek->monday , $sourceWeek->tuesday... // it returns eg.: $sourceWeek->monday , $sourceWeek->tuesday...
/** @var TimeTableMonthDay $sourceDay */ /** @var TimeTableMonthDay $sourceDay */
@ -121,7 +134,16 @@ class CopyWeekSearch extends Model
$sourceEvents = $sourceDay->events; $sourceEvents = $sourceDay->events;
/** @var Event $sourceEvent */ /** @var Event $sourceEvent */
foreach ($sourceEvents as $sourceEvent ){ foreach ($sourceEvents as $sourceEvent) {
$processEvent = true;
if (isset($this->selectedEvents)) {
$processEvent = in_array($sourceEvent->id, $this->selectedEvents);
}
if ($processEvent) {
if ($_POST['command' ] == 'delete') {
$eventRegistrationManager->deleteEvent($sourceEvent);
} else {
$event = new Event(); $event = new Event();
$event->start = $sourceEvent->start; $event->start = $sourceEvent->start;
$event->id_room = $sourceEvent->id_room; $event->id_room = $sourceEvent->id_room;
@ -131,7 +153,7 @@ class CopyWeekSearch extends Model
$event->active = $sourceEvent->active; $event->active = $sourceEvent->active;
$event->deleted_at = $sourceEvent->deleted_at; $event->deleted_at = $sourceEvent->deleted_at;
$start = $this->createDateTime( clone $targetDay->date , new DateTime( '@'. $event->start ) ); $start = $this->createDateTime(clone $targetDay->date, new DateTime('@' . $event->start));
$event->start = $start->getTimestamp(); $event->start = $start->getTimestamp();
// end date is start date + duration // end date is start date + duration
@ -139,7 +161,8 @@ class CopyWeekSearch extends Model
$event->end = $start->getTimestamp() + $eventDuration; $event->end = $start->getTimestamp() + $eventDuration;
$event->save(false); $event->save(false);
}
}
} }
} }
@ -156,11 +179,12 @@ class CopyWeekSearch extends Model
* @return DateTime * @return DateTime
* @throws Exception * @throws Exception
*/ */
private function createDateTime($date,$time){ private function createDateTime($date, $time)
{
$result = new DateTime(); $result = new DateTime();
$result->setDate($date->format('Y'),$date->format('m'),$date->format('d')); $result->setDate($date->format('Y'), $date->format('m'), $date->format('d'));
$result->setTimezone($time->getTimezone()); $result->setTimezone($time->getTimezone());
$result->setTime($time->format('H'),$time->format('i')); $result->setTime($time->format('H'), $time->format('i'));
return $result; return $result;
} }

View File

@ -1,33 +0,0 @@
<?php /** @noinspection PhpUnhandledExceptionInspection */
use common\modules\event\models\copy\CopyWeekSearch;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $model CopyWeekSearch */
?>
<div class="panel panel-default">
<div class="panel-heading">Másolás</div>
<div class="panel-body">
<?php $form = ActiveForm::begin(['options' =>['class' => 'form-inline' ]]); ?>
<?= $form->field($model, 'sourceDateString')->hiddenInput()->label(false) ?>
<?= $form->field($model, 'targetDateString')->hiddenInput()->label(false) ?>
<div class="form-group">
<label for="inpSourceEvent">Forrás hét: </label>
<input type="text" id="inpSourceEvent" disabled class="form-control" value="<?=$model->sourceTimeTable->getWeekByIndex(0)->getWeekString()?>">
</div>
<div class="form-group">
<label for="inpTargetEvent">Cél hét:</label>
<input type="text" id="inpTargetEvent" disabled class="form-control" value="<?=$model->targetTimeTable->getWeekByIndex(0)->getWeekString()?>">
</div>
<?= Html::submitButton( 'Másol', ['class' => 'btn btn-success' ]) ?>
<?php ActiveForm::end(); ?>
</div>
</div>

View File

@ -1,11 +1,15 @@
<?php <?php
use common\modules\event\modelAndView\CreateEventModelAndView;
use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
/* @var $this yii\web\View */ /* @var $this yii\web\View */
/* @var $model common\models\Event */ /* @var $model common\models\Event */
/* @var $form yii\widgets\ActiveForm */ /* @var $form yii\widgets\ActiveForm */
/* @var $modelAndView CreateEventModelAndView */
$event = $modelAndView->event;
?> ?>
<div class="event-form"> <div class="event-form">
@ -14,7 +18,7 @@ use yii\widgets\ActiveForm;
<?php $form = ActiveForm::begin(); ?> <?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'startDateString')->widget(\kartik\widgets\DateTimePicker::classname(), [ <?= $form->field($event, 'startDateString')->widget(\kartik\widgets\DateTimePicker::class, [
'pluginOptions' => [ 'pluginOptions' => [
'autoclose' => true, 'autoclose' => true,
'format' => 'yyyy.mm.dd hh:ii' 'format' => 'yyyy.mm.dd hh:ii'
@ -25,7 +29,7 @@ use yii\widgets\ActiveForm;
]); ]);
?> ?>
<?= $form->field($model, 'endDateString')->widget(\kartik\widgets\DateTimePicker::classname(), [ <?= $form->field($event, 'endDateString')->widget(\kartik\widgets\DateTimePicker::class, [
'pluginOptions' => [ 'pluginOptions' => [
'autoclose' => true, 'autoclose' => true,
'format' => 'yyyy.mm.dd hh:ii' 'format' => 'yyyy.mm.dd hh:ii'
@ -35,16 +39,16 @@ use yii\widgets\ActiveForm;
] ]
]) ])
?> ?>
<?= $form->field($model, 'seat_count')->textInput() ?> <?= $form->field($event, 'seat_count')->textInput() ?>
<?= $form->field($model, 'id_room')->dropDownList(\common\models\Room::roomOptions(false, true)) ?> <?= $form->field($event, 'id_room')->dropDownList(\common\models\Room::roomOptions(false, true)) ?>
<?= $form->field($model, 'id_trainer')->dropDownList(\common\models\Trainer::trainerOptions(false, true)) ?> <?= $form->field($event, 'id_trainer')->dropDownList(\common\models\Trainer::trainerOptions(false, true, $modelAndView->trainers)) ?>
<?= $form->field($model, 'id_event_type')->dropDownList(\common\models\EventType::eventTypeOptions(false, true)) ?> <?= $form->field($event, 'id_event_type')->dropDownList(\common\models\EventType::eventTypeOptions(false, true)) ?>
<div class="form-group"> <div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('event', 'Create') : Yii::t('event', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> <?= Html::submitButton($event->isNewRecord ? Yii::t('event', 'Create') : Yii::t('event', 'Update'), ['class' => $event->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div> </div>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>

View File

@ -1,7 +1,10 @@
<?php /** @noinspection PhpUnhandledExceptionInspection */ <?php /** @noinspection PhpUnhandledExceptionInspection */
use common\modules\event\models\copy\CopyWeekContext;
use common\modules\event\models\copy\CopyWeekSearch; use common\modules\event\models\copy\CopyWeekSearch;
use common\modules\event\widgets\timetable\TimeTableMonthView; use common\modules\event\widgets\timetable\TimeTableMonthView;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */ /* @var $this yii\web\View */
/* @var $tableHeaders string */ /* @var $tableHeaders string */
@ -12,11 +15,56 @@ use common\modules\event\widgets\timetable\TimeTableMonthView;
<?php <?php
echo $this->render('_copy_week_search', ['model' => $model]); echo $this->render('_copy_week_search', ['model' => $model]);
echo $this->render('_copy_week_form', ['model' => $model]);
?> ?>
<?php $form = ActiveForm::begin(['options' =>['class' => 'form-inline' ]]); ?>
<div class="panel panel-default">
<div class="panel-heading">Másolás</div>
<div class="panel-body">
<?= $form->field($model, 'sourceDateString')->hiddenInput()->label(false) ?>
<?= $form->field($model, 'targetDateString')->hiddenInput()->label(false) ?>
<div class="form-group">
<label for="inpSourceEvent">Forrás hét: </label>
<input type="text" id="inpSourceEvent" disabled class="form-control" value="<?=$model->sourceTimeTable->getWeekByIndex(0)->getWeekString()?>">
</div>
<div class="form-group">
<label for="inpTargetEvent">Cél hét:</label>
<input type="text" id="inpTargetEvent" disabled class="form-control" value="<?=$model->targetTimeTable->getWeekByIndex(0)->getWeekString()?>">
</div>
<?= Html::submitButton( 'Forrás hét másolása', ['class' => 'btn btn-success', 'value' => 'copy', 'name' => 'command' ]) ?>
<?= Html::submitButton( 'Forrás hét törlése', ['class' => 'btn btn-danger', 'value' => 'delete', 'name' => 'command' ]) ?>
<p>
<small>
Ha egy esemény sincsen kiválasztva, akkor a másolás/törlés, minden eseményt érinteni fog.
(Nincs esemény kiválasztva = Minden esemény kiválasztva)
</small>
</p>
<p>
<small>Ha valamelyik esemény ki van választva, akkor a másolás/törlés, csak a kiválasztott esemény(eke)t fogja érinteni</small>
</p>
<p>
<small><strong>Esemény törlése:</strong> a már regisztrált vendégek kártyájára visszakerül az alkalom</small>
</p>
</div>
</div>
<h2>Forrás hét</h2> <h2>Forrás hét</h2>
<?= TimeTableMonthView::widget(['timeTable' => $model->sourceTimeTable]) ?> <?= TimeTableMonthView::widget(
[
'timeTable' => $model->sourceTimeTable,
'copyWeekContext' =>new CopyWeekContext(
[
'copyWeekForm' => $form,
'copyWeekFormModel' => $model
]
)
]
) ?>
<?php ActiveForm::end(); ?>
<h2>Cél hét</h2> <h2>Cél hét</h2>
<?= TimeTableMonthView::widget(['timeTable' => $model->targetTimeTable]) ?> <?= TimeTableMonthView::widget(['timeTable' => $model->targetTimeTable]) ?>

View File

@ -4,7 +4,7 @@ use yii\helpers\Html;
/* @var $this yii\web\View */ /* @var $this yii\web\View */
/* @var $model common\models\Event */ /* @var $modelAndView common\modules\event\modelAndView\CreateEventModelAndView */
$this->title = Yii::t('event', 'Create Event'); $this->title = Yii::t('event', 'Create Event');
$this->params['breadcrumbs'][] = ['label' => Yii::t('event', 'Events'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => Yii::t('event', 'Events'), 'url' => ['index']];
@ -15,7 +15,7 @@ $this->params['breadcrumbs'][] = $this->title;
<h1><?= Html::encode($this->title) ?></h1> <h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [ <?= $this->render('_form', [
'model' => $model, 'modelAndView' => $modelAndView,
]) ?> ]) ?>
</div> </div>

View File

@ -16,7 +16,7 @@ if ( $permissions->allowCreate ){
$indexTableTemplateButtons[] = '{update}'; $indexTableTemplateButtons[] = '{update}';
} }
$indexTableTemplateButtons[] = '{reserve-card}'; $indexTableTemplateButtons[] = '{reserve-card}';
$indexTableTemplateButtons[] = '{equipment-types-assignment}'; //$indexTableTemplateButtons[] = '{equipment-types-assignment}';
?> ?>
@ -63,7 +63,12 @@ $indexTableTemplateButtons[] = '{equipment-types-assignment}';
], ],
[ [
'attribute' => 'event_type_name', 'attribute' => 'event_type_name',
'label' => \Yii::t('event', 'Id Event Type') 'label' => \Yii::t('event', 'Id Event Type'),
'value' => function ($model, $key, $index, $column){
return "<span style='margin-right: 3px; display: inline-block; width: 1rem; height: 1rem;' class='event-theme-active-". $model['event_type_theme']."'></span>".$model['event_type_name'] ;
}
,
'format' => 'raw'
], ],
[ [
'attribute' => 'event_start', 'attribute' => 'event_start',
@ -148,16 +153,19 @@ $indexTableTemplateButtons[] = '{equipment-types-assignment}';
'aria-label' => Yii::t('yii', 'Register'), 'aria-label' => Yii::t('yii', 'Register'),
'data-pjax' => '0', 'data-pjax' => '0',
]; ];
if ( isset($model['event_deleted_at']) ){
return "";
}
return Html::a('<span class="glyphicon glyphicon-user"></span>', $url, $options); return Html::a('<span class="glyphicon glyphicon-user"></span>', $url, $options);
}, },
'equipment-types-assignment' => function ($url, $model, $key) { // 'equipment-types-assignment' => function ($url, $model, $key) {
$options = [ // $options = [
'title' => Yii::t('yii', 'Equipment Types'), // 'title' => Yii::t('yii', 'Equipment Types'),
'aria-label' => Yii::t('yii', 'Equipment Types'), // 'aria-label' => Yii::t('yii', 'Equipment Types'),
'data-pjax' => '0', // 'data-pjax' => '0',
]; // ];
return Html::a('<span class="glyphicon glyphicon-wrench"></span>', $url, $options); // return Html::a('<span class="glyphicon glyphicon-wrench"></span>', $url, $options);
} // }
] ]
], ],

View File

@ -1,13 +1,14 @@
<?php <?php
use common\modules\event\modelAndView\CreateEventModelAndView;
use yii\helpers\Html; use yii\helpers\Html;
/* @var $this yii\web\View */ /* @var $this yii\web\View */
/* @var $model common\models\Event */ /* @var $modelAndView CreateEventModelAndView */
$this->title = Yii::t('event', 'Update Event:') . ' #' . $model->id; $this->title = Yii::t('event', 'Update Event:') . ' #' . $modelAndView->event->id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('event', 'Events'), 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => Yii::t('event', 'Events'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]]; $this->params['breadcrumbs'][] = ['label' => $modelAndView->event->id, 'url' => ['view', 'id' => $modelAndView->event->id]];
$this->params['breadcrumbs'][] = Yii::t('event', 'Update'); $this->params['breadcrumbs'][] = Yii::t('event', 'Update');
?> ?>
<div class="event-update"> <div class="event-update">
@ -15,7 +16,7 @@ $this->params['breadcrumbs'][] = Yii::t('event', 'Update');
<h1><?= Html::encode($this->title) ?></h1> <h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [ <?= $this->render('_form', [
'model' => $model, 'modelAndView' => $modelAndView
]) ?> ]) ?>
</div> </div>

View File

@ -187,19 +187,19 @@ function getCommonColumnsHtmlOptions($model)
]; ];
return Html::a('<span class="glyphicon glyphicon-ban-circle"></span>', $url, $options); return Html::a('<span class="glyphicon glyphicon-ban-circle"></span>', $url, $options);
}, },
'delete-registration' => function ($url, $model) { // 'delete-registration' => function ($url, $model) {
if (isset($model['event_registration_canceled_at'])) { // if (isset($model['event_registration_canceled_at'])) {
return ""; // return "";
} // }
$options = [ // $options = [
'title' => Yii::t('yii', 'Delete'), // 'title' => Yii::t('yii', 'Delete'),
'aria-label' => Yii::t('yii', 'Delete'), // 'aria-label' => Yii::t('yii', 'Delete'),
'data-confirm' => Yii::t('event', 'Are you sure you want to delete this item? Usage count will be restored!'), // 'data-confirm' => Yii::t('event', 'Are you sure you want to delete this item? Usage count will be restored!'),
'data-method' => 'post', // 'data-method' => 'post',
'data-pjax' => '0', // 'data-pjax' => '0',
]; // ];
return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, $options); // return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, $options);
}, // },
] ]
], ],

View File

@ -1,5 +1,6 @@
<?php <?php
namespace common\modules\event\widgets\day; namespace common\modules\event\widgets\day;
use common\modules\event\models\copy\CopyWeekContext;
use common\modules\event\models\timetable\TimeTableMonthDay; use common\modules\event\models\timetable\TimeTableMonthDay;
use yii\bootstrap\Widget; use yii\bootstrap\Widget;
@ -11,13 +12,15 @@ use yii\bootstrap\Widget;
* @package common\modules\event\widgets * @package common\modules\event\widgets
* *
* @property TimeTableMonthDay $day * @property TimeTableMonthDay $day
* @property CopyWeekContext $copyWeekContext
*/ */
class TimeTableMonthDayView extends Widget class TimeTableMonthDayView extends Widget
{ {
public $day; public $day;
public $copyWeekContext;
public function run(){ public function run(){
return $this->render('_day', [ 'day' => $this->day]); return $this->render('_day', [ 'day' => $this->day,'copyWeekContext' => $this->copyWeekContext]);
} }

View File

@ -1,5 +1,6 @@
<?php <?php
/* @var $day TimeTableMonthDay */ /* @var $day TimeTableMonthDay */
/* @var $copyWeekContext \common\modules\event\models\copy\CopyWeekContext */
use common\models\Event; use common\models\Event;
use common\modules\event\models\timetable\TimeTableMonthDay; use common\modules\event\models\timetable\TimeTableMonthDay;
@ -15,6 +16,6 @@ use common\modules\event\widgets\event\EventView;
} else { } else {
/** @var Event $event */ /** @var Event $event */
foreach ($day->events as $event) { foreach ($day->events as $event) {
echo EventView::widget(['event' => $event]); echo EventView::widget(['event' => $event, 'copyWeekContext' => $copyWeekContext]);
} }
} ?> } ?>

View File

@ -1,6 +1,8 @@
<?php <?php
namespace common\modules\event\widgets\event; namespace common\modules\event\widgets\event;
use common\helpers\AppDateTimeHelper;
use common\models\Event; use common\models\Event;
use common\modules\event\models\copy\CopyWeekContext;
use DateTime; use DateTime;
use yii\bootstrap\Widget; use yii\bootstrap\Widget;
@ -10,6 +12,7 @@ use yii\bootstrap\Widget;
* @package common\modules\event\widgets * @package common\modules\event\widgets
* *
* @property Event $event * @property Event $event
* @property CopyWeekContext $copyWeekContext
*/ */
class EventView extends Widget class EventView extends Widget
{ {
@ -17,13 +20,13 @@ class EventView extends Widget
public $start; public $start;
public $end; public $end;
public $copyWeekContext;
public function init(){ public function init(){
parent::init(); parent::init();
if ( isset($this->event )){ if ( isset($this->event )){
$this->start = new DateTime(); $this->start = AppDateTimeHelper::convertUnixTimeToDateTime($this->event->start);
$this->start->setTimestamp($this->event->start); $this->end = AppDateTimeHelper::convertUnixTimeToDateTime($this->event->end);
$this->end = new DateTime();
$this->end->setTimestamp($this->event->end);
} }
} }
@ -33,7 +36,8 @@ class EventView extends Widget
[ [
'event' => $this->event, 'event' => $this->event,
'start' => $this->start, 'start' => $this->start,
'end' => $this->end 'end' => $this->end,
'copyWeekContext' => $this->copyWeekContext
] ]
); );
} }

Some files were not shown because too many files have changed in this diff Show More