OSDN Git Service

Исправлен список всех перемещений. Добавлен тест проверки возможности открытия этого...
[invent/invent.git] / controllers / ItemsController.php
index 3456546..9938bcf 100644 (file)
@@ -59,6 +59,10 @@ class ItemsController extends Controller
      */
     public static function addIfNeed($options)
     {
+        $result = [
+            'id' => FALSE,
+            'error' => Yii::t('items', 'Items: Key field missing "invent" :') . print_r($options, TRUE),
+        ];
         // Если указан инвентарный номер
         if (is_array($options) && isset($options[ 'invent' ]))
         {
@@ -72,42 +76,47 @@ class ItemsController extends Controller
 
             if (count($item) > 0) // Записи найдены, выводим первую совпавшую
             {
-                return $item[ 0 ]->id;
+                $result[ 'id' ] = $item[ 0 ]->id;
+                $result[ 'error' ] = '';
             }
-            // Внесённого оборудования не найдено. Добавим новую запись
-            if (isset($options[ 'model' ]))
+            else
             {
-                // Ð\95Ñ\81ли Ñ\83казан Ñ\82ип Ð¿Ñ\80едмеÑ\82а/обоÑ\80Ñ\83дованиÑ\8f
-                if (isset($options[ 'type' ]))
+                // Ð\92неÑ\81Ñ\91нного Ð¾Ð±Ð¾Ñ\80Ñ\83дованиÑ\8f Ð½Ðµ Ð½Ð°Ð¹Ð´ÐµÐ½Ð¾. Ð\94обавим Ð½Ð¾Ð²Ñ\83Ñ\8e Ð·Ð°Ð¿Ð¸Ñ\81Ñ\8c
+                if (isset($options[ 'model' ]))
                 {
-                    $type_id = TypesController::addIfNeed($options[ 'type' ]); // Найдём или добавим тип
-                    // Если тип не добавили
-                    if($type_id === FALSE)
+                    $model = ModelsController::addIfNeed($options);
+                    if ($model[ 'id' ] === FALSE)
                     {
-                        $type_id = NULL; // сделаем его пустым
+                        $result[ 'error' ] .= '<br />' . $model[ 'error' ];
+                    }
+                    else
+                    {
+                        // Создаём новую запись предмета/оборудования
+                        $item = new Items();
+                        $item->name        = isset($options[ 'netName' ]) ? $options[ 'netName' ] : NULL; // Сетевое имя
+
+                        $item->model_id    = $model[ 'id' ];                                              // идентификатор модели (Подготовлено для преобразования)
+                        $item->invent      = isset($options[ 'invent' ]) ? $options[ 'invent' ] : NULL;   // Инвентарный номер
+                        $item->comment     = isset($options[ 'comment' ]) ? $options[ 'comment' ] : NULL; // Коментарий
+                        $item->os          = isset($options[ 'os' ]) ? $options[ 'os' ] : NULL;           // Операционная система
+                        $item->mac         = isset($options[ 'mac' ]) ? $options[ 'mac' ] : NULL;         // MAC-адрес
+                        $item->serial      = isset($options[ 'serial' ]) ? $options[ 'serial' ] : NULL;   // Серийный номер
+                        $item->checked     = false;                                                       // Не инвентризирован (требует внимания после импорта)
+                        // Сохраняем запись
+                        if ($item->validate() && $item->save())
+                        {
+                            $result[ 'id' ] = $item->id; // Возвращаем идентификатор записанного оборудования
+                            $result[ 'error' ] = '';
+                        }
+                        else
+                        {
+                            $result[ 'error' ] .= Yii::t('items', 'Items: Failed to add entry: ') . print_r($item->errors, TRUE) . '<br />';
+                        }
                     }
-                }
-                // Создаём новую запись предмета/оборудования
-                $item = new Items();
-                $item->name        = isset($options[ 'netName' ]) ? $options[ 'netName' ] : NULL; // Сетевое имя
-                $item->model       = isset($options[ 'model' ]) ? $options[ 'model' ] : NULL;     // Наименование
-                $item->invent      = isset($options[ 'invent' ]) ? $options[ 'invent' ] : NULL;   // Инвентарный номер
-                $item->comment     = isset($options[ 'comment' ]) ? $options[ 'comment' ] : NULL; // Коментарий
-                $item->type_id     = isset($type_id) ? $type_id : NULL;                           // Идентификатор типа
-                $item->os          = isset($options[ 'os' ]) ? $options[ 'os' ] : NULL;           // Операционная система
-                $item->mac         = isset($options[ 'mac' ]) ? $options[ 'mac' ] : NULL;         // MAC-адрес
-                $item->serial      = isset($options[ 'serial' ]) ? $options[ 'serial' ] : NULL;   // Серийный номер
-                $item->product     = isset($options[ 'product' ]) ? $options[ 'product' ] : NULL; // Код оборудования
-                $item->modelnumber = isset($options[ 'modelnum' ]) ? $options[ 'modelnum' ] : NULL; // Номер модели
-                $item->checked     = false;                                                       // Не инвентризирован (требует внимания после импорта)
-                // Сохраняем запись
-                if ($item->validate() && $item->save())
-                {
-                    return $item->id; // Возвращаем идентификатор записанного оборудования
                 }
             }
         }
-        return FALSE;
+        return $result;
     }
 
     /**
@@ -208,7 +217,7 @@ class ItemsController extends Controller
                 //$message = '[0] = "' . $keys[0] . '", [1] = "' . $keys[1] . '"<br />';
                 foreach ($items as $row)
                 {
-                    $message .= $row->model . ' (' . $row->id . ')';
+                    $message .= $row->models->name . ' (' . $row->id . ')';
                 }
                 if ($message != '')
                     $message = Yii::t('items', 'Checked item(s): ') . $message;
@@ -241,7 +250,7 @@ class ItemsController extends Controller
         {
             $id = Yii::$app->request->queryParams['id'];
             $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
-            $dataProvider->query->select(Items::tableName() . '.id');
+            //$dataProvider->query->select(Items::tableName() . '.id');
             $pageSize = $dataProvider->pagination->pageSize;
             $dataProvider->pagination = FALSE;
             $rows = $dataProvider->getModels();
@@ -280,6 +289,7 @@ class ItemsController extends Controller
         
         // Проверка наличия ключевых полей
         if ((!isset($arrayRows[ 0 ][ 'model' ]))
+            || (!isset($arrayRows[ 0 ][ 'type' ]))
             || (!isset($arrayRows[ 0 ][ 'invent' ]))
             || (!isset($arrayRows[ 0 ][ 'location' ]))
             || (!isset($arrayRows[ 0 ][ 'region' ]))
@@ -288,7 +298,7 @@ class ItemsController extends Controller
         {
             // Сообщение об ошибке
             $arrayReturn[ 'countErrors' ] = count($arrayRows);
-            $arrayReturn[ 'errors' ] .= '<br />' . Yii::t('import', 'Skip all. Key column not found.: ' . print_r($arrayRows[0], TRUE));
+            $arrayReturn[ 'errors' ] .= '<br />' . Yii::t('import', 'Skip all. Key column(s) "model", "type", "invent", "location", "region", "date" not found: ') . print_r($arrayRows[0], TRUE);
         }
         else
         {
@@ -301,35 +311,29 @@ class ItemsController extends Controller
                 {
                     // Сообщим об ошибке
                     $arrayReturn[ 'countErrors' ]++;
-                    $arrayReturn[ 'errors' ] .= '<br />' . Yii::t('import', 'Location: {location} ({region})', $row) . ' :: ' . $location[ 'error' ];
+                    $arrayReturn[ 'errors' ] .= '<br />' . $location[ 'error' ];
                 }
                 else
                 {
                     // Попробуем найти или добавить предмет/оборудование
-                    $item_id = $this->addIfNeed($row);
-                    if (!isset($item_id))
-                    {
-                        $arrayReturn[ 'errors' ] .= '<br />Оборудование: ' . print_r($row, TRUE);
-                        continue;
-                    }
-                    if ($item_id === FALSE)
+                    $item = $this->addIfNeed($row);
+                    if ($item[ 'id' ] === FALSE)
                     {
-                        // Сообщим об ошибке
                         $arrayReturn[ 'countErrors' ]++;
-                        $arrayReturn[ 'errors' ] .= '<br />' . Yii::t('import', 'Item: {model}, Invent: {invent}, serial No:, comment: {comment}', $row);
+                        $arrayReturn[ 'errors' ] .= '<br />' . $item[ 'error' ];
                     }
                     else
                     {
                         // Проверка, что предмет/оборудование уже были в базе
-                        $item = Items::find()->where([ 'id' => $item_id ])->one();
+                        $item = Items::find()->where([ 'id' => $item[ 'id' ]])->one();
                         if ($item->checked === TRUE)
                         {
                             $arrayReturn[ 'countExists' ]++;
                         }
                         else
                         {
-                            $state = isset($row[ 'status' ]) ? StatusController::addIfNeed($row) : StatusController::addIfNeed([ 'name' => 'Склад' ]);
-                            if ( $state['id'] === FALSE )
+                            $state = isset($row[ 'status' ]) ? StatusController::addIfNeed($row) : StatusController::addIfNeed([ 'status' => 'Склад' ]);
+                            if ( $state[ 'id' ] === FALSE )
                             {
                                 // Сообщим об ошибке
                                 $arrayReturn[ 'countErrors' ]++;
@@ -339,11 +343,11 @@ class ItemsController extends Controller
                             {
                                 // Новый предмет/оборудование. Пробуем добавить первое перемещение
                                 $moving = new Moving();
-                                $moving->date = $row[ 'date' ];
-                                $moving->state_id = $state['id'];
-                                $moving->item_id = $item_id;
+                                $moving->date        = $row[ 'date' ];
+                                $moving->state_id    = $state[ 'id' ];
+                                $moving->item_id     = $item[ 'id' ];
                                 $moving->location_id = $location[ 'id' ];
-                                $moving->comment = Yii::t('import', 'Import: {comment}', $row);
+                                $moving->comment     = Yii::t('import', 'Import: {comment}', $row);
 
                                 if ($moving->validate() && $moving->save())
                                 {
@@ -353,10 +357,10 @@ class ItemsController extends Controller
                                 else
                                 {
                                     // Запись не удалась, пробуем удалить предмет/оборудование
-                                    Items::find()->where([ 'id' => $item_id, 'checked' => FALSE ])->one()->delete();
+                                    Items::find()->where([ 'id' => $item[ 'id' ], 'checked' => FALSE ])->one()->delete();
                                     // Сообщим об ошибке
                                     $arrayReturn[ 'countErrors' ]++;
-                                    $arrayReturn[ 'errors' ] .= '<br />' . Yii::t('import', 'Moving: {date} ('.$moving->errors['date'][0].'), Инвентарный номер:{invent} {model}, location: {location} ( {region} )' , $row);
+                                    $arrayReturn[ 'errors' ] .= '<br />' . Yii::t('import', 'Moving: {date} (') . $moving->errors['date'][0]. Yii::t('import', '), Inventory number:{invent}, model: {model}, location: {location} ( {region} )' , $row);
                                 }
                                 unset($moving);
                             }
@@ -422,13 +426,13 @@ class ItemsController extends Controller
                             if (count($columns) == 0)
                             {
                                 // Ищем строку с заголовком таблицы
-                                if ( stripos($row[0], $columnNames[ 'npp' ]) !== FALSE )
+                                if ( stripos($row[0], $columnsNames[ 'npp' ]) !== FALSE )
                                 {
                                     // Перебираем все колонки
                                     foreach ($row as $key => $item)
                                     {
                                         // Перебираем все названия заголовков колонок
-                                        foreach($columnNamses as $name => $text)
+                                        foreach($columnsNames as $name => $text)
                                         {
                                             // Если название совпало,
                                             if (stripos($item, $text) !== FALSE)
@@ -483,12 +487,12 @@ class ItemsController extends Controller
                                 $flag = FALSE;
                                 foreach ($cellIterator as $key => $item)
                                 {
-                                    if (($key == 'A') && (stripos($item->getValue(), $columnsNames[ 'npp' ]) !== FALSE)) $flag = TRUE;
+                                    if (($key == 'A') && (stripos($item->getCalculatedValue(), $columnsNames[ 'npp' ]) !== FALSE)) $flag = TRUE;
                                     if ($flag)
                                     {
                                         foreach ($columnsNames as $name => $text)
                                         {
-                                            if (stripos($item->getValue(), $text) !== FALSE)
+                                            if (stripos($item->getCalculatedValue(), $text) !== FALSE)
                                             {
                                                 $columns[ $name ] = $key;
                                             }
@@ -504,14 +508,14 @@ class ItemsController extends Controller
                                 {
                                     if ($key == $columns[ 'npp' ])
                                     {
-                                        $npp = str_replace(' ', '', $item->getValue());
+                                        $npp = str_replace(' ', '', $item->getCalculatedValue());
                                         if (ctype_digit($npp)) $flag = TRUE;
                                     }
                                     if ($flag)
                                     {
                                         foreach($columns as $keym => $index)
                                         {
-                                            if ($index == $key) $line[ $keym ] = $item->getValue();
+                                            if ($index == $key) $line[ $keym ] = $item->getCalculatedValue();
                                         }
                                     }
                                 }