Commit d682b074ca97e04d97e9c4a98c35883d096de70a

Authored by Mihail
1 parent 49293a4b

add view for details in price change form

backend/controllers/Check_priceController.php 0 → 100644
  1 +<?php
  2 +namespace backend\controllers;
  3 +
  4 +use Yii;
  5 +use yii\bootstrap\Modal;
  6 +use yii\data\ActiveDataProvider;
  7 +use yii\filters\AccessControl;
  8 +use backend\components\base\BaseController;
  9 +use yii\filters\VerbFilter;
  10 +use backend\models\UploadFileParsingForm;
  11 +use yii\web\UploadedFile;
  12 +use yii\data\ArrayDataProvider;
  13 +use yii\multiparser\DynamicFormHelper;
  14 +use backend\components\parsers\CustomParserConfigurator;
  15 +use backend\models\Details;
  16 +use backend\models\ImporterFiles;
  17 +use backend\models\Importer;
  18 +use yii\base\ErrorException;
  19 +use yii\db\Query;
  20 +
  21 +use common\components\CustomVarDamp;
  22 +
  23 +/**
  24 + * Parser controller
  25 + */
  26 +class Check_priceController extends BaseController
  27 +{
  28 + public $layout = "/column";
  29 +
  30 + /**
  31 + * @inheritdoc
  32 + */
  33 + public function behaviors()
  34 + {
  35 + return [
  36 + 'access' => [
  37 + 'class' => AccessControl::className(),
  38 + 'rules' => [
  39 + [
  40 + 'actions' => ['index', 'view'],
  41 + 'allow' => true,
  42 + 'roles' => ['@'],
  43 + ],
  44 + ],
  45 + ],
  46 +// 'verbs' => [
  47 +// 'class' => VerbFilter::className(),
  48 +// 'actions' => [
  49 +// 'logout' => ['post'],
  50 +// ],
  51 +// ],
  52 + ];
  53 + }
  54 +
  55 + /**
  56 + * @inheritdoc
  57 + */
  58 + public function actions()
  59 + {
  60 + return [
  61 + 'error' => [
  62 + 'class' => 'yii\web\ErrorAction',
  63 + ],
  64 + ];
  65 + }
  66 +
  67 +
  68 + public function actionIndex()
  69 + {
  70 +
  71 + if(Yii::$app->request->isAjax){
  72 + CustomVarDamp::dumpAndDie(1);
  73 + }
  74 +
  75 + //$query = (new Query())->select('*')->from('{{%importer_files}}')->where(['not', ['time_end' => null]])->orderBy(['upload_time' => SORT_DESC]);
  76 + $query = Importer::find()->where(['active' => true])->orderBy(['price_date_update' => SORT_DESC]);
  77 +
  78 + $provider = new ActiveDataProvider([
  79 + 'query' => $query,
  80 + 'pagination' => [
  81 + 'pageSize' => 10,
  82 + ],
  83 + ]);
  84 + return $this->render('index',
  85 + [
  86 + 'dataProvider' => $provider,
  87 + ]);
  88 + }
  89 +
  90 +
  91 + public function actionView ($id)
  92 + {
  93 +
  94 +
  95 +
  96 +
  97 + $query = Details::find()->where(['IMPORT_ID' => $id])->orderBy(['timestamp' => SORT_DESC]);
  98 +
  99 + $provider = new ActiveDataProvider([
  100 + 'query' => $query,
  101 + 'pagination' => [
  102 + 'pageSize' => 16,
  103 + ],
  104 + ]);
  105 + return $this->render('view',
  106 + ['dataProvider' => $provider]);
  107 + }
  108 +}
... ...
backend/controllers/ParserController.php
... ... @@ -166,7 +166,7 @@ class ParserController extends BaseController
166 166  
167 167  
168 168 // 2. запишем полученные данные в таблицу товаров (Details)
169   - $details_model = new Details('web');
  169 + $details_model = new Details();
