Пример #1
0
 public function search(array $params)
 {
     $query = Trip::find();
     $query->with('number', 'employee');
     $query->orderBy(['numberPossession.from' => SORT_DESC]);
     $dataProvider = new ActiveDataProvider(['query' => $query, 'sort' => false]);
     if (!($this->load($params) && $this->validate())) {
         return $dataProvider;
     }
     if (!empty($this->mobileNumber)) {
         $numberIds = array_map(function ($item) {
             return $item['_id'];
         }, Number::find()->select(['_id'])->asArray()->where(['like', 'number', $this->mobileNumber])->all());
         $query->andWhere(['in', 'numberId', $numberIds]);
     }
     if (!empty($this->employeeName)) {
         $employeeIds = array_map(function ($item) {
             return (int) $item['id'];
         }, Employee::findByName($this->employeeName, true)->select('id')->asArray()->all());
         $query->andWhere(['in', 'employeeId', $employeeIds]);
     }
     if ($this->complete === self::INCOMPLETE) {
         $query->andWhere(['complete' => false]);
     }
     if ($this->rentNumberFrom !== $this->rentNumberTo) {
         $query->andWhere(['numberPossession.from' => ['$gt' => new MongoDate(strtotime($this->rentNumberFrom)), '$lte' => new MongoDate(strtotime($this->rentNumberTo))]]);
     }
     $query->andFilterWhere(['like', 'destination', $this->destination]);
     return $dataProvider;
 }
 public function testValidateAttribute()
 {
     $this->tester->haveInCollection(Number::collectionName(), ['number' => '9101234567']);
     $this->specify("Test validate", function ($number, $expected) {
         $this->model['number'] = $number;
         $this->model->validate(['number']);
         $this->tester->assertEquals($expected, $this->model->hasErrors());
     }, ['examples' => [['9101234567', false], ['1111111111', true], ['9121111111', true]]]);
 }
Пример #3
0
 public function actionNumberList($q = null)
 {
     $query = Number::find()->select(['number'])->where(['like', 'number', $q])->asArray();
     $query->andWhere(['options' => Number::OPTION_TRIP]);
     $out = [];
     foreach ($query->all() as $item) {
         $out[] = ['value' => $item['number']];
     }
     echo Json::encode($out);
 }
Пример #4
0
 /**
  * @param \yii\base\Model $model
  * @param string $attribute
  */
 public function validateAttribute($model, $attribute)
 {
     $regexpValidator = new RegularExpressionValidator(['pattern' => '/^9[0-9]{9}$/']);
     if (!$regexpValidator->validate($model->{$attribute})) {
         $this->addError($model, $attribute, '{attribute} имеет неверный формат');
         return;
     }
     $existValidator = new ExistValidator(['targetClass' => Number::className(), 'targetAttribute' => 'number']);
     if (!$existValidator->validate($model->{$attribute})) {
         $this->addError($model, $attribute, "{attribute} не существует");
     }
 }
Пример #5
0
 /**
  * @return array
  */
 public function rules()
 {
     return [[['number', 'operatorId'], 'required'], ['number', 'match', 'pattern' => '/^9[0-9]{9}$/'], ['number', 'unique'], ['ownerId', 'filter', 'filter' => function ($value) {
         return empty($value) ? null : (int) $value;
     }], ['ownerId', 'exist', 'targetClass' => Employee::className(), 'targetAttribute' => 'id'], ['limit', 'integer', 'min' => 0], ['limit', function ($attribute) {
         if ($this->accounting && empty($this->{$attribute})) {
             $this->addError($attribute, "При выбранной опции «Учитывать перерасход» лимит должен быть указан");
         }
     }, 'skipOnEmpty' => false], ['operatorId', MongoIdValidator::className(), 'forceFormat' => 'object'], ['operatorId', 'exist', 'targetClass' => Operator::className(), 'targetAttribute' => '_id'], ['destination', 'in', 'range' => [self::DESTINATION_MODEM, self::DESTINATION_PHONE]], ['options', function ($attribute) {
         $range = array_keys(Number::optionItems());
         foreach ($this->{$attribute} as $item) {
             if (!in_array($item, $range)) {
                 $this->addError('options', "Опция «{$item}» не существует.");
             }
         }
     }], ['comment', 'safe']];
 }
