/**
  * Displays a children for one person
  * @param integer $personId
  * @return mixed
  */
 public function actionView($personId)
 {
     $model = PersonsRecord::findOne($personId);
     $searchModel = new PersonsChildrenSearch();
     $searchModel->PersonID = $personId;
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
     return $this->render('view', ['model' => $model, 'searchModel' => $searchModel, 'dataProvider' => $dataProvider]);
 }
 public function actionPerson($id)
 {
     Url::remember('', 'actions-redirect');
     $person = PersonsRecord::findOne($id);
     $searchModel = new FinanceSearch();
     $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
     $dataProvider->query->andWhere(['ContractorID' => $id]);
     return $this->render('person', ['dataProvider' => $dataProvider, 'searchModel' => $searchModel, 'person' => $person]);
 }
Example #3
0
 public function rules()
 {
     return [[['HardID'], function ($attribute) {
     }], ['dateRange', 'required'], ['dateRange', function ($attribute) {
         list($this->dateFrom, $this->dateTo) = preg_split('/\\s+-\\s+/', $this->dateRange);
         $formatter = Yii::$app->formatter;
         $this->dateFrom = $formatter->asDatetime($this->dateFrom, 'yyyy-MM-dd HH:mm:ss');
         $this->dateTo = $formatter->asDatetime($this->dateTo, 'yyyy-MM-dd HH:mm:ss');
     }], [['dateFrom', 'dateTo'], 'safe'], ['PersonID', 'exist', 'targetClass' => PersonsRecord::className(), 'targetAttribute' => 'ID'], ['allowCancelled', 'boolean']];
 }