170 170 // проверим все ли обязательные колонки были указаны пользователем
171 171 $details_model->load(['Details' => $data[0]]);
172 172 if ($details_model->validate()) {
... ... @@ -176,7 +176,7 @@ class ParserController extends BaseController
176 176 try {
177 177 //@todo add transaction
178 178 // попытаемся вставить данные в БД с апдейтом по ключам
179   - $details_model->save($data);
  179 + $details_model->ManualInsert($data);
180 180  
181 181 // 3. зафиксируем дату начала и конца загрузки в файлах поставщика (для ручной загрузки начало приравниваем time_start и update_date)
182 182 $files_model->time_start = $update_date;
... ... @@ -219,19 +219,19 @@ class ParserController extends BaseController
219 219  
220 220 }
221 221  
222   - public function actionCheck_price ()
223   - {
224   - //$query = (new Query())->select('*')->from('{{%importer_files}}')->where(['not', ['time_end' => null]])->orderBy(['upload_time' => SORT_DESC]);
225   - $query = Importer::find()->where(['active' => true])->orderBy(['price_date_update' => SORT_DESC]);
226   -
227   - $provider = new ActiveDataProvider([
228   - 'query' => $query,
229   - 'pagination' => [
230   - 'pageSize' => 10,
231   - ],
232   - ]);
233   - return $this->render('checkPrice',
234   - [
235   - 'dataProvider' => $provider]);
236   - }
  222 +// public function actionCheck_price ()
  223 +// {
  224 +// //$query = (new Query())->select('*')->from('{{%importer_files}}')->where(['not', ['time_end' => null]])->orderBy(['upload_time' => SORT_DESC]);
  225 +// $query = Importer::find()->where(['active' => true])->orderBy(['price_date_update' => SORT_DESC]);
  226 +//
  227 +// $provider = new ActiveDataProvider([
  228 +// 'query' => $query,
  229 +// 'pagination' => [
  230 +// 'pageSize' => 10,
  231 +// ],
  232 +// ]);
  233 +// return $this->render('check_price',
  234 +// [
  235 +// 'dataProvider' => $provider]);
  236 +// }
237 237 }
... ...
backend/models/Details.php
1 1 <?php
2   -/**
3   - * Created by PhpStorm.
4   - * User: Cibermag
5   - * Date: 15.09.2015
6   - * Time: 16:49
7   - */
8 2  
9 3 namespace backend\models;
10 4  
11   -use yii\base\Model;
12 5 use Yii;
  6 +use backend\components\base\BaseActiveRecord;