Пример #6
0
 public function actionUpdate()
 {
     foreach (Number::find()->all() as $number) {
         $history = [];
         foreach ($number->history as $item) {
             /** @var Employee $employee */
             $employee = Employee::findOne(['id' => $item['ownerId']]);
             if (!is_null($employee)) {
                 $newItem = ['ownerName' => $employee->fullName, 'ownerPost' => $employee->post];
                 if (isset($item['rentDate'])) {
                     $newItem['rentDate'] = $item['rentDate'];
                 }
                 if (isset($item['returnDate'])) {
                     $newItem['returnDate'] = $item['returnDate'];
                 }
                 $history[] = $newItem;
             }
             $number->history = $history;
             $number->save(false);
         }
     }
 }
Пример #7
0
 public function actionOwnerList($q)
 {
     Yii::$app->response->format = Response::FORMAT_JSON;
     return Number::ownerList($q);
 }
Пример #8
0
 public function getOutsideOperator()
 {
     return array_filter($this->outSideOperator, function ($item) {
         $number = Number::findOne($item['id']);
         return $number !== null && $number['operatorId'] == $this->operatorId ? true : false;
     });
 }
Пример #9
0
 /**
  * @param $queryParam
  * @return array
  */
 public static function itemsList($queryParam)
 {
     if (is_numeric($queryParam)) {
         $query = new Query();
         $query->select(['_id' => false, 'number' => 'text'])->from(Number::collectionName())->where(['like', 'number', $queryParam]);
     } else {
         $query = new \yii\db\Query();
         $query->select(["CONCAT_WS(' ',last_name, first_name, middle_name) AS number"])->from(Employee::tableName())->where(['like', 'last_name', $queryParam]);
     }
     $items['results'] = array_map(function ($item) {
         $item['id'] = $item['number'];
         return $item;
     }, $query->limit(10)->all());
     return $items;
 }
Пример #10
0
use app\tests\codeception\_pages\mobile\number\UpdatePage;
use app\modules\mobile\models\Number;
use app\modules\directory\models\Employee;
/**
 * @var $model app\modules\mobile\models\Number
 */
$I = new FunctionalTester($scenario);
$I->wantTo('ensure that update Number model works');
$page = UpdatePage::openBy($I);
$model = $I->grabRecord(Number::className(), ['_id' => 'number1']);
$I->seeInTitle('Номер ' . $model['number']);
$I->dontSeeElement($page->fieldSelector('number'));
$I->SeeElement("#documents-panel-body");
$I->SeeElement("#history-panel-body");
$I->seeInField($page->fieldSelector('ownerName'), $model->owner['fullName']);
$I->seeInField($page->fieldSelector('ownerPost'), $model->owner['post']);
$I->seeInField($page->fieldSelector('operatorId'), $model['operatorId']);
$I->seeInField($page->fieldSelector('destination'), $model['destination']);
$I->seeInField($page->fieldSelector('limit'), $model['limit']);
foreach (array_keys(Number::optionItems()) as $option) {
    in_array($option, $model->options) ? $I->seeCheckboxIsChecked($page->fieldSelector($option)) : $I->dontSeeCheckboxIsChecked($page->fieldSelector($option));
}
$I->seeInField($page->fieldSelector('comment'), $model['comment']);
$owner = $I->grabRecord(Employee::className(), ['_id' => 'employee2']);
$page->submit(['number' => '1234567890', 'ownerName' => $owner['fullName'], 'ownerPost' => $owner['post'], 'operatorId' => 'operator2', 'destination' => Number::DESTINATION_MODEM, 'limit' => '2000', 'options' => [Number::OPTION_TRIP], 'comment' => 'This is update comment']);
$I->see("Данные успешно обновлены", '.alert-success');
$history = $model['history'];
$history[count($history) - 1]['returnDate'] = time();
$history[] = ['ownerId' => 'employee2', 'rentDate' => time()];
$I->seeRecord(Number::className(), ['_id' => 'number1', 'number' => $model['number'], 'ownerId' => 'employee2', 'operatorId' => 'operator2', 'destination' => Number::DESTINATION_MODEM, 'limit' => 2000, 'options' => [Number::OPTION_TRIP], 'history' => $history, 'comment' => 'This is update comment']);
Пример #11
0
 * User: bill
 * Date: 26.01.15
 * Time: 11:31
 */
