diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000..abe251a --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1 @@ +/temp \ No newline at end of file diff --git a/backend/components/parsers/CustomConverter.php b/backend/components/parsers/CustomConverter.php index 3612457..599a796 100644 --- a/backend/components/parsers/CustomConverter.php +++ b/backend/components/parsers/CustomConverter.php @@ -9,7 +9,7 @@ class CustomConverter extends Converter { * @param $key_array - ключи для вложенного массива * @return array - таблица с проименованными колонками */ - public static function convertToAssocArray ($value_arr, $key_array, $key_prefix = '') + public static function convertToAssocArray ( array $value_arr, array $key_array, $key_prefix = '') { // очистка служебного префикса в массиве заголовков if ($key_prefix) { @@ -44,7 +44,12 @@ class CustomConverter extends Converter { return $result; } - public function addColumns ($value_arr, $add_array) + /** + * @param $value_arr - двумерный массив к которому нужно добавить колонки + * @param $add_array - массив с колонками (ключи) и занчениями колонок + * @return mixed + */ + public function addColumns ( array $value_arr , array $add_array ) { $i = 0; while ($i < count($value_arr)) { diff --git a/backend/components/parsers/CustomCsvParser.php b/backend/components/parsers/CustomCsvParser.php index 1db0a46..dd28725 100644 --- a/backend/components/parsers/CustomCsvParser.php +++ b/backend/components/parsers/CustomCsvParser.php @@ -11,7 +11,7 @@ namespace backend\components\parsers; class CustomCsvParser extends \yii\multiparser\CsvParser { - public $last_line = 30; + public $last_line = 10; //public $hasHeaderRow = true; // public $keys = ['first','second', 'third', 'forth', 'fifth']; public function setupConverter() diff --git a/backend/controllers/ParserController.php b/backend/controllers/ParserController.php index 965b7c2..631c16e 100644 --- a/backend/controllers/ParserController.php +++ b/backend/controllers/ParserController.php @@ -2,6 +2,7 @@ namespace backend\controllers; use Yii; +use yii\data\ActiveDataProvider; use yii\filters\AccessControl; use backend\components\base\BaseController; use yii\filters\VerbFilter; @@ -14,6 +15,7 @@ use backend\models\Details; use backend\models\ImporterFiles; use backend\models\Importer; use yii\base\ErrorException; +use yii\db\Query; use common\components\CustomVarDamp; @@ -34,7 +36,7 @@ class ParserController extends BaseController 'class' => AccessControl::className(), 'rules' => [ [ - 'actions' => ['index', 'results', 'write'], + 'actions' => ['index', 'results', 'write','check_price'], 'allow' => true, 'roles' => ['@'], ], @@ -77,11 +79,11 @@ class ParserController extends BaseController $model->file = UploadedFile::getInstance($model, 'file'); // первый проход - валидируем, сохраняем файл, ложим в кеш отпарсенные данные и параметры модели (потом при записи в базу данных они пригодятся) if ($model->validate()) { - $filePath = Yii::getAlias('@webroot') . '/uploads/' . $model->file->baseName . '.' . $model->file->extension; + $model->file_path = Yii::getAlias('@webroot') . '/uploads/' . $model->file->baseName . '.' . $model->file->extension; - $model->file->saveAs($filePath); + $model->file->saveAs($model->file_path); //запускаем парсинг - $data = $model->readFile($filePath); + $data = $model->readFile(); // сохраняем в кеш отпарсенные даные Yii::$app->getCache()->set('parser_data', json_encode($data)); // сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных @@ -188,13 +190,14 @@ class ParserController extends BaseController if (!$imp_model->save()) { CustomVarDamp::dumpAndDie( $imp_model->getErrors() ); } - + $configuration['success'] = true; // все прошло успешно - очищаем кеш Yii::$app->getCache()->delete('parser_data'); Yii::$app->getCache()->delete('parser_configuration'); // @todo - Delete the file - CustomVarDamp::dumpAndDie('!!!'); + // все успешно - возвращаемся в начало + return $this->render('index', ['model' => $configuration]); } catch (ErrorException $e) { CustomVarDamp::dump($e->getMessage()); } @@ -215,4 +218,18 @@ class ParserController extends BaseController } + public function actionCheck_price () + { + $query = (new Query())->select('*')->from('{{%importer_files}}')->where(['not', ['time_end' => null]])->orderBy(['upload_time' => SORT_DESC]); + + $provider = new ActiveDataProvider([ + 'query' => $query, + 'pagination' => [ + 'pageSize' => 10, + ], + ]); + return $this->render('checkPrice', + [ + 'dataProvider' => $provider]); + } } diff --git a/backend/models/Importer.php b/backend/models/Importer.php index 65c993d..8a51373 100644 --- a/backend/models/Importer.php +++ b/backend/models/Importer.php @@ -47,8 +47,8 @@ class Importer extends BaseActiveRecord public function rules() { return [ - [['code', 'name', 'currency_id', 'delivery', 'info', 'price_date_update'], 'required'], - [['name_price', 'email', 'PARSER_FIELD_SIGN'], 'safe'], + [['code', 'name', 'currency_id', 'delivery', 'price_date_update'], 'required'], + [['name_price', 'email', 'PARSER_FIELD_SIGN', 'info'], 'safe'], [['currency_id', 'active', 'PARSER_IS_ACTIVE', 'PARSER_COLUMN_COUNT', 'PARSER_FIELD_BRAND', 'PARSER_FIELD_ARTICLE', 'PARSER_FIELD_ARTICLE_PREFIX', 'PARSER_FIELD_PRICE', 'PARSER_FIELD_DESCR', 'PARSER_FIELD_BOX', 'PARSER_FIELD_ADD_BOX', 'PARSER_FIELD_GROUP_RG'], 'integer'], [['info'], 'string'], [['PARSER_FIELD_MULTIPLIER'], 'number'], diff --git a/backend/models/UploadFileParsingForm.php b/backend/models/UploadFileParsingForm.php index b5de7d7..346a180 100644 --- a/backend/models/UploadFileParsingForm.php +++ b/backend/models/UploadFileParsingForm.php @@ -14,13 +14,17 @@ class UploadFileParsingForm extends Model /** * @var UploadedFile file attribute */ + // атрибуты формы public $file; public $importer_id; public $action; public $delimiter; public $delete_price; public $delete_prefix; - public $update_date; + + // служебные атрибуты + public $file_path; + public $success; /** * @return array the validation rules. @@ -34,10 +38,10 @@ class UploadFileParsingForm extends Model [['file'], 'file'],// 'extensions' => ['csv', 'xml'] ], // 'wrongMimeType' => 'Указан неподдерживаемый тип файла. Можно выбирать csv, xml файлы.' ], ['importer_id', 'integer','max' => 999999, 'min' => 0 ], - [['action','delete_prefix', 'delete_price'], 'boolean'], + [['action','delete_prefix', 'delete_price', 'success'], 'boolean'], ['delimiter', 'string', 'max' => 1], ['delimiter', 'default', 'value' => ';'], - ['update_date', 'safe'] + [ 'success', 'default', 'value' => false] ]; } @@ -51,9 +55,9 @@ class UploadFileParsingForm extends Model ]; } - public function readFile($filePath){ + public function readFile(){ - $data = Yii::$app->multiparser->parse($filePath); + $data = Yii::$app->multiparser->parse( $this->file_path ); if( !is_array($data) ){ $data = ['No results']; } diff --git a/backend/views/layouts/column.php b/backend/views/layouts/column.php index 62aa1be..4cf2c73 100644 --- a/backend/views/layouts/column.php +++ b/backend/views/layouts/column.php @@ -282,7 +282,11 @@ $this->beginContent('@app/views/layouts/main.php'); echo Menu::widget([ 'options' => ['class' => 'sidebar-menu'], 'items' => [ - ['label' => "Прайс парсер", 'url' => ['parser/index']], + ['label' => "Загрузка файлов", 'url' => ['#'], 'items' => [ + ['label' => 'Ручная загрузка', 'url' => ['parser/index']], + ['label' => 'Проверка прайс файлов', 'url' => ['parser/check_price']], + ], + ], ['label' => 'Управление ролями', 'url' => ['#'], 'items' => [ ['label' => 'Покупатели', 'url' => '#'], ['label' => 'Поставщики', 'url' => '#'], diff --git a/backend/views/parser/checkPrice.php b/backend/views/parser/checkPrice.php new file mode 100644 index 0000000..83ea6c4 --- /dev/null +++ b/backend/views/parser/checkPrice.php @@ -0,0 +1,24 @@ +title = 'Results'; +$this->params['breadcrumbs'][] = $this->title; +?> +
+ +

title) ?>

+ + $dataProvider, + 'columns' => [['class' => SerialColumn::className()], + 'importer_id', + 'upload_time' ]] );?> + +
\ No newline at end of file diff --git a/backend/views/parser/index.php b/backend/views/parser/index.php index c587aa7..6eb914b 100644 --- a/backend/views/parser/index.php +++ b/backend/views/parser/index.php @@ -11,6 +11,10 @@ use yii\helpers\ArrayHelper; if (!$model->action) { $model->action = 1; } + if ($model->success) { // вернулись после успешной загрузки данного файла + //echo "

Файл успешно загружен

"; + echo Html::tag('h3', 'Файл успешно загружен',['class'=>'bg-success']); + } ?>

Загрузка прайсов поставщиков

-- libgit2 0.21.4