bug fixing

This commit is contained in:
Roland Schneider 2021-10-06 18:31:56 +02:00
parent ad2be423d9
commit d26581e338
28 changed files with 527 additions and 83 deletions

View File

@ -238,7 +238,7 @@ class AdminMenuStructure
///////////////////////////// /////////////////////////////
// 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']];

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,12 +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(\common\models\EventType::themes()) ?> <?= $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']) ?>
@ -22,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

@ -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

@ -38,6 +38,12 @@ 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 => 'CARD_NOT_FOUND',
@ -77,7 +83,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 +92,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 +116,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 +125,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);
} }
$selectedTicket->consumeReservationCount(1); try {
$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;
@ -174,7 +190,7 @@ class EventRegistrationManager extends BaseObject
{ {
$registration = EventRegistration::find()->andWhere(['id' => $idRegistration])->one(); $registration = EventRegistration::find()->andWhere(['id' => $idRegistration])->one();
if ( $registration === null) { 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;
@ -187,15 +203,44 @@ class EventRegistrationManager extends BaseObject
public function cancelRegistration($registration) public function cancelRegistration($registration)
{ {
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', 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', self::ALREADY_DELETED);
} }
$registration->canceled_at = date('Y-m-d H:i:s'); $event = Event::findOne($registration->id_event);
$registration->save(false);
if (!isset($event)) {
throw new BadRequestHttpException('The reservation is already deleted', self::EVENT_NOT_FOUND);
}
$tx = \Yii::$app->db->beginTransaction();
try {
$now = strtotime("now UTC");
$timeUntilEventStart = $event->start - $now;
if ( $timeUntilEventStart < 30 * 60){
throw new BadRequestHttpException('The reservation is already deleted', self::CANCEL_TIME_LIMIT_REACHED);
}
$registration->canceled_at = date('Y-m-d H:i:s', $now);
$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);
$tx->commit();
} catch (\Exception $e) {
$tx->rollBack();
throw $e;
}
} }
@ -240,7 +285,7 @@ class EventRegistrationManager extends BaseObject
// 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($registrations) === 0) {
$event->delete(); $event->delete();
} else { } else {
// ///////////////////////////// // /////////////////////////////

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,8 +158,6 @@ 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
*/ */
@ -174,7 +175,9 @@ class Event extends ActiveRecord
* @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()
@ -188,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

@ -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 száma'),
'reservation_count' => Yii::t('common/transfer', 'Foglalások száma'),
]; ];
} }
@ -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,7 @@
namespace common\models; namespace common\models;
use common\components\RoleDefinition;
use common\helpers\AppArrayHelper; use common\helpers\AppArrayHelper;
use Yii; use Yii;
use yii\behaviors\TimestampBehavior; use yii\behaviors\TimestampBehavior;
@ -80,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')];
@ -92,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

@ -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

@ -2,14 +2,18 @@
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\EventRegistrationEquipmentTypeAssignment;
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;
@ -21,6 +25,7 @@ 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;
@ -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,33 @@ class EventController extends Controller
*/ */
public function actionCreate() public function actionCreate()
{ {
$model = new Event(); $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 +166,30 @@ class EventController extends Controller
*/ */
public function actionUpdate($id) public function actionUpdate($id)
{ {
$model = $this->findModel($id); $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
]); ]);
} }
@ -284,7 +322,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 +336,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());
@ -320,10 +359,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

@ -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

