From d682b074ca97e04d97e9c4a98c35883d096de70a Mon Sep 17 00:00:00 2001 From: Mihail Date: Wed, 23 Sep 2015 18:05:52 +0300 Subject: [PATCH] add view for details in price change form --- backend/controllers/Check_priceController.php | 108 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ backend/controllers/ParserController.php | 34 +++++++++++++++++----------------- backend/models/Details.php | 138 ++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------------------------------------------------------------- backend/models/Details_old.php | 135 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ backend/views/check_price/index.php | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ backend/views/check_price/view.php | 32 ++++++++++++++++++++++++++++++++ backend/views/layouts/column.php | 2 +- backend/views/parser/checkPrice.php | 46 ---------------------------------------------- 8 files changed, 403 insertions(+), 150 deletions(-) create mode 100644 backend/controllers/Check_priceController.php create mode 100644 backend/models/Details_old.php create mode 100644 backend/views/check_price/index.php create mode 100644 backend/views/check_price/view.php delete mode 100644 backend/views/parser/checkPrice.php diff --git a/backend/controllers/Check_priceController.php b/backend/controllers/Check_priceController.php new file mode 100644 index 0000000..4ebd29b --- /dev/null +++ b/backend/controllers/Check_priceController.php @@ -0,0 +1,108 @@ + [ + 'class' => AccessControl::className(), + 'rules' => [ + [ + 'actions' => ['index', 'view'], + 'allow' => true, + 'roles' => ['@'], + ], + ], + ], +// 'verbs' => [ +// 'class' => VerbFilter::className(), +// 'actions' => [ +// 'logout' => ['post'], +// ], +// ], + ]; + } + + /** + * @inheritdoc + */ + public function actions() + { + return [ + 'error' => [ + 'class' => 'yii\web\ErrorAction', + ], + ]; + } + + + public function actionIndex() + { + + if(Yii::$app->request->isAjax){ + CustomVarDamp::dumpAndDie(1); + } + + //$query = (new Query())->select('*')->from('{{%importer_files}}')->where(['not', ['time_end' => null]])->orderBy(['upload_time' => SORT_DESC]); + $query = Importer::find()->where(['active' => true])->orderBy(['price_date_update' => SORT_DESC]); + + $provider = new ActiveDataProvider([ + 'query' => $query, + 'pagination' => [ + 'pageSize' => 10, + ], + ]); + return $this->render('index', + [ + 'dataProvider' => $provider, + ]); + } + + + public function actionView ($id) + { + + + + + $query = Details::find()->where(['IMPORT_ID' => $id])->orderBy(['timestamp' => SORT_DESC]); + + $provider = new ActiveDataProvider([ + 'query' => $query, + 'pagination' => [ + 'pageSize' => 16, + ], + ]); + return $this->render('view', + ['dataProvider' => $provider]); + } +} diff --git a/backend/controllers/ParserController.php b/backend/controllers/ParserController.php index 5b058cb..9d0ddf8 100644 --- a/backend/controllers/ParserController.php +++ b/backend/controllers/ParserController.php @@ -166,7 +166,7 @@ class ParserController extends BaseController // 2. запишем полученные данные в таблицу товаров (Details) - $details_model = new Details('web'); + $details_model = new Details(); // проверим все ли обязательные колонки были указаны пользователем $details_model->load(['Details' => $data[0]]); if ($details_model->validate()) { @@ -176,7 +176,7 @@ class ParserController extends BaseController try { //@todo add transaction // попытаемся вставить данные в БД с апдейтом по ключам - $details_model->save($data); + $details_model->ManualInsert($data); // 3. зафиксируем дату начала и конца загрузки в файлах поставщика (для ручной загрузки начало приравниваем time_start и update_date) $files_model->time_start = $update_date; @@ -219,19 +219,19 @@ 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]); - $query = Importer::find()->where(['active' => true])->orderBy(['price_date_update' => SORT_DESC]); - - $provider = new ActiveDataProvider([ - 'query' => $query, - 'pagination' => [ - 'pageSize' => 10, - ], - ]); - return $this->render('checkPrice', - [ - 'dataProvider' => $provider]); - } +// public function actionCheck_price () +// { +// //$query = (new Query())->select('*')->from('{{%importer_files}}')->where(['not', ['time_end' => null]])->orderBy(['upload_time' => SORT_DESC]); +// $query = Importer::find()->where(['active' => true])->orderBy(['price_date_update' => SORT_DESC]); +// +// $provider = new ActiveDataProvider([ +// 'query' => $query, +// 'pagination' => [ +// 'pageSize' => 10, +// ], +// ]); +// return $this->render('check_price', +// [ +// 'dataProvider' => $provider]); +// } } diff --git a/backend/models/Details.php b/backend/models/Details.php index 2f2ec33..e172845 100644 --- a/backend/models/Details.php +++ b/backend/models/Details.php @@ -1,67 +1,74 @@ mode = $mode; + return '{{%details}}'; } + /** + * @inheritdoc + */ public function rules() { return [ - [['BRAND','ARTICLE', 'PRICE', 'BOX'], 'required' ], + [[ 'BRAND', 'ARTICLE', 'PRICE', 'DESCR', 'BOX'], 'required'], + // [['IMPORT_ID', 'BOX', 'ADD_BOX'], 'integer'], + [['PRICE'], 'number'], + [['timestamp'], 'safe'], + [['BRAND', 'ARTICLE'], 'string', 'max' => 100], + [['FULL_ARTICLE'], 'string', 'max' => 150], + [['DESCR', 'GROUP'], 'string', 'max' => 200] ]; } - public function formName() - { - return 'Details'; - } - - - public static function tableName() + /** + * @inheritdoc + */ + public function attributeLabels() { - return '{{%details}}'; + return [ + 'ID' => Yii::t('app', 'ID'), + 'IMPORT_ID' => Yii::t('app', 'Import ID'), + 'BRAND' => Yii::t('app', 'Brand'), + 'ARTICLE' => Yii::t('app', 'Article'), + 'FULL_ARTICLE' => Yii::t('app', 'Full Article'), + 'PRICE' => Yii::t('app', 'Price'), + 'DESCR' => Yii::t('app', 'Descr'), + 'BOX' => Yii::t('app', 'Box'), + 'ADD_BOX' => Yii::t('app', 'Add Box'), + 'GROUP' => Yii::t('app', 'Group'), + 'timestamp' => Yii::t('app', 'Timestamp'), + ]; } -// //@todo вероятно этой функции не место здесь -// public function prepareData ( $data, $configuration ) -// { -// if ( isset($configuration['importer_id']) && $configuration['importer_id']) { -// $data = \Yii::$app->multiparser->addColumn( $data, 'IMPORT_ID', $configuration['importer_id'] ); -// } -// // \common\components\CustomVarDamp::dumpAndDie($data); -// return $data; -// } - - /** - * @param $data - двумерный массив данных для записи в таблицу details - * @throws \yii\db\Exception - * вставляет записи с апдейтом при дубляже ключей - */ - public function save ($data) + public function ManualInsert ($data) { $table_name = self::tableName(); $keys_arr = array_keys( $data[0] ); @@ -85,51 +92,10 @@ class Details extends Model{ $query_insert = Yii::$app->db->createCommand()->batchInsert($table_name, $keys_arr, $current_batch_array)->sql; // добавим фрагмент с апдейтом при дубляже $query = "{$query_insert} {$query_update}"; - // \common\components\CustomVarDamp::dumpAndDie($query); + // \common\components\CustomVarDamp::dumpAndDie($query); $res = Yii::$app->db->createCommand($query)->execute(); } } } - -// - -//$q = " INSERT INTO {$table_name} ({$keys_string}) VALUES ("; - -//$q .= " on duplicate key update `FULL_ARTICLE` = values (`FULL_ARTICLE`), -// `PRICE` = values (`PRICE`), -// `DESCR` = values(`DESCR`), -// `BOX` = values(`BOX`), -// `ADD_BOX` = values(`ADD_BOX`), -// `GROUP` = values(`GROUP`);"; - -// INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6) -// ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b); - - - -//INSERT INTO `books` (`UserId`, `BookId`, `Count`) VALUES (13, 1001, 3) -//ON DUPLICATE KEY UPDATE `Count` = `Count` + VALUES(`Count`); - -//$values_string = ''; -//$keys_arr = array_keys( $data[0] ); -//$keys_string = implode( ',', $keys_arr); -//$table_name = self::tableName(); -//$current_batch = 0; -//for ($i = $current_batch; $i < $this::BATCH AND $i < count($data); $i++) { -// $values_string .= '(' . implode( ',', $data[$i]) . '),'; -//} -// for ($current_batch = $this::BATCH; $current_batchdb->createCommand()->batchInsert($table_name, $keys_arr, $data)->sql; -//$query = "{$query_insert} on duplicate key update `PRICE` = values (`PRICE`),`DESCR` = values(`DESCR`),`BOX` = values(`BOX`)"; -//$res = Yii::$app->db->createCommand($query)->execute(); - - - -// Yii::$app->db->createCommand()->batchInsert($table_name, $keys_arr, $data)->sql execute(); \ No newline at end of file diff --git a/backend/models/Details_old.php b/backend/models/Details_old.php new file mode 100644 index 0000000..15b1f67 --- /dev/null +++ b/backend/models/Details_old.php @@ -0,0 +1,135 @@ +mode = $mode; + } + + public function rules() + { + return [ + [['BRAND','ARTICLE', 'PRICE', 'BOX'], 'required' ], + ]; + } + + public function formName() + { + return 'Details'; + } + + + public static function tableName() + { + return '{{%details}}'; + } + +// //@todo вероятно этой функции не место здесь +// public function prepareData ( $data, $configuration ) +// { +// if ( isset($configuration['importer_id']) && $configuration['importer_id']) { +// $data = \Yii::$app->multiparser->addColumn( $data, 'IMPORT_ID', $configuration['importer_id'] ); +// } +// // \common\components\CustomVarDamp::dumpAndDie($data); +// return $data; +// } + + /** + * @param $data - двумерный массив данных для записи в таблицу details + * @throws \yii\db\Exception + * вставляет записи с апдейтом при дубляже ключей + */ + public function save ($data) + { + $table_name = self::tableName(); + $keys_arr = array_keys( $data[0] ); + // найдем те поля которые не являются ключами. Их нужно будет при дубляже апдейтить + $fields_arr_to_update = array_diff( $keys_arr, $this::KEY_COLUMN ); + + $query_update = ' on duplicate key update '; + foreach ($fields_arr_to_update as $field) { + $query_update .= "{$field} = values({$field}),"; + } + // удалим последнюю запятую + $query_update = substr($query_update, 0, strlen($query_update) - 1); + + // запросы будем выполнять пакетами + // размер пакета установлен в константе + // разобъем массив на пакеты и будем их проходить + $data = array_chunk($data, $this::BATCH ); + foreach( $data as $current_batch_array ){ + + //воспользуемся пакетной вставкой от фреймворка, плюс сразу с экранированием и защитой от инъекций + $query_insert = Yii::$app->db->createCommand()->batchInsert($table_name, $keys_arr, $current_batch_array)->sql; + // добавим фрагмент с апдейтом при дубляже + $query = "{$query_insert} {$query_update}"; + // \common\components\CustomVarDamp::dumpAndDie($query); + $res = Yii::$app->db->createCommand($query)->execute(); + + } + + } +} + +// + +//$q = " INSERT INTO {$table_name} ({$keys_string}) VALUES ("; + +//$q .= " on duplicate key update `FULL_ARTICLE` = values (`FULL_ARTICLE`), +// `PRICE` = values (`PRICE`), +// `DESCR` = values(`DESCR`), +// `BOX` = values(`BOX`), +// `ADD_BOX` = values(`ADD_BOX`), +// `GROUP` = values(`GROUP`);"; + +// INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6) +// ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b); + + + +//INSERT INTO `books` (`UserId`, `BookId`, `Count`) VALUES (13, 1001, 3) +//ON DUPLICATE KEY UPDATE `Count` = `Count` + VALUES(`Count`); + +//$values_string = ''; +//$keys_arr = array_keys( $data[0] ); +//$keys_string = implode( ',', $keys_arr); +//$table_name = self::tableName(); +//$current_batch = 0; +//for ($i = $current_batch; $i < $this::BATCH AND $i < count($data); $i++) { +// $values_string .= '(' . implode( ',', $data[$i]) . '),'; +//} +// for ($current_batch = $this::BATCH; $current_batchdb->createCommand()->batchInsert($table_name, $keys_arr, $data)->sql; +//$query = "{$query_insert} on duplicate key update `PRICE` = values (`PRICE`),`DESCR` = values(`DESCR`),`BOX` = values(`BOX`)"; +//$res = Yii::$app->db->createCommand($query)->execute(); + + + +// Yii::$app->db->createCommand()->batchInsert($table_name, $keys_arr, $data)->sql execute(); \ No newline at end of file diff --git a/backend/views/check_price/index.php b/backend/views/check_price/index.php new file mode 100644 index 0000000..e34f765 --- /dev/null +++ b/backend/views/check_price/index.php @@ -0,0 +1,58 @@ +title = 'Проверка прайсов'; +$this->params['breadcrumbs'][] = $this->title; +?> +
+ +