Example #4
0
 /** @inheritdoc */
 public function rules()
 {
     return ['requiredFields' => [['Login'], 'required', 'on' => 'login'], 'requiredFields2' => [['Login', 'Password'], 'required', 'on' => 'password'], 'loginTrim' => ['Login', 'trim'], 'LoginValidate' => ['Login', function ($attribute) {
         if ($this->user === null) {
             $this->addError($attribute, \Yii::t('user', 'Invalid login or password'));
         } else {
             if ($this->user->isDeleted) {
                 $this->addError($attribute, \Yii::t('user', 'User blocked'));
             } else {
                 if ($this->user->isBlocked) {
                     $this->addError($attribute, \Yii::t('user', 'User blocked'));
                 }
             }
         }
     }, 'on' => 'login'], 'passwordValidate' => ['Password', function ($attribute) {
         if ($this->Password === null) {
             $this->addError($attribute, \Yii::t('user', 'Invalid password'));
         }
         if ($this->user === null) {
             $this->addError($attribute, \Yii::t('user', 'Invalid login or password'));
         } else {
             if ($this->user !== null) {
                 //                    list($password, $hash) = explode(':', $this->user->Password);
                 if (!Yii::$app->getSecurity()->validatePassword($this->Password, $this->user->Password)) {
                     $this->addError($attribute, \Yii::t('user', 'Invalid password'));
                     return;
                 }
                 if ($this->user->isDeleted) {
                     $this->addError($attribute, \Yii::t('user', 'User blocked'));
                 } else {
                     if ($this->user->isBlocked) {
                         $this->addError($attribute, \Yii::t('user', 'User blocked'));
                     } else {
                         if ($this->user->ServiceCard || $this->user->group && $this->user->group->IsService) {
                             //Allow login only for service group
                         } else {
                             $this->addError($attribute, \Yii::t('user', 'You can not log in'));
                         }
                     }
                 }
             }
         }
     }, 'on' => 'password'], 'confirmationValidate' => ['Login', function ($attribute) {
         if ($this->user !== null) {
             $confirmationRequired = $this->module->enableConfirmation && !$this->module->enableUnconfirmedLogin;
             if ($confirmationRequired && !$this->user->getIsConfirmed()) {
                 $this->addError($attribute, \Yii::t('user', 'You need to confirm your email address'));
             }
             //@todo
             if ($this->user->getIsBlocked()) {
                 $this->addError($attribute, \Yii::t('user', 'Your account has been blocked'));
             }
         }
     }], 'rememberMe' => ['rememberMe', 'boolean']];
 }
 /**
  * Reset password for root
  */
 public function actionPassword()
 {
     /** @var PersonsRecord $person */
     $person = PersonsRecord::findOne(1);
     if ($person !== null) {
         $newPassword = $this->prompt('Введите новый пароль для ' . $person->Login . ':', ['required' => true, 'default' => 'root', 'validator' => function ($input, $error) use($person) {
             if (!preg_match('/^[-a-zA-Z0-9_\\.]+$/', $input)) {
                 $error = 'Wrong try';
                 return false;
             }
             return true;
         }]);
         if ($person->resetPassword($newPassword)) {
             echo "OK!\n";
         } else {
             echo "Error ;(";
         }
     } else {
         echo "Root user not found!";
     }
 }
 /**
  * Step 3
  * @param $hardId
  * @return string|\yii\web\Response
  * @throws HttpException
  */
 public function actionCreateAccount($hardId, $groupId = '')
 {
     /** @var PersonsGroupRecord $group */
     if ($groupId !== '') {
         $group = PersonsGroupRecord::findOne($groupId);
     } else {
         $group = PersonsGroupRecord::getDefault();
     }
     /** @var PersonsRecord $user */
     $user = Yii::createObject(['class' => PersonsRecord::className(), 'scenario' => 'create']);
     /** @var CardForm $card */
     $card = \Yii::createObject(CardForm::className());
     $card->HardID = $hardId;
     if (!$card->isExist()) {
         $card = $card->create();
     } else {
         $card = $card->find();
     }
     if (!$card->ID) {
         throw new HttpException(400, 'Не удалось сохранить номер карты');
     }
     $user->CardID = $card->id;
     $user->GroupID = $group->id;
     $user->ServiceCard = $group->IsService;
     $this->performAjaxValidation($user);
     if ($user->load(Yii::$app->request->post()) && $user->create()) {
         /** @var FinanceRecord $finance */
         $finance = Yii::createObject(FinanceRecord::className());
         $finance->ClassID = 2;
         //Регистраци карты
         $finance->ContractorID = $user->ID;
         $finance->save();
         Yii::$app->getSession()->setFlash('success', Yii::t('user', 'User has been created'));
         return $this->redirect(['/accounts/charge-balance', 'id' => $user->account->id]);
     }
     return $this->render('createAccount', ['user' => $user]);
 }
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getPerson()
 {
     return $this->hasOne(PersonsRecord::className(), ['ID' => 'PersonID']);
 }
 public function actionCreateAccount($hardId, $groupId = '')
 {
     /** @var PersonsGroupRecord $group */
     if ($groupId !== '') {
         $group = PersonsGroupRecord::findOne($groupId);
     } else {
         $group = PersonsGroupRecord::getDefault();
     }
     /** @var PersonsRecord $user */
     $user = Yii::$app->user->identity;
     if ($group->ID < $user->GroupID) {
         throw new ForbiddenHttpException('Вы не можете зарегистрировать карту более высокого уровня');
     }
     /** @var PersonsRecord $user */
     $user = Yii::createObject(['class' => PersonsRecord::className(), 'scenario' => 'create']);
     $user->GroupID = $group->id;
     $user->ServiceCard = $group->IsService;
     //from parent controller (not my behavior)
     $this->performAjaxValidation($user);
     //data already loaded with ajax validation
     if ($user->load(Yii::$app->request->post()) && $user->validate()) {
         $card = null;
         /** @var CardForm $card */
         $cardForm = \Yii::createObject(CardForm::className());
         $cardForm->HardID = $hardId;
         if (!$cardForm->isExist()) {
             $card = $cardForm->create();
         } else {
             if ($cardForm->isUsed()) {
                 throw new HttpException(400, 'Данная карта уже зарегистрирована в системе');
             } else {
                 $card = $cardForm->find();
             }
         }
         if (!$card->ID) {
             throw new HttpException(400, 'Не удалось зарегистрировать карту');
         }
         $user->CardID = $card->id;
         if ($user->create()) {
             /** @var FinanceRecord $finance */
             $finance = Yii::createObject(FinanceRecord::className());
             $finance->ClassID = 2;
             //Регистраци карты
             $finance->ContractorID = $user->ID;
             $finance->save();
             //Yii::$app->getSession()->setFlash('success', Yii::t('user', 'User has been created'));
             return $this->redirect(['/person/children', 'personId' => $user->id]);
         }
     }
     return $this->render('createAccount', ['user' => $user]);
 }
Example #9
0
<?php