@ -65,6 +65,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')
]); ]);
@ -87,6 +88,11 @@ class EventSearch extends Event
] ]
); );
if ( !RoleDefinition::isAdmin()){
$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,

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

@ -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

@ -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',

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

@ -17,7 +17,12 @@ if (!isset($event)) {
<div class="alert alert-success"> <div class="alert alert-success">
<?= Html::a( $start->format('H:i') .'-' . $end->format('H:i') , Url::toRoute(['event/update', 'id' => $event->id ] ) ) ?> <?= Html::a( $start->format('H:i') .'-' . $end->format('H:i') , Url::toRoute(['event/update', 'id' => $event->id ] ) ) ?>
<br> <br>
<?= Html::a( $event->eventType->name , Url::toRoute(['/event-type/view', 'id'=> $event->eventType->id])) ?> <?= Html::a( $event->eventType->name ,
Url::toRoute(['/event-type/view', 'id'=> $event->eventType->id]),
[
'class' => 'event-theme-active-' . $event->eventType->theme,
'style' => 'padding: 3px 6px; border-radius: 1rem;'
]) ?>
<br> <br>
<?= Html::a( $event->room->name , Url::toRoute(['/room/view', 'id' => $event->room->id]) )?> <?= Html::a( $event->room->name , Url::toRoute(['/room/view', 'id' => $event->room->id]) )?>
<br> <br>

View File

@ -0,0 +1,52 @@
<?php
use yii\db\Migration;
/**
* Class m211003_183453_create_table_user_trainer_assignment
*/
class m211003_183453_create_table_user_trainer_assignment extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
// http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable('{{%user_trainer_assignment}}', [
'id_user_trainer_assignment' => $this->primaryKey(),
'id_user' => $this->integer(11) ,
'id_trainer' => $this->integer(11) ,
], $tableOptions);
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
echo "m211003_183453_create_table_user_trainer_assignment cannot be reverted.\n";
return false;
}
/*
// Use up()/down() to run migration code without a transaction.
public function up()
{
}
public function down()
{
echo "m211003_183453_create_table_user_trainer_assignment cannot be reverted.\n";
return false;
}
*/
}

View File

@ -0,0 +1,42 @@
<?php
use yii\db\Migration;
/**
* Class m211004_162117_alter_table_event_add_column_id_user
*/
class m211004_162117_alter_table_event_add_column_id_user extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
$this->addColumn("event","id_user", "int(11)");
}
/**
* {@inheritdoc}
*/
public function safeDown()
{
echo "m211004_162117_alter_table_event_add_column_id_user cannot be reverted.\n";
return false;
}
/*
// Use up()/down() to run migration code without a transaction.
public function up()
{
}
public function down()
{
echo "m211004_162117_alter_table_event_add_column_id_user cannot be reverted.\n";
return false;
}
*/
}

View File