title) ?>

+ + + $dataProvider, + 'columns' => [['class' => SerialColumn::className()], + [ + 'class' => ActionColumn::className(), + 'template'=>'{view}', + 'contentOptions' => function ($model, $key, $index, $column){ + return ['data' => ['id' => $model->id, 'date' => $model->price_date_update]]; + } + ], + [ + 'label' =>'Поставщик', + 'value' => function ($data) { + return '№ ' .$data->id . ' ' . $data->name; + }, + ], + ['label' =>'Дата обновления', + 'attribute' => 'price_date_update' ], + ['label' => 'Кол-во дней', + 'value' => function ($data) { + $date1 = new DateTime("now"); + $date2 = new DateTime( $data->price_date_update ); + $quo_days = $date2->diff($date1)->format('%R%a'); + // уберем первый символ - там знак "+" + $quo_days = substr( $quo_days, 1, strlen($quo_days) ); + $quo_days = (int) $quo_days; + + if($quo_days > 15) + $quo_days = '>15'; + + return $quo_days; + } + ], + ]] );?> + + + + +
\ No newline at end of file diff --git a/backend/views/check_price/view.php b/backend/views/check_price/view.php new file mode 100644 index 0000000..f6d9ff0 --- /dev/null +++ b/backend/views/check_price/view.php @@ -0,0 +1,32 @@ +title = 'Проверка прайсов'; +$this->params['breadcrumbs'][] = $this->title; + +?> +
+ +

title) ?>

+ + $dataProvider, + + ] ); + + + ?> + + + +
+ \ No newline at end of file diff --git a/backend/views/layouts/column.php b/backend/views/layouts/column.php index 4cf2c73..eed7fc0 100644 --- a/backend/views/layouts/column.php +++ b/backend/views/layouts/column.php @@ -284,7 +284,7 @@ $this->beginContent('@app/views/layouts/main.php'); 'items' => [ ['label' => "Загрузка файлов", 'url' => ['#'], 'items' => [ ['label' => 'Ручная загрузка', 'url' => ['parser/index']], - ['label' => 'Проверка прайс файлов', 'url' => ['parser/check_price']], + ['label' => 'Проверка прайс файлов', 'url' => ['check_price/index']], ], ], ['label' => 'Управление ролями', 'url' => ['#'], 'items' => [ diff --git a/backend/views/parser/checkPrice.php b/backend/views/parser/checkPrice.php deleted file mode 100644 index b1d0749..0000000 --- a/backend/views/parser/checkPrice.php +++ /dev/null @@ -1,46 +0,0 @@ -title = 'Проверка прайсов'; -$this->params['breadcrumbs'][] = $this->title; -?> -
- -

title) ?>

- - $dataProvider, - 'columns' => [['class' => SerialColumn::className()], - [ - 'label' =>'Поставщик', - 'value' => function ($data) { - return '№ ' .$data->id . ' ' . $data->name; - }, - ], - ['label' =>'Дата обновления', - 'attribute' => 'price_date_update' ], - ['label' => 'Кол-во дней', - 'value' => function ($data) { - $date1 = new DateTime("now"); - $date2 = new DateTime( $data->price_date_update ); - $quo_days = $date2->diff($date1)->format('%R%a'); - // уберем первый символ - там знак "+" - $quo_days = substr( $quo_days, 1, strlen($quo_days) ); - $quo_days = (int) $quo_days; - - if($quo_days > 15) - $quo_days = '>15'; - - return $quo_days; - } - ] - ]] );?> - -
\ No newline at end of file -- libgit2 0.21.4