13 7  
14   -class Details extends Model{
  8 +/**
  9 + * This is the model class for table "{{%details}}".
  10 + *
  11 + * @property string $ID
  12 + * @property string $IMPORT_ID
  13 + * @property string $BRAND
  14 + * @property string $ARTICLE
  15 + * @property string $FULL_ARTICLE
  16 + * @property double $PRICE
  17 + * @property string $DESCR
  18 + * @property string $BOX
  19 + * @property string $ADD_BOX
  20 + * @property string $GROUP
  21 + * @property string $timestamp
  22 + */
  23 +class Details extends BaseActiveRecord
  24 +{
15 25 const KEY_COLUMN = ['IMPORT_ID','BRAND','ARTICLE'];
16 26 const BATCH = 500;
17   -
18   - private $mode;
19   -
20   - // обязательные поля модели
21   - public $BRAND;
22   - public $ARTICLE;
23   - public $PRICE;
24   - public $BOX;
25   -
26   - function __construct($mode)
  27 + /**
  28 + * @inheritdoc
  29 + */
  30 + public static function tableName()
27 31 {
28   - $this->mode = $mode;
  32 + return '{{%details}}';
29 33 }
30 34  
  35 + /**
  36 + * @inheritdoc
  37 + */
31 38 public function rules()
32 39 {
33 40 return [
34   - [['BRAND','ARTICLE', 'PRICE', 'BOX'], 'required' ],
  41 + [[ 'BRAND', 'ARTICLE', 'PRICE', 'DESCR', 'BOX'], 'required'],
  42 + // [['IMPORT_ID', 'BOX', 'ADD_BOX'], 'integer'],
  43 + [['PRICE'], 'number'],
  44 + [['timestamp'], 'safe'],
  45 + [['BRAND', 'ARTICLE'], 'string', 'max' => 100],
  46 + [['FULL_ARTICLE'], 'string', 'max' => 150],
  47 + [['DESCR', 'GROUP'], 'string', 'max' => 200]
35 48 ];
36 49 }
37 50  
38   - public function formName()
39   - {
40   - return 'Details';
41   - }
42   -
43   -
44   - public static function tableName()
  51 + /**
  52 + * @inheritdoc
  53 + */
  54 + public function attributeLabels()
45 55 {
46   - return '{{%details}}';
  56 + return [
  57 + 'ID' => Yii::t('app', 'ID'),
  58 + 'IMPORT_ID' => Yii::t('app', 'Import ID'),
  59 + 'BRAND' => Yii::t('app', 'Brand'),
  60 + 'ARTICLE' => Yii::t('app', 'Article'),
  61 + 'FULL_ARTICLE' => Yii::t('app', 'Full Article'),
  62 + 'PRICE' => Yii::t('app', 'Price'),
  63 + 'DESCR' => Yii::t('app', 'Descr'),
  64 + 'BOX' => Yii::t('app', 'Box'),
  65 + 'ADD_BOX' => Yii::t('app', 'Add Box'),
  66 + 'GROUP' => Yii::t('app', 'Group'),
  67 + 'timestamp' => Yii::t('app', 'Timestamp'),
  68 + ];
47 69 }
48 70  
49   -// //@todo вероятно этой функции не место здесь
50   -// public function prepareData ( $data, $configuration )
51   -// {
52   -// if ( isset($configuration['importer_id']) && $configuration['importer_id']) {
53   -// $data = \Yii::$app->multiparser->addColumn( $data, 'IMPORT_ID', $configuration['importer_id'] );
54   -// }
55   -// // \common\components\CustomVarDamp::dumpAndDie($data);
56   -// return $data;
57   -// }
58   -
59   - /**
60   - * @param $data - двумерный массив данных для записи в таблицу details
61   - * @throws \yii\db\Exception
62   - * вставляет записи с апдейтом при дубляже ключей
63   - */
64   - public function save ($data)
  71 + public function ManualInsert ($data)
65 72 {
66 73 $table_name = self::tableName();
67 74 $keys_arr = array_keys( $data[0] );
... ... @@ -85,51 +92,10 @@ class Details extends Model{
85 92 $query_insert = Yii::$app->db->createCommand()->batchInsert($table_name, $keys_arr, $current_batch_array)->sql;
86 93 // добавим фрагмент с апдейтом при дубляже
87 94 $query = "{$query_insert} {$query_update}";
88   - // \common\components\CustomVarDamp::dumpAndDie($query);
  95 + // \common\components\CustomVarDamp::dumpAndDie($query);
89 96 $res = Yii::$app->db->createCommand($query)->execute();
90 97  
91 98 }
92 99  
93 100 }
94 101 }
95   -
96   -//
97   -
98   -//$q = " INSERT INTO {$table_name} ({$keys_string}) VALUES (";
99   -
100   -//$q .= " on duplicate key update `FULL_ARTICLE` = values (`FULL_ARTICLE`),
101   -// `PRICE` = values (`PRICE`),
102   -// `DESCR` = values(`DESCR`),
103   -// `BOX` = values(`BOX`),
104   -// `ADD_BOX` = values(`ADD_BOX`),
105   -// `GROUP` = values(`GROUP`);";
106   -
107   -// INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
108   -// ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);
109   -
110   -
111   -
112   -//INSERT INTO `books` (`UserId`, `BookId`, `Count`) VALUES (13, 1001, 3)
113   -//ON DUPLICATE KEY UPDATE `Count` = `Count` + VALUES(`Count`);
114   -
115   -//$values_string = '';
116   -//$keys_arr = array_keys( $data[0] );
117   -//$keys_string = implode( ',', $keys_arr);
118   -//$table_name = self::tableName();
119   -//$current_batch = 0;
120   -//for ($i = $current_batch; $i < $this::BATCH AND $i < count($data); $i++) {
121   -// $values_string .= '(' . implode( ',', $data[$i]) . '),';
122   -//}
123   -// for ($current_batch = $this::BATCH; $current_batch<count($data); $current_batch + $this::BATCH )
124   -//// удалим последнюю запятую
125   -//$values_string = substr($values_string, 0, strlen($values_string) - 1) . ' ';
126   -////\common\components\CustomVarDamp::dumpAndDie($values_string);
127   -//// $query = "INSERT INTO {$table_name}({$keys_string}) VALUES {$values_string}";
128   -//// on duplicate key update `PRICE` = values (`PRICE`),`DESCR` = values(`DESCR`),`BOX` = values(`BOX`)";
129   -//$query_insert = Yii::$app->db->createCommand()->batchInsert($table_name, $keys_arr, $data)->sql;
130   -//$query = "{$query_insert} on duplicate key update `PRICE` = values (`PRICE`),`DESCR` = values(`DESCR`),`BOX` = values(`BOX`)";
131   -//$res = Yii::$app->db->createCommand($query)->execute();
132   -
133   -
134   -
135   -// Yii::$app->db->createCommand()->batchInsert($table_name, $keys_arr, $data)->sql execute();
136 102 \ No newline at end of file
... ...
backend/models/Details_old.php 0 → 100644
  1 +<?php
  2 +/**
  3 + * Created by PhpStorm.
  4 + * User: Cibermag
  5 + * Date: 15.09.2015
  6 + * Time: 16:49
  7 + */
  8 +
  9 +namespace backend\models;
  10 +
  11 +use yii\base\Model;
  12 +use Yii;
  13 +
  14 +class Details_old extends Model{
  15 + const KEY_COLUMN = ['IMPORT_ID','BRAND','ARTICLE'];
  16 + const BATCH = 500;
  17 +
  18 + private $mode;
  19 +
  20 + // обязательные поля модели
  21 + public $BRAND;
  22 + public $ARTICLE;
  23 + public $PRICE;
  24 + public $BOX;
  25 +
  26 + function __construct($mode)
  27 + {
  28 + $this->mode = $mode;
  29 + }
  30 +
  31 + public function rules()
  32 + {
  33 + return [
  34 + [['BRAND','ARTICLE', 'PRICE', 'BOX'], 'required' ],
  35 + ];
  36 + }
  37 +
  38 + public function formName()
  39 + {
  40 + return 'Details';
  41 + }
  42 +
  43 +
  44 + public static function tableName()
  45 + {
  46 + return '{{%details}}';
  47 + }
  48 +
  49 +// //@todo вероятно этой функции не место здесь
  50 +// public function prepareData ( $data, $configuration )
  51 +// {
  52 +// if ( isset($configuration['importer_id']) && $configuration['importer_id']) {
  53 +// $data = \Yii::$app->multiparser->addColumn( $data, 'IMPORT_ID', $configuration['importer_id'] );
  54 +// }
  55 +// // \common\components\CustomVarDamp::dumpAndDie($data);
  56 +// return $data;
  57 +// }
  58 +
  59 + /**
  60 + * @param $data - двумерный массив данных для записи в таблицу details
  61 + * @throws \yii\db\Exception
  62 + * вставляет записи с апдейтом при дубляже ключей
  63 + */
  64 + public function save ($data)
  65 + {
  66 + $table_name = self::tableName();
  67 + $keys_arr = array_keys( $data[0] );
  68 + // найдем те поля которые не являются ключами. Их нужно будет при дубляже апдейтить
  69 + $fields_arr_to_update = array_diff( $keys_arr, $this::KEY_COLUMN );
  70 +
  71 + $query_update = ' on duplicate key update ';
  72 + foreach ($fields_arr_to_update as $field) {
  73 + $query_update .= "{$field} = values({$field}),";
  74 + }
  75 + // удалим последнюю запятую
  76 + $query_update = substr($query_update, 0, strlen($query_update) - 1);
  77 +
  78 + // запросы будем выполнять пакетами
  79 + // размер пакета установлен в константе
  80 + // разобъем массив на пакеты и будем их проходить
  81 + $data = array_chunk($data, $this::BATCH );
  82 + foreach( $data as $current_batch_array ){
  83 +
  84 + //воспользуемся пакетной вставкой от фреймворка, плюс сразу с экранированием и защитой от инъекций
  85 + $query_insert = Yii::$app->db->createCommand()->batchInsert($table_name, $keys_arr, $current_batch_array)->sql;
  86 + // добавим фрагмент с апдейтом при дубляже
  87 + $query = "{$query_insert} {$query_update}";
  88 + // \common\components\CustomVarDamp::dumpAndDie($query);
  89 + $res = Yii::$app->db->createCommand($query)->execute();
  90 +
  91 + }
  92 +
  93 + }
  94 +}
  95 +
  96 +//
  97 +
  98 +//$q = " INSERT INTO {$table_name} ({$keys_string}) VALUES (";
  99 +
  100 +//$q .= " on duplicate key update `FULL_ARTICLE` = values (`FULL_ARTICLE`),
  101 +// `PRICE` = values (`PRICE`),
  102 +// `DESCR` = values(`DESCR`),
  103 +// `BOX` = values(`BOX`),
  104 +// `ADD_BOX` = values(`ADD_BOX`),
  105 +// `GROUP` = values(`GROUP`);";
  106 +
  107 +// INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)
  108 +// ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);
  109 +
  110 +
  111 +
  112 +//INSERT INTO `books` (`UserId`, `BookId`, `Count`) VALUES (13, 1001, 3)
  113 +//ON DUPLICATE KEY UPDATE `Count` = `Count` + VALUES(`Count`);
  114 +
  115 +//$values_string = '';
  116 +//$keys_arr = array_keys( $data[0] );
  117 +//$keys_string = implode( ',', $keys_arr);
  118 +//$table_name = self::tableName();
  119 +//$current_batch = 0;
  120 +//for ($i = $current_batch; $i < $this::BATCH AND $i < count($data); $i++) {
  121 +// $values_string .= '(' . implode( ',', $data[$i]) . '),';
  122 +//}
  123 +// for ($current_batch = $this::BATCH; $current_batch<count($data); $current_batch + $this::BATCH )
  124 +//// удалим последнюю запятую
  125 +//$values_string = substr($values_string, 0, strlen($values_string) - 1) . ' ';
  126 +////\common\components\CustomVarDamp::dumpAndDie($values_string);
  127 +//// $query = "INSERT INTO {$table_name}({$keys_string}) VALUES {$values_string}";
  128 +//// on duplicate key update `PRICE` = values (`PRICE`),`DESCR` = values(`DESCR`),`BOX` = values(`BOX`)";
  129 +//$query_insert = Yii::$app->db->createCommand()->batchInsert($table_name, $keys_arr, $data)->sql;
  130 +//$query = "{$query_insert} on duplicate key update `PRICE` = values (`PRICE`),`DESCR` = values(`DESCR`),`BOX` = values(`BOX`)";
  131 +//$res = Yii::$app->db->createCommand($query)->execute();
  132 +
  133 +
  134 +
  135 +// Yii::$app->db->createCommand()->batchInsert($table_name, $keys_arr, $data)->sql execute();
0 136 \ No newline at end of file
... ...
backend/views/parser/checkPrice.php renamed to backend/views/check_price/index.php
... ... @@ -2,7 +2,8 @@
2 2 use yii\helpers\Html;
3 3 use yii\grid\GridView;
4 4 use yii\grid\SerialColumn;
5   -use yii\grid\DataColumn;
  5 +use yii\grid\ActionColumn;
  6 +use yii\widgets\Pjax;
6 7  
7 8  
8 9 /* @var $this yii\web\View */
... ... @@ -16,9 +17,17 @@ $this-&gt;params[&#39;breadcrumbs&#39;][] = $this-&gt;title;
16 17  
17 18 <h1><?= Html::encode($this->title) ?></h1>
18 19  
  20 +
19 21 <?= GridView::widget( ['dataProvider' => $dataProvider,
20 22 'columns' => [['class' => SerialColumn::className()],
21 23 [
  24 + 'class' => ActionColumn::className(),
  25 + 'template'=>'{view}',
  26 + 'contentOptions' => function ($model, $key, $index, $column){
  27 + return ['data' => ['id' => $model->id, 'date' => $model->price_date_update]];
  28 + }
  29 + ],
  30 + [
22 31 'label' =>'Поставщик',
23 32 'value' => function ($data) {
24 33 return '№ ' .$data->id . ' ' . $data->name;
... ... @@ -34,13 +43,16 @@ $this-&gt;params[&#39;breadcrumbs&#39;][] = $this-&gt;title;
34 43 // уберем первый символ - там знак "+"
35 44 $quo_days = substr( $quo_days, 1, strlen($quo_days) );
36 45 $quo_days = (int) $quo_days;
37   -
  46 +
38 47 if($quo_days > 15)
39 48 $quo_days = '>15';
40 49  
41 50 return $quo_days;
42 51 }
43   - ]
  52 + ],
44 53 ]] );?>
45 54  
  55 +
  56 +
  57 +
46 58 </div>
47 59 \ No newline at end of file
... ...
backend/views/check_price/view.php 0 → 100644
  1 +<?php
  2 +use yii\helpers\Html;
  3 +use yii\grid\GridView;
  4 +use yii\grid\SerialColumn;
  5 +use yii\bootstrap\Modal;
  6 +
  7 +
  8 +/* @var $this yii\web\View */
  9 +/* @var $searchModel backend\models\CatalogSearch */
  10 +/* @var $dataProvider yii\data\ActiveDataProvider */
  11 +
  12 +$this->title = 'Проверка прайсов';
  13 +$this->params['breadcrumbs'][] = $this->title;
  14 +
  15 +?>
  16 +<div class="catalog-index">
  17 +
  18 + <h1><?= Html::encode($this->title) ?></h1>
  19 +
  20 + <?= GridView::widget( ['dataProvider' => $dataProvider,
  21 +
  22 + ] );
  23 +
  24 +
  25 + ?>
  26 +
  27 +
  28 +
  29 +</div>
  30 +<?php
  31 +
  32 +?>
0 33 \ No newline at end of file
... ...
backend/views/layouts/column.php
... ... @@ -284,7 +284,7 @@ $this-&gt;beginContent(&#39;@app/views/layouts/main.php&#39;);
284 284 'items' => [
285 285 ['label' => "Загрузка файлов", 'url' => ['#'], 'items' => [
286 286 ['label' => 'Ручная загрузка', 'url' => ['parser/index']],
287   - ['label' => 'Проверка прайс файлов', 'url' => ['parser/check_price']],
  287 + ['label' => 'Проверка прайс файлов', 'url' => ['check_price/index']],
288 288 ],
289 289 ],
290 290 ['label' => 'Управление ролями', 'url' => ['#'], 'items' => [
... ...