use app\tests\codeception\_pages\mobile\number\CreatePage;
use app\modules\mobile\models\Number;
use app\modules\mobile\models\Document;
use app\modules\directory\models\Employee;
$I = new FunctionalTester($scenario);
$I->wantTo("ensure that creation Number model works");
$owner = $I->grabRecord(Employee::className(), ['id' => 1]);
$newDocument = 'file1.jpg';
$number = '9876543210';
$I->amGoingTo("prepare database.");
Document::deleteAll(['filename' => $newDocument]);
Number::deleteAll(['number' => $number]);
$page = CreatePage::openBy($I);
$I->dontSeeElement("input[type=file]");
$I->dontSeeElement("#documents-panel-body");
$I->dontSeeElement("#history-panel-body");
$page->submit(['number' => $number, 'ownerName' => $owner->fullName, 'ownerPost' => $owner->post, 'operatorId' => 'operator2', 'destination' => Number::DESTINATION_MODEM, 'limit' => "1000", 'options' => [Number::OPTION_ACCOUNTING, Number::OPTION_DIRECTORY], 'comment' => 'This is comment of testing number.']);
$I->SeeRecord(Number::className(), ['number' => $number, 'ownerId' => 1, 'operatorId' => 'operator2', 'destination' => Number::DESTINATION_MODEM, 'limit' => 1000, 'options' => [Number::OPTION_ACCOUNTING, Number::OPTION_DIRECTORY], 'history' => [['ownerId' => 'employee1', 'rentDate' => time()]], 'comment' => 'This is comment of testing number.']);
$I->see("Номер успешно создан", '.alert-success');
$I->seeInField($page->fieldSelector('ownerName'), $owner->fullName);
$I->seeInField($page->fieldSelector('ownerPost'), $owner->posts[1]);
$I->seeOptionIsSelected($page->fieldSelector('operatorId'), "Оператор 2");
$I->seeOptionIsSelected($page->fieldSelector('destination'), Number::DESTINATION_MODEM);
$I->seeCheckboxIsChecked($page->fieldSelector(Number::OPTION_ACCOUNTING));
$I->seeCheckboxIsChecked($page->fieldSelector(Number::OPTION_DIRECTORY));
$I->dontSeeCheckboxIsChecked($page->fieldSelector(Number::OPTION_TRIP));
$I->seeInField($page->fieldSelector('comment'), 'This is comment of testing number.');
Пример #12
0
 public function testBeforeSave()
 {
     $this->specify("ownerId must be set before save number", function ($ownerFixture) {
         /** @var $owner Employee */
         $owner = $this->employees($ownerFixture);
         $model = new Number(['scenario' => 'create']);
         $model->number = '1234567890';
         $model->ownerName = $owner->fullName;
         $model->ownerPost = $owner->post;
         $model->operatorId = $this->operators('operator1')->getPrimaryKey();
         $model->save();
         $this->tester->seeInCollection($model::collectionName(), ['number' => '1234567890', 'ownerId' => $owner->getPrimaryKey()]);
         Number::deleteAll(['number' => '1234567890']);
     }, ['examples' => [['employee1'], ['employee4']]]);
     $this->specify("ownerId must be null if ownerName is empty string", function () {
         $model = $this->numbers('number1');
         /** @var $model Number */
         $model->setScenario('update');
         $model->ownerName = "";
         $model->save();
         $this->tester->seeInCollection($model::collectionName(), ['number' => $model['number'], 'ownerId' => null]);
     });
 }
Пример #13
0
 public function actionTrip()
 {
     $this->stdout("Загружаю командировки\n", Console::FG_BLUE, Console::BOLD);
     $query = (new Query())->from($this->tripTableName);
     $this->stdout("Источник: таблица '{$this->tripTableName}' " . $query->count() . " записей.\nЦелевая коллекция: '" . Trip::collectionName() . "'\n");
     $this->cleanCollection(Trip::collectionName());
     $successCounter = 0;
     foreach ($query->all() as $item) {
         $trip = new Trip();
         $number = (new Query())->select(['number'])->from($this->numberTableName)->where(['id' => $item['mobile_id']])->one();
         $trip['numberId'] = Number::findOne(['number' => $number['number']])->getPrimaryKey();
         $trip['employeeId'] = (int) $item['employee_id'];
         $trip['duration'] = ['from' => new MongoDate(strtotime("+1 day", (int) $item['rent_date'])), 'to' => new MongoDate((int) $item['return_date'])];
         $trip['numberPossession'] = ['from' => new MongoDate((int) $item['rent_date']), 'to' => new MongoDate(strtotime($item['actual_return_date']))];
         if ($trip['numberPossession']['to'] !== null) {
             $trip['complete'] = true;
         }
         $trip['destination'] = $item['destination'];
         if ($trip->save(false)) {
             $successCounter++;
         }
     }
     $this->stdout("Успешно загружено {$successCounter} записей\n", Console::BOLD, Console::FG_GREEN);
     $this->stdout("\n");
     return Controller::EXIT_CODE_NORMAL;
 }