use yii\bootstrap\ActiveForm;
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\cf\FinanceSearch */
/* @var $form yii\widgets\ActiveForm */
$formatter = \Yii::$app->formatter;
if (!empty($model->dateFrom)) {
    $model->dateFrom = $formatter->asDatetime($model->dateFrom, 'dd.MM.yyyy HH:mm');
    $model->dateTo = $formatter->asDatetime($model->dateTo, 'dd.MM.yyyy HH:mm');
}
$persons = \common\models\cf\PersonsRecord::find()->select(['CONCAT(FirstName, " ", LastName)', 'ID'])->where(['GroupID' => \common\models\cf\PersonsGroupRecord::KASHIER])->indexBy('ID')->column();
?>

<div class="finance-record-search">

    <?php 
$form = ActiveForm::begin(['enableAjaxValidation' => false, 'options' => ['id' => 'finance-record-search']]);
?>

    <?php 
echo $form->field($model, 'dateRange')->widget(\kartik\daterange\DateRangePicker::className(), ['presetDropdown' => true, 'hideInput' => true, 'pluginOptions' => ['timePicker' => true, 'timePicker24Hour' => true, 'format' => 'DD.MM.YYYY HH:mm', 'timePickerIncrement' => 1, 'opens' => 'right', 'locale' => ['format' => 'DD.MM.YYYY HH:mm']], 'pluginEvents' => ['apply.daterangepicker' => "function(e) {\n\n            }"]]);
?>
    <?php 
echo $form->field($model, 'PersonID')->dropdownList($persons, ['prompt' => 'Все']);
?>

    <?php 
