Commit 01746976b19ae7299a16e58b73e31f0aed0126a8

Authored by Mihail
1 parent 9e481998

fix errors with writing to Importer files

backend/controllers/CheckPriceController.php
... ... @@ -61,7 +61,6 @@ class CheckPriceController extends BaseController
61 61  
62 62 public function actionIndex()
63 63 {
64   -
65 64 if(Yii::$app->request->isAjax){
66 65 CustomVarDamp::dumpAndDie(1);
67 66 }
... ... @@ -84,6 +83,7 @@ class CheckPriceController extends BaseController
84 83  
85 84 public function actionView ($id)
86 85 {
  86 + // @todo переписать запрос - нужно условие на равенство даты, а также вьюшка должна быть модальным окном вызываемой по аджаксу
87 87 $query = Details::find()->where(['IMPORT_ID' => $id])->orderBy(['timestamp' => SORT_DESC]);
88 88  
89 89 $provider = new ActiveDataProvider([
... ...
backend/controllers/ParserController.php
... ... @@ -92,13 +92,13 @@ class ParserController extends BaseController
92 92 CustomVarDamp::dump($e->getMessage());
93 93 }
94 94 // получим id только что записанной записи - его запишем в название файла
95   - $id = $files_model->find()
  95 + $model->record_id = $files_model->find()
96 96 ->where(['importer_id' => $files_model->importer_id])
97 97 ->orderBy(['id' => SORT_DESC])
98 98 ->one()
99 99 ->id;
100 100  
101   - $file_name = $id . '.' . $model->file->extension;
  101 + $file_name = $model->record_id . '.' . $model->file->extension;
102 102  
103 103 if ($model->mode) {
104 104 $model->file_path = Yii::getAlias('@auto_upload') . '/' . $file_name;
... ... @@ -188,10 +188,10 @@ class ParserController extends BaseController
188 188  
189 189  
190 190 // 1. запишем дату старта в таблицу файлов поставщика (ImportersFiles)
191   - $files_model = new ImporterFiles();
192   - // id поставщика и id загруженного файла получим из конфигурации
193   - $files_model->load(['ImporterFiles' => $configuration->toArray()]);
  191 + // id загруженного файла получим из конфигурации
  192 + $files_model = ImporterFiles::findOne( $configuration->record_id );
194 193  
  194 + //$files_model->load(['ImporterFiles' => $configuration->toArray()]);
195 195 $update_date = date('Y-m-d H:i:s');
196 196 $files_model->time_start = $update_date;
197 197 // запишем дату начала загрузки
... ... @@ -206,7 +206,7 @@ class ParserController extends BaseController
206 206 $details_model->load(['Details' => $data[0]]);
207 207 if ($details_model->validate()) {
208 208 // дополним данные значением импортера и даты обновления цены
209   - $data = \Yii::$app->multiparser->addColumns($data, ['IMPORT_ID' => $configuration['importer_id'], 'timestamp' => $update_date]);
  209 + $data = \Yii::$app->multiparser->addColumns($data, ['IMPORT_ID' => $configuration->importer_id, 'timestamp' => $update_date]);
210 210  
211 211 try {
212 212 //@todo add transaction
... ... @@ -234,7 +234,6 @@ class ParserController extends BaseController
234 234 Yii::$app->getCache()->delete('parser_configuration');
235 235  
236 236 unlink($configuration['file_path']);
237   -
238 237 return $this->render('index', ['model' => $configuration]);
239 238  
240 239 } catch (ErrorException $e) {
... ...
backend/models/ImporterFiles.php
... ... @@ -35,6 +35,10 @@ class ImporterFiles extends \yii\db\ActiveRecord
35 35 ];
36 36 }
37 37  
  38 + public function getImporter ()
  39 + {
  40 + return $this->hasOne(Importer::className(), ['id' => 'importer_id'])->name;
  41 + }
38 42 /**
39 43 * @inheritdoc
40 44 */
... ...
backend/models/UploadFileParsingForm.php
... ... @@ -26,6 +26,7 @@ class UploadFileParsingForm extends Model
26 26 public $file_path;
27 27 public $success;
28 28 public $mode; //0 - режим ручной загрузки, 1 - режим автозагрузки
  29 + public $record_id; // id таблицы в которую записывается информация о файле
29 30  
30 31 /**
31 32 * @return array the validation rules.
... ... @@ -52,7 +53,7 @@ class UploadFileParsingForm extends Model
52 53 ['importer_id', 'integer','max' => 999999, 'min' => 0 ],
53 54 [['action','delete_prefix', 'delete_price', 'success'], 'boolean', 'except' => 'auto' ], // только для ручной загрузки
54 55 ['delimiter', 'string', 'max' => 1],
55   - ['mode', 'safe'],
  56 + [['mode','record_id'], 'safe'],
56 57 ['delimiter', 'default', 'value' => ';'],
57 58 [ 'success', 'default', 'value' => false]
58 59  
... ... @@ -87,10 +88,8 @@ class UploadFileParsingForm extends Model
87 88 'delete_price',
88 89 'delete_prefix',
89 90 'file_path',
90   - // id записи таблицы ImportersFiles, получаем из имени загруженного файла
91   - 'id' => function () {
92   - return $this->file->getBaseName();
93   - },
  91 + // id записи таблицы ImportersFiles,
  92 + // 'id' => 'record_id',
94 93 ];
95 94 }
96 95  
... ...
console/migrations/m150922_094313_change_key_ImportFiles.php
... ... @@ -5,6 +5,7 @@ use yii\db\Migration;
5 5  
6 6 class m150922_094313_change_key_ImportFiles extends Migration
7 7 {
  8 + //@todo вероятно что эта миграция ненужна - посмотреть ближе к концу проекта на ключи которые используются - остальные удалить.
8 9 public function up()
9 10 {
10 11 $this->dropIndex('importer_id', '{{%importer_files}}');
... ...
console/migrations/m150925_111922_add_foreign_key_ImportFiles.php 0 → 100644
  1 +<?php
  2 +
  3 +use yii\db\Schema;
  4 +use yii\db\Migration;
  5 +
  6 +class m150925_111922_add_foreign_key_ImportFiles extends Migration
  7 +{
  8 + public function up()
  9 + {
  10 + $this->addForeignKey('importer_fk', '{{%importer_files}}', 'importer_id', '{{%importer}}', 'id');
  11 + }
  12 +
  13 + public function down()
  14 + {
  15 + $this->dropForeignKey('importer_fk', '{{%importer_files}}');
  16 + }
  17 +
  18 +}
... ...
vendor/yiisoft/multiparser/CsvParser.php
... ... @@ -125,9 +125,18 @@ class CsvParser implements ParserInterface
125 125 $return = [];
126 126  
127 127 $current_line = 0;
128   - //$this->keys = NULL;
  128 + // будем считать количество пустых строк подряд - при трех подряд - считаем что это конец файла и выходим
  129 + $empty_lines = 0;
  130 + while ( $empty_lines < 3 ) {
  131 + // прочтем строку из файла. Если там есть значения - то в ней массив, иначе - false
  132 + $row = $this->readRow();
129 133  
130   - while (($row = $this->readRow()) !== FALSE) {
  134 + if ($row === false) {
  135 + //счетчик пустых строк
  136 + $empty_lines++;
  137 + continue;
  138 + }
  139 + // строка не пустая, имеем прочитанный массив значений
131 140 $current_line++;
132 141 if ($this->hasHeaderRow) {
133 142 if ($this->keys === NULL) {
... ... @@ -148,7 +157,8 @@ class CsvParser implements ParserInterface
148 157 if (($this->last_line) && ($current_line > $this->last_line)) {
149 158 break;
150 159 }
151   -
  160 + // обнуляем счетчик, так как считаюся пустые строки ПОДРЯД
  161 + $empty_lines = 0;
152 162 }
153 163  
154 164 $this->closeHandler();
... ...