@ -22,6 +22,7 @@ export class JwtInterceptor implements HttpInterceptor {
const token = this.store.selectSnapshot<string>(AppState.getToken); const token = this.store.selectSnapshot<string>(AppState.getToken);
console.info("using token: ", token);
if (token) { if (token) {
// clone the incoming request and add JWT token in the cloned request's Authorization Header // clone the incoming request and add JWT token in the cloned request's Authorization Header
request = request.clone({ request = request.clone({

View File

@ -22,6 +22,11 @@ export const RegistrationErrors ={
MAX_SEAT_COUNT_EXCEEDED : 8, MAX_SEAT_COUNT_EXCEEDED : 8,
EVENT_UNAVAILABLE : 9, EVENT_UNAVAILABLE : 9,
ALREADY_REGISTERED : 10, ALREADY_REGISTERED : 10,
EVENT_START_DATE_IN_PAST : 11,
EVENT_NOT_FOUND: 12,
ALREADY_CANCELLED: 13,
ALREADY_DELETED: 14,
CANCEL_TIME_LIMIT_REACHED: 15
} }
export interface TimeTableFilter { export interface TimeTableFilter {

View File

@ -1,7 +1,7 @@
<fit-navigation></fit-navigation> <fit-navigation></fit-navigation>
<div class="container " > <div class="container " >
<div class="row "> <div class="row ">
<div class="col-12">Bejelentkezve: {{username | async}}</div> <div class="col-12">Bejelentkezve: {{(user | async).username}} ({{(user | async).card}})</div>
</div> </div>
<router-outlet></router-outlet> <router-outlet></router-outlet>
</div> </div>

View File

@ -1,6 +1,6 @@
import { Component, OnInit } from '@angular/core'; import { Component, OnInit } from '@angular/core';
import {Select} from "@ngxs/store"; import {Select} from "@ngxs/store";
import {AppState} from "../../state/app.state"; import {AppState, Identity} from "../../state/app.state";
import {Observable} from "rxjs"; import {Observable} from "rxjs";
@Component({ @Component({
@ -9,7 +9,7 @@ import {Observable} from "rxjs";
styleUrls: ['./secured-layout.component.scss'] styleUrls: ['./secured-layout.component.scss']
}) })
export class SecuredLayoutComponent implements OnInit { export class SecuredLayoutComponent implements OnInit {
@Select(AppState.getUsername) public username: Observable<string>; @Select(AppState.getUser) public user: Observable<Identity>;
constructor() { } constructor() { }

View File

@ -89,11 +89,15 @@ export class EventDetailsComponent implements OnInit {
break; break;
case RegistrationErrors.MAX_SEAT_COUNT_EXCEEDED: case RegistrationErrors.MAX_SEAT_COUNT_EXCEEDED:
case RegistrationErrors.TICKET_INSUFFICIENT: case RegistrationErrors.TICKET_INSUFFICIENT:
case RegistrationErrors.TICKET_NOT_FOUND:
message = "Nem rendelkezik megfelelő bérlettel!" message = "Nem rendelkezik megfelelő bérlettel!"
break; break;
case RegistrationErrors.NO_FREE_SEATS: case RegistrationErrors.NO_FREE_SEATS:
message = "Nincs több szabad hely!" message = "Nincs több szabad hely!"
break; break;
case RegistrationErrors.EVENT_START_DATE_IN_PAST:
message = "Nem lehet regisztrálni! Az esemény már elkezdődött!"
break;
} }
} }
@ -109,8 +113,18 @@ export class EventDetailsComponent implements OnInit {
this.toastr.success("Sikeres lemondás", "Lemondás") this.toastr.success("Sikeres lemondás", "Lemondás")
this.goBack(); this.goBack();
}, },
() => { (error) => {
this.toastr.error("Hiba történt", "Lemondás") let status = error.status;
let code = error?.error?.code;
let message = "Hiba történt";
if (status == 400) {
switch (code) {
case RegistrationErrors.CANCEL_TIME_LIMIT_REACHED:
message = "Már nem lehet lemondani a regisztrációt!";
break;
}
}
this.toastr.error(message, "Lemondás")
}); });
} }

View File

@ -11,11 +11,11 @@
</div> </div>
<div class="row"> <div class="row">
<div class="col-lg-3 col-sm-12 app-font-weight-bold"><span class="title">Edzés kezdési időpontja</span></div> <div class="col-lg-3 col-sm-12 app-font-weight-bold"><span class="title">Edzés kezdési időpontja</span></div>
<div class="col-lg-9 col-sm-12"><span>{{registration.event.start * 1000 | date:'yyyy.MM.dd HH:mm'}}</span></div> <div class="col-lg-9 col-sm-12"><span>{{registration.event.start | eventDate:'datetime'}}</span></div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-lg-3 col-sm-12 app-font-weight-bold"><span class="title">Edzés vége</span></div> <div class="col-lg-3 col-sm-12 app-font-weight-bold"><span class="title">Edzés vége</span></div>
<div class="col-lg-9 col-sm-12"><span>{{registration.event.end * 1000 | date:'yyyy.MM.dd HH:mm'}}</span></div> <div class="col-lg-9 col-sm-12"><span>{{registration.event.end | eventDate:'datetime'}}</span></div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-lg-3 col-sm-12 app-font-weight-bold"><span class="title">Férőhelyek száma</span></div> <div class="col-lg-3 col-sm-12 app-font-weight-bold"><span class="title">Férőhelyek száma</span></div>

View File

@ -6,9 +6,12 @@ import {
import {TimeTableFilter} from "../app.types"; import {TimeTableFilter} from "../app.types";
import jwtDecode, {JwtPayload} from "jwt-decode"; import jwtDecode, {JwtPayload} from "jwt-decode";
export interface Identity{
export interface AppStateModel {
username: string; username: string;
card: string;
}
export interface AppStateModel {
user: Identity
token: string; token: string;
filterTimeTable: FilterTimeTableAction; filterTimeTable: FilterTimeTableAction;
} }
@ -17,7 +20,7 @@ export interface AppStateModel {
@State<AppStateModel>({ @State<AppStateModel>({
name: "app", name: "app",
defaults: { defaults: {
username: null, user: null,
token: null, token: null,
filterTimeTable: { filterTimeTable: {
idTrainer: -1, idTrainer: -1,
@ -37,8 +40,8 @@ export class AppState {
} }
@Selector() @Selector()
public static getUsername(state: AppStateModel): string { public static getUser(state: AppStateModel): Identity {
return state.username; return state.user;
} }
@Selector() @Selector()
@ -60,18 +63,22 @@ export class AppState {
@Action(LoginAction) @Action(LoginAction)
dispatchLogin(ctx: StateContext<AppStateModel>, {token}: LoginAction): void { dispatchLogin(ctx: StateContext<AppStateModel>, {token}: LoginAction): void {
let username = null; let username = null;
let card = null;
try { try {
const decoded = jwtDecode<JwtPayload & { username: string }>(token); const decoded = jwtDecode<JwtPayload & { username: string , card: string}>(token);
username = decoded?.username; username = decoded?.username;
card = decoded?.card;
} catch (e) { } catch (e) {
// user not logged in // user not logged in
token = null; token = null;
username = null;
card = null;
} }
ctx.patchState({ ctx.patchState({
username: username, user: (username && card) ? {username: username, card: card } : null,
token: token token: token
}); });
} }

View File

@ -55,6 +55,7 @@ class LoginController extends CustomerApiController
->expiresAt($time + 3600)// Configures the expiration time of the token (exp claim) ->expiresAt($time + 3600)// Configures the expiration time of the token (exp claim)
->withClaim('uid', $form->getCustomer()->getId())// Configures a new claim, called "uid" ->withClaim('uid', $form->getCustomer()->getId())// Configures a new claim, called "uid"
->withClaim('username', $form->getCustomer()->email)// Configures a new claim, called "username" ->withClaim('username', $form->getCustomer()->email)// Configures a new claim, called "username"
->withClaim('card', $form->getCustomer()->card->number )// Configures a new claim, called "username"
->getToken($signer, $key); // Retrieves the generated token ->getToken($signer, $key); // Retrieves the generated token
return $this->asJson([ return $this->asJson([

View File

@ -6,61 +6,63 @@ use yii\helpers\Html;
?> ?>
<div class="ticket-form"> <div class="ticket-form">
<?php if ( $model->status != Ticket::STATUS_DELETED){?> <?php if ( $model->status != Ticket::STATUS_DELETED){?>
<?php <?php
$form = ActiveForm::begin ( [ ] ) $form = ActiveForm::begin ( [ ] )
// 'id' => 'ticket_form', // 'id' => 'ticket_form',
; ;
?> ?>
<?php <?php
$options = Ticket::statuses (); $options = Ticket::statuses ();
unset ( $options [Ticket::STATUS_DELETED] ); unset ( $options [Ticket::STATUS_DELETED] );
echo $form->field ( $model, 'status' )->dropDownList ( $options ); echo $form->field ( $model, 'status' )->dropDownList ( $options );
?> ?>
<div class="form-group"> <div class="form-group">
<?= Html::submitButton( "Módosítás", ['class' => 'btn btn-success' ]) ?> <?= Html::submitButton( "Módosítás", ['class' => 'btn btn-success' ]) ?>
</div> </div>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>
<?php } else{ echo "Törölt bérlet"; }?> <?php } else{ echo "Törölt bérlet"; }?>
</div> </div>
<?php <?php
$attributes = [ $attributes = [
'id_ticket', 'id_ticket',
[ [
'attribute' => 'id_user', 'attribute' => 'id_user',
'value' => $model->user->username 'value' => $model->user->username
] ]
, ,
[ [
'attribute' => 'id_ticket_type', 'attribute' => 'id_ticket_type',
'value' => $model->ticketTypeName 'value' => $model->ticketTypeName
] ]
, ,
[ [
'attribute' => 'id_account', 'attribute' => 'id_account',
'value' => $model->accountName 'value' => $model->accountName
] ]
, ,
[ [
'attribute' => 'id_discount', 'attribute' => 'id_discount',
'value' => $model->discountName 'value' => $model->discountName
] ]
, ,
'start:datetime', 'start:datetime',
'end:datetime', 'end:datetime',
'max_usage_count', 'max_usage_count',
'usage_count', 'usage_count',
'max_reservation_count',
'reservation_count',
// [ // [
// 'attribute' => 'status', // 'attribute' => 'status',
// 'value' => $model->statusName // 'value' => $model->statusName
@ -68,7 +70,7 @@ $attributes = [
'price_brutto', 'price_brutto',
'comment:raw', 'comment:raw',
'created_at', 'created_at',
'updated_at' 'updated_at'
]; ];