echo $form->field($model, 'allowCancelled')->checkbox();
?>
Example #10
0
 /**
  * Отмена всех сервисных операций
  */
 public function actionServiceFinances()
 {
     $persons = PersonsRecord::find()->where(['ServiceCard' => 1])->indexBy('ID')->all();
     /** @var PersonsRecord[] $persons */
     echo "Found " . sizeof($persons) . " service persons. Updating finance records...\n";
     $success = 0;
     foreach ($persons as $id => $person) {
         $success += FinanceRecord::updateAll(['CancelAccountID' => $id], ['ContractorID' => $id]);
     }
     echo " done updated: " . $success . "\n";
 }
 /** @inheritdoc */
 public function beforeSave($insert)
 {
     if ($insert) {
         //            $this->EventTime = new Expression('NOW()');
         //            $this->CancelTime = new Expression('NOW()');
         $this->AccountantID = Yii::$app->user->id;
         //            $this->RoomID = $session->RoomID;
         $person = PersonsRecord::find()->select('ServiceCard')->where(['ID' => $this->ContractorID, 'ServiceCard' => 1])->one();
         if (null !== $person && $person->ServiceCard) {
             $this->CancelAccountID = $this->ContractorID;
         }
     }
     return parent::beforeSave($insert);
 }
 /**
  * Finds the PersonsRecord model based on its primary key value.
  * If the model is not found, a 404 HTTP exception will be thrown.
  * @param integer $id
  * @return PersonsRecord the loaded model
  * @throws NotFoundHttpException if the model cannot be found
  */
 protected function findModel($id)
 {
     if (($model = PersonsRecord::findOne($id)) !== null) {
         return $model;
     } else {
         throw new NotFoundHttpException('The requested page does not exist.');
     }
 }
 /**
  * @return PersonsRecord
  */
 public function getAccountant()
 {
     return $this->hasOne(PersonsRecord::className(), ['ID' => 'AccountantID']);
 }
 /**
  * @param $from
  * @param $to
  * @param $personId
  * @param $allowCancelled
  * @return string
  * @throws \yii\base\InvalidConfigException
  */
 public function actionGenerate($from, $to, $personId = null, $allowCancelled = false)
 {
     $formatter = Yii::$app->formatter;
     /** @var ReportDataModel $data */
     $data = Yii::createObject(ReportDataModel::className());
     $data->fromDate = $from;
     $data->toDate = $to;
     //приход
     $_income = 0;
     //расход
     $_expense = 0;
     $data->orderCount = 0;
     $charges = [];
     $chargesWithRegistration = [];
     $ordersCash = [];
     /** @var array $objects */
     $objects = ObjectRecord::find()->indexBy('ID')->orderBy('Name')->asArray()->all();
     foreach ($objects as $oID => $obj) {
         $objects[$oID]['cash'] = 0;
     }
     $objectsStat = $objects;
     $objectsByDay = [];
     $data->actions = FinanceClassRecord::find()->indexBy('ID')->orderBy('Type')->where(['Deleted' => '0'])->asArray()->all();
     foreach ($data->actions as $aID => $act) {
         $data->actions[$aID]['count'] = 0;
         $data->actions[$aID]['cash'] = 0;
     }
     $query = FinanceRecord::find()->with('action')->leftJoin('tpersons', 'tfinance.ContractorID=tpersons.ID')->andWhere(['tpersons.Deleted' => 0])->andWhere(['tpersons.ServiceCard' => 0])->andWhere(['>=', 'EventTime', $from])->andWhere(['<=', 'EventTime', $to])->orderBy('EventTime');
     //Включить отмененные
     if (!$allowCancelled) {
         $query->andFilterWhere(['CancelAccountID' => 0]);
     }
     $query->asArray();
     foreach ($query->each() as $row) {
         $isAccountMatched = $personId != null && $personId == $row['AccountantID'];
         $EventTime = $row['EventTime'];
         $EventDay = $formatter->asDate($EventTime, 'php:D d-m-Y');
         //Отменено ?
         $cancelled = $row['CancelAccountID'] != 0;
         //if($cancelled && !$allowCancelled) continue;
         $type = $row['action']['Type'];
         $action = $row['action'];
         $cash = $row['CashSum'];
         if (!isset($data->actions[$action['ID']])) {
             $data->actions[$action['ID']] = $action;
             $data->actions[$action['ID']]['count'] = 0;
             $data->actions[$action['ID']]['cash'] = 0;
         }
         $data->actions[$action['ID']]['count']++;
         $data->actions[$action['ID']]['cash'] += $cash;
         if ($type == FinanceClassRecord::TYPE_IN) {
             if ($personId != null) {
                 if ($isAccountMatched) {
                     $_income += $cash;
                     if ($row['ClassID'] != 14 && $row['ClassID'] != 2) {
                         if ($cash > 0) {
                             $data->orderCount++;
                             $ordersCash[] = $cash;
                         }
                     }
                 }
             } else {
                 $_income += $cash;
                 if ($row['ClassID'] != 14 && $row['ClassID'] != 2) {
                     if ($cash > 0) {
                         $data->orderCount++;
                         $ordersCash[] = $cash;
                     }
                 }
             }
             //Регистрация карты
         } else {
             if ($type == FinanceClassRecord::TYPE_OUT) {
                 if ($personId != null) {
                     if ($isAccountMatched) {
                         $_expense += $cash;
                     }
                 } else {
                     $_expense += $cash;
                 }
             } else {
             }
         }
         switch ($row['ClassID']) {
             //Использование объектов
             case 1:
                 //total money
                 $data->totalSpend += $cash;
                 $data->totalSpendWithCard += $cash;
                 if (!isset($objects[$row['ObjectID']])) {
                     throw new Exception('объект не найден: №' . $row['ObjectID']);
                 }
                 $object = $objects[$row['ObjectID']];
                 //Total objects stat
                 //                    if(!isset($objectsStat[$object['ID']]['cash'])) {
                 //                        $objectsStat[$object['ID']]['cash'] = 0;
                 //                    }
                 $objectsStat[$object['ID']]['cash'] += $cash;
                 //Objects stat by days
                 if (!isset($objectsByDay[$EventDay])) {
                     $objectsByDay[$EventDay] = $objects;
                 }
                 //                    if(!isset($objectsByDay[$EventDay][$object['ID']])) {
                 //                        $objectsByDay[$EventDay][$object['ID']] = $object;
                 //                        $objectsByDay[$EventDay][$object['ID']]['cash'] = 0;
                 //                        $objectsByDay[$EventDay][$object['ID']]['EventTime'] = $EventTime;
                 //                    }
                 $objectsByDay[$EventDay][$object['ID']]['cash'] += $cash;
                 break;
                 //Покупка услуги|акции
             //Покупка услуги|акции
             case 22:
                 if ($personId != null) {
                     if ($isAccountMatched) {
                         $data->soldService[$row['ID']] = $row;
                         $data->soldService[$row['ID']]['cash'] = $cash;
                         $data->totalSpend += $cash;
                     }
                 } else {
                     $data->soldService[$row['ID']] = $row;
                     $data->soldService[$row['ID']]['cash'] = $cash;
                     $data->totalSpend += $cash;
                 }
                 break;
                 //Регистрация карты
             //Регистрация карты
             case 2:
                 if ($personId != null) {
                     if ($isAccountMatched) {
                         $data->totalIncomeFromCardRegistration += $cash;
                     }
                 } else {
                     $data->totalIncomeFromCardRegistration += $cash;
                 }
                 break;
                 //Залог
             //Залог
             case 14:
                 //идет в доход от регистрации
                 if ($personId != null) {
                     if ($isAccountMatched) {
                         $data->totalIncomeFromCardRegistration += $cash;
                     }
                 } else {
                     $data->totalIncomeFromCardRegistration += $cash;
                 }
                 break;
                 //Пополнение простое
             //Пополнение простое
             case 6:
                 if ($personId != null) {
                     if ($isAccountMatched) {
                         $data->chargeCount++;
                         $data->totalCharge += $cash;
                         $charges[] = $cash;
                         $data->currentCardDebt += $cash;
                     }
                 } else {
                     $data->chargeCount++;
                     $data->totalCharge += $cash;
                     $charges[] = $cash;
                     $data->currentCardDebt += $cash;
                 }
                 break;
                 //Пополнение при регистрации
             //Пополнение при регистрации
             case 12:
                 if ($personId != null) {
                     if ($isAccountMatched) {
                         $data->cardRegistrationCount++;
                         //в доход от регистрации
                         $data->totalIncomeFromCardRegistration += $cash;
                         //либо в пополнения
                         //$data->totalCharge += $cash;
                         $chargesWithRegistration[] = $cash;
                         $data->currentCardDebt += $cash;
                     }
                 } else {
                     $data->cardRegistrationCount++;
                     //в доход от регистрации
                     $data->totalIncomeFromCardRegistration += $cash;
                     //либо в пополнения
                     //$data->totalCharge += $cash;
                     $chargesWithRegistration[] = $cash;
                     $data->currentCardDebt += $cash;
                 }
                 break;
                 //Пополнение при регистрации подарочной карты
             //Пополнение при регистрации подарочной карты
             case 15:
                 if ($personId != null) {
                     if ($isAccountMatched) {
                         $data->cardGiftRegistrationCount++;
                         $data->totalIncomeFromGiftCardRegistration += $cash;
                         $chargesWithRegistration[] = $cash;
                     }
                 } else {
                     $data->cardGiftRegistrationCount++;
                     $data->totalIncomeFromGiftCardRegistration += $cash;
                     $chargesWithRegistration[] = $cash;
                 }
                 break;
                 //Снятие денег с карты
             //Снятие денег с карты
             case 7:
                 if ($personId != null) {
                     if ($isAccountMatched) {
                         $data->totalMoneyBackFromCard += $cash;
                     }
                 } else {
                     $data->totalMoneyBackFromCard += $cash;
                 }
                 break;
                 //Билеты на карту
             //Билеты на карту
             case 3:
                 $data->currentTicketsEmitted += $row['Coins'];
                 break;
                 //Обмен билетов на товар
             //Обмен билетов на товар
             case 4:
                 $data->currentTicketsSpend += $row['Coins'];
                 break;
                 //Возврат залога
             //Возврат залога
             case 13:
                 //возвращается на счет поэтому не имеет фин значения (type = 0)
                 break;
                 //Акционное попоплнение
             //Акционное попоплнение
             case 18:
                 if ($personId != null) {
                     if ($isAccountMatched) {
                         $data->currentBonusesEmitted += $cash;
                     }
                 } else {
                     $data->currentBonusesEmitted += $cash;
                 }
                 break;
                 //плата за замену карты
             //плата за замену карты
             case 19:
                 break;
                 //оплата бонусами
             //оплата бонусами
             case 20:
                 $data->currentBonusesSpend += $cash;
                 break;
                 //начисление бонусов
             //начисление бонусов
             case 21:
                 $data->currentBonusesEmitted += $cash;
                 break;
         }
     }
     $data->objects = $objectsStat;
     $data->objectsByDays = $objectsByDay;
     $data->sumIncome = $_income;
     $data->sumExpense = $_expense;
     $data->income = $data->sumIncome - $data->sumExpense;
     if (count($charges) > 0) {
         $data->averageChargeAmount = array_sum($charges) / count($charges);
     }
     if (count($chargesWithRegistration) > 0) {
         $data->averageRegistrationChargeAmount = array_sum($chargesWithRegistration) / count($chargesWithRegistration);
     }
     if (count($ordersCash) > 0) {
         $ordersCash = array_filter($ordersCash);
         $data->orderCount = count($ordersCash);
         $data->orderAvg = array_sum($ordersCash) / count($ordersCash);
         $data->orderMax = max($ordersCash);
         $data->orderMin = min($ordersCash);
     }
     /*
             $data->currentCardDebtPlusBonus = AccountRecord::find()
                 ->select('Money')
                 ->leftJoin('tpersons', 'taccount.PersonID=tpersons.ID')
                 ->where(['tpersons.ServiceCard'=>0])
                 ->andWhere(['>=', 'taccount.RegisterDate', $from])
                 ->andWhere(['<=', 'taccount.RegisterDate', $to])
                 ->andWhere(['taccount.Deleted'=>0])
                 ->sum('Money');
     */
     //Текущий дебет на карточках за выбранный период
     //        $data->currentCardDebt = FinanceRecord::find()
     //            ->andWhere(['CancelAccountID'=>0])
     //            ->andWhere(['>=', 'EventTime', $from])
     //            ->andWhere(['<=', 'EventTime', $to])
     //            ->andWhere(['in', 'ClassID', [6, 12]])
     //            ->sum('CashSum');
     //Дебет без бонусов
     $data->currentCardDebt = $data->currentCardDebt - $data->totalSpend;
     $data->currentCardDebtPlusBonus = $data->currentCardDebt + $data->currentBonusesEmitted;
     //Всего начислено бонусов
     //по журналу
     $data->totalBonusesEmitted = FinanceRecord::find()->leftJoin('tpersons', 'tfinance.ContractorID=tpersons.ID')->andWhere(['<=', 'tpersons.RegisterDate', $to])->andWhere(['in', 'tfinance.ClassID', [18, 21]])->andWhere(['tfinance.CancelAccountID' => 0])->andWhere(['tpersons.Deleted' => 0, 'tpersons.ServiceCard' => 0])->sum('tfinance.CashSum');
     //фактический бонусный дебет на аккаунтах
     $data->totalCardBonusDebt = AccountRecord::find()->leftJoin(PersonsRecord::tableName() . ' person', 'person.ID=taccount.PersonID')->andWhere(['<=', 'taccount.RegisterDate', $to])->select('taccount.Bonuses')->andWhere(['person.ServiceCard' => 0])->andWhere(['taccount.Deleted' => 0])->andWhere(['person.Deleted' => 0])->sum('taccount.Bonuses');
     //Фактически денег на счетах
     $data->totalCardDebt = AccountRecord::find()->leftJoin(PersonsRecord::tableName() . ' person', 'person.ID=taccount.PersonID')->andWhere(['<=', 'taccount.RegisterDate', $to])->select('taccount.Money')->andWhere(['person.ServiceCard' => 0])->andWhere(['taccount.Deleted' => 0])->sum('taccount.Money');
     //Общий дебет на карточках с бонусами
     $data->totalCardDebtPlusBonus = $data->totalCardDebt + $data->totalCardBonusDebt;
     //Билетов на картах
     $data->totalTickets = AccountRecord::find()->andWhere(['<=', 'RegisterDate', $to])->andWhere(['Deleted' => 0])->sum('Tickets');
     //Количество зарег сервисных карт
     $data->countServiceCardWasCreated = PersonsRecord::find()->andWhere(['>=', 'RegisterDate', $from])->andWhere(['<', 'RegisterDate', $to])->andWhere(['Deleted' => 0])->andWhere(['ServiceCard' => 1])->count();
     $file = $this->_create($data, PersonsRecord::findOne($personId));
     Yii::$app->response->sendFile($file, 'Report.' . $from . '-' . $to . '.xlsx');
 }
 public function attributes()
 {
     // add related fields to searchable attributes
     return array_merge(parent::attributes(), ['account.Money', 'group.Name', 'card.HardID', 'account.LevelID']);
 }
 /**
  * Deletes an existing PersonsGroupRecord model.
  * If deletion is successful, the browser will be redirected to the 'index' page.
  * @param integer $id
  * @return mixed
  */
 public function actionDelete($id)
 {
     $defaultGroup = PersonsGroupRecord::getDefault();
     $model = $this->findModel($id);
     if ($model->getIsMandatory()) {
         Yii::$app->getSession()->setFlash('error', Yii::t('app', 'You can not delete mandatory groups!'));
     } else {
         if ($model->id == $defaultGroup->id) {
             Yii::$app->getSession()->setFlash('error', Yii::t('app', 'Default group can not be removed'));
         } else {
             $this->findModel($id)->forceDelete();
             PersonsRecord::updateAll(['GroupID' => $defaultGroup->id], ['GroupID' => $id]);
             Yii::$app->getSession()->setFlash('warning', Yii::t('app', 'All users of deleted group was moved to default group!'));
         }
     }
     return $this->redirect(['index']);
 }