Пример #14
0
 public function init()
 {
     parent::init();
     $this->nowInDb = Number::find()->where(['number' => $this->number])->count() ? true : false;
 }
Пример #15
0
 public function actionAll()
 {
     $numbers = Number::find()->with('owner')->orderBy('number')->all();
     return $this->render('all', ['numbers' => $numbers]);
 }
Пример #16
0
$I = new FunctionalTester($scenario);
$I->wantTo('test validation of Number model');
CreatePage::openBy($I);
$I->seeInTitle('Новый номер');
$I->amGoingTo("send empty form");
CreatePage::openBy($I)->submit();
$I->see('Необходимо заполнить «Номер».');
$I->amGoingTo("introduce too short number");
CreatePage::openBy($I)->submit(['number' => '1234']);
$I->see('Значение «Номер» должно содержать 10 символов.');
$I->amGoingTo("introduce number and limit of letters and numbers");
CreatePage::openBy($I)->submit(['number' => '123abc', 'limit' => '123abc']);
$I->see('Значение «Номер» должно быть целым числом.');
$I->see('Значение «Лимит» должно быть целым числом.');
$I->amGoingTo("introduce negative value of number and limit");
CreatePage::openBy($I)->submit(['number' => '-123', 'limit' => '-456']);
$I->see('Значение «Номер» должно быть не меньше 0.');
$I->see('Значение «Лимит» должно быть не меньше 0.');
$I->amGoingTo("introduce non unique value of number");
$I->haveRecord(Number::className(), ['number' => '9101234567']);
CreatePage::openBy($I)->submit(['number' => '9101234567']);
$I->see('Номер «9101234567» уже занят.');
$I->amGoingTo("check accounting option and empty limit");
CreatePage::openBy($I)->submit(['number' => '0123456789', 'options' => [Number::OPTION_ACCOUNTING]]);
$I->see("При выбранной опции «Учитывать перерасход» лимит должен быть указан");
$I->amGoingTo("introduce non existent owner name");
CreatePage::openBy($I)->submit(['number' => '0123456789', 'ownerName' => 'Non Existent Employee']);
$I->see("Сотрудник «Non Existent Employee» не найден.");
$I->amGoingTo("introduce non existent owner post");
CreatePage::openBy($I)->submit(['number' => '0123456789', 'ownerName' => 'Иванов Иван Иванович', 'ownerPost' => 'Non Existent Post']);
$I->see("Сотрудник «Иванов Иван Иванович» c должностью «Non Existent Post» не найден.");
Пример #17
0
 public function export()
 {
     $dataProvider = new ActiveDataProvider(['pagination' => false]);
     $dataProvider->query = Number::find()->with('owner')->where(['destination' => self::DESTINATION_PHONE]);
     return $dataProvider;
 }
Пример #18
0
 public function rules()
 {
     return array_merge(parent::rules(), [[['ownerId', 'contentType'], 'required'], ['ownerId', 'exist', 'targetClass' => Number::className(), 'targetAttribute' => '_id'], [['file'], 'file']]);
 }
Пример #19
0
 public function beforeSave($insert)
 {
     if (parent::beforeSave($insert)) {
         switch ($this->getScenario()) {
             case 'edit':
                 $this->numberId = Number::findOne(['number' => $this->mobileNumber])->getPrimaryKey();
                 $this->employeeId = Employee::findByName($this->employeeName)->andWhere(['post' => $this->employeePost])->one()->getPrimaryKey();
                 $this->duration = ['from' => new MongoDate(strtotime($this->beginDate)), 'to' => new MongoDate(strtotime($this->endDate))];
                 $this->numberPossession = ['from' => new MongoDate(strtotime($this->rentNumberDate))];
                 break;
             case 'complete':
                 break;
         }
         return true;
     } else {
         return false;
     }
 }