3cf42f5c
Mihail
init commit - bas...
|
1
2
3
4
|
<?php
namespace backend\controllers;
use Yii;
|
dd60c760
Mihail
add menu and chec...
|
5
|
use yii\data\ActiveDataProvider;
|
3cf42f5c
Mihail
init commit - bas...
|
6
|
use yii\filters\AccessControl;
|
693c46cb
Mihail
add base classes ...
|
7
|
use backend\components\base\BaseController;
|
3cf42f5c
Mihail
init commit - bas...
|
8
|
use yii\filters\VerbFilter;
|
b13b1c83
Mihail
final version par...
|
9
|
use backend\models\UploadFileParsingForm;
|
3cf42f5c
Mihail
init commit - bas...
|
10
|
use yii\web\UploadedFile;
|
fcd9278e
Mihail
parser csv v1
|
11
|
use yii\data\ArrayDataProvider;
|
74072a2a
Mihail
add first version...
|
12
|
use yii\multiparser\DynamicFormHelper;
|
474f35bf
Mihail
add DynamicFormHe...
|
13
|
use backend\components\parsers\CustomParserConfigurator;
|
8894c93a
Mihail
add Importers fil...
|
14
15
|
use backend\models\Details;
use backend\models\ImporterFiles;
|
9dd0fbe4
Mihail
add writing data ...
|
16
|
use backend\models\Importer;
|
8894c93a
Mihail
add Importers fil...
|
17
|
use yii\base\ErrorException;
|
dd60c760
Mihail
add menu and chec...
|
18
|
use yii\db\Query;
|
500b481a
Administrator
JSON
|
19
|
|
e774f057
Mihail
work with custome...
|
20
|
use common\components\CustomVarDamp;
|
3cf42f5c
Mihail
init commit - bas...
|
21
22
|
/**
|
b13b1c83
Mihail
final version par...
|
23
|
* Parser controller
|
3cf42f5c
Mihail
init commit - bas...
|
24
|
*/
|
693c46cb
Mihail
add base classes ...
|
25
|
class ParserController extends BaseController
|
3cf42f5c
Mihail
init commit - bas...
|
26
|
{
|
500b481a
Administrator
JSON
|
27
|
public $layout = "/column";
|
8894c93a
Mihail
add Importers fil...
|
28
|
|
3cf42f5c
Mihail
init commit - bas...
|
29
30
31
32
33
34
35
36
37
38
|
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
|
dd60c760
Mihail
add menu and chec...
|
39
|
'actions' => ['index', 'results', 'write','check_price'],
|
3cf42f5c
Mihail
init commit - bas...
|
40
41
42
43
44
|
'allow' => true,
'roles' => ['@'],
],
],
],
|
e774f057
Mihail
work with custome...
|
45
46
47
48
49
50
|
// 'verbs' => [
// 'class' => VerbFilter::className(),
// 'actions' => [
// 'logout' => ['post'],
// ],
// ],
|
3cf42f5c
Mihail
init commit - bas...
|
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
|
500b481a
Administrator
JSON
|
66
|
|
3cf42f5c
Mihail
init commit - bas...
|
67
68
|
public function actionIndex()
{
|
77422ce3
Mihail
edit upload form
|
69
|
$model = new UploadFileParsingForm();
|
3cf42f5c
Mihail
init commit - bas...
|
70
|
|
500b481a
Administrator
JSON
|
71
72
73
|
return $this->render('index', ['model' => $model]);
}
|
8894c93a
Mihail
add Importers fil...
|
74
75
|
public function actionResults()
{
|
500b481a
Administrator
JSON
|
76
|
$model = new UploadFileParsingForm();
|
474f35bf
Mihail
add DynamicFormHe...
|
77
|
$data = [];
|
b13b1c83
Mihail
final version par...
|
78
|
if ($model->load(Yii::$app->request->post())) {
|
3cf42f5c
Mihail
init commit - bas...
|
79
|
$model->file = UploadedFile::getInstance($model, 'file');
|
8894c93a
Mihail
add Importers fil...
|
80
|
// первый проход - валидируем, сохраняем файл, ложим в кеш отпарсенные данные и параметры модели (потом при записи в базу данных они пригодятся)
|
3663f570
Mihail
draft commit
|
81
|
if ($model->validate()) {
|
dd60c760
Mihail
add menu and chec...
|
82
|
$model->file_path = Yii::getAlias('@webroot') . '/uploads/' . $model->file->baseName . '.' . $model->file->extension;
|
500b481a
Administrator
JSON
|
83
|
|
dd60c760
Mihail
add menu and chec...
|
84
|
$model->file->saveAs($model->file_path);
|
8894c93a
Mihail
add Importers fil...
|
85
|
//запускаем парсинг
|
dd60c760
Mihail
add menu and chec...
|
86
|
$data = $model->readFile();
|
8894c93a
Mihail
add Importers fil...
|
87
88
89
90
|
// сохраняем в кеш отпарсенные даные
Yii::$app->getCache()->set('parser_data', json_encode($data));
// сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных
Yii::$app->getCache()->set('parser_configuration', serialize($model));
|
500b481a
Administrator
JSON
|
91
|
|
500b481a
Administrator
JSON
|
92
|
|
3cf42f5c
Mihail
init commit - bas...
|
93
|
}
|
8894c93a
Mihail
add Importers fil...
|
94
95
|
// листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные
} else if (Yii::$app->getCache()->get('parser_data')) {
|
500b481a
Administrator
JSON
|
96
|
|
8894c93a
Mihail
add Importers fil...
|
97
|
$data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
|
500b481a
Administrator
JSON
|
98
|
|
3cf42f5c
Mihail
init commit - bas...
|
99
100
|
}
|
474f35bf
Mihail
add DynamicFormHe...
|
101
102
103
104
105
106
107
|
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
|
8894c93a
Mihail
add Importers fil...
|
108
109
|
//формируем заголовок для пользователя, где он сможет выбрать соответсвие полей (выпадающий список)
$header_model = DynamicFormHelper::CreateDynamicModel(count($data[0]));
|
474f35bf
Mihail
add DynamicFormHe...
|
110
|
|
474f35bf
Mihail
add DynamicFormHe...
|
111
112
113
|
return $this->render('results',
['model' => $data,
'header_model' => $header_model,
|
8894c93a
Mihail
add Importers fil...
|
114
115
|
// список колонок для выбора
'basic_column' => Yii::$app->multiparser->getConfiguration('csv', 'basic_column'),
|
474f35bf
Mihail
add DynamicFormHe...
|
116
|
'dataProvider' => $provider]);
|
3cf42f5c
Mihail
init commit - bas...
|
117
|
}
|
474f35bf
Mihail
add DynamicFormHe...
|
118
|
|
8894c93a
Mihail
add Importers fil...
|
119
120
|
public function actionWrite()
{
|
8894c93a
Mihail
add Importers fil...
|
121
122
123
124
125
126
127
128
|
//получим колонки которые выбрал пользователь
$arr_attributes = Yii::$app->request->post()['DynamicModel'];
//соберем модель по полученным данным
$model = DynamicFormHelper::CreateDynamicModel($arr_attributes);
//добавим правила валидации (колонки должны быть те что указаны в конфиге)
foreach ($arr_attributes as $key => $value) {
$model->addRule($key, 'in', ['range' => array_keys(Yii::$app->multiparser->getConfiguration('csv', 'basic_column'))]);
}
|
474f35bf
Mihail
add DynamicFormHe...
|
129
|
|
8894c93a
Mihail
add Importers fil...
|
130
131
|
// провалидируем выбранные колонки
if ($model->validate()) {
|
28253169
Mihail
add converter as ...
|
132
|
|
8894c93a
Mihail
add Importers fil...
|
133
134
|
// валидация успешна у нас есть соответсвие колонок, преобразуем в массив данное соответсвие для дальнейшей работы
$arr = $model->toArray();
|
aa518ad3
Mihail
finishing with co...
|
135
|
|
8894c93a
Mihail
add Importers fil...
|
136
137
138
139
140
141
142
|
// получим данные из кеша
if (Yii::$app->getCache()->get('parser_data') && Yii::$app->getCache()->get('parser_configuration')) {
$data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
$configuration = unserialize(Yii::$app->getCache()->get('parser_configuration'));
} else {
CustomVarDamp::dumpAndDie('Ошибка кеша');
}
|
474f35bf
Mihail
add DynamicFormHe...
|
143
|
|
8894c93a
Mihail
add Importers fil...
|
144
145
146
147
148
|
// соотнесем отпарсенные данные с соответсивем полученным от пользователя
// для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию
$data = \Yii::$app->multiparser->convertToAssocArray($data, $arr, 'attr_');
|
9dd0fbe4
Mihail
add writing data ...
|
149
|
// 1. запишем дату старта в таблицу файлов поставщика (ImportersFiles)
|
8894c93a
Mihail
add Importers fil...
|
150
151
152
153
154
155
|
$files_model = new ImporterFiles();
// id поставщика получим из конфигурации
$files_model->load(['ImporterFiles' => $configuration->toArray()]);
if ($files_model->validate()) {
try {
$files_model->save();
|
9dd0fbe4
Mihail
add writing data ...
|
156
157
158
159
160
161
162
|
$update_date = $files_model->find()
->where(['importer_id' => $files_model->importer_id])
->orderBy(['id' => SORT_DESC])
->one()
->upload_time;
$update_date = date('Y-m-d H:i:s',strtotime($update_date));
// CustomVarDamp::dumpAndDie(strtotime($update_date));
|
8894c93a
Mihail
add Importers fil...
|
163
164
165
166
167
|
} catch (ErrorException $e) {
CustomVarDamp::dump($e->getMessage());
}
|
9dd0fbe4
Mihail
add writing data ...
|
168
|
// 2. запишем полученные данные в таблицу товаров (Details)
|
8894c93a
Mihail
add Importers fil...
|
169
170
171
172
|
$details_model = new Details('web');
// проверим все ли обязательные колонки были указаны пользователем
$details_model->load(['Details' => $data[0]]);
if ($details_model->validate()) {
|
9dd0fbe4
Mihail
add writing data ...
|
173
174
|
// дополним данные значением импортера и даты обновления цены
$data = \Yii::$app->multiparser->addColumns( $data, ['IMPORT_ID' => $configuration['importer_id'],'timestamp' => $update_date] );
|
8894c93a
Mihail
add Importers fil...
|
175
176
|
try {
|
9dd0fbe4
Mihail
add writing data ...
|
177
|
//@todo add transaction
|
8894c93a
Mihail
add Importers fil...
|
178
179
180
|
// попытаемся вставить данные в БД с апдейтом по ключам
$details_model->save($data);
|
9dd0fbe4
Mihail
add writing data ...
|
181
182
183
|
// 3. зафиксируем дату конца загрузки в файлах поставщика
$files_model->time_end = date('Y-m-d H:i:s');
// CustomVarDamp::dumpAndDie($files_model);
|
8894c93a
Mihail
add Importers fil...
|
184
185
|
$files_model->save();
|
9dd0fbe4
Mihail
add writing data ...
|
186
187
188
189
190
191
192
|
// 4. зафиксируем дату загрузки в таблице поставщиков
$imp_model = Importer::findOne( $configuration['importer_id'] );
$imp_model->price_date_update = ''.strtotime($update_date);
if (!$imp_model->save()) {
CustomVarDamp::dumpAndDie( $imp_model->getErrors() );
}
|
dd60c760
Mihail
add menu and chec...
|
193
|
$configuration['success'] = true;
|
8894c93a
Mihail
add Importers fil...
|
194
195
196
|
// все прошло успешно - очищаем кеш
Yii::$app->getCache()->delete('parser_data');
Yii::$app->getCache()->delete('parser_configuration');
|
9dd0fbe4
Mihail
add writing data ...
|
197
|
// @todo - Delete the file
|
8894c93a
Mihail
add Importers fil...
|
198
|
|
dd60c760
Mihail
add menu and chec...
|
199
200
|
// все успешно - возвращаемся в начало
return $this->render('index', ['model' => $configuration]);
|
8894c93a
Mihail
add Importers fil...
|
201
202
203
204
205
206
207
208
209
210
211
|
} catch (ErrorException $e) {
CustomVarDamp::dump($e->getMessage());
}
}
if ($details_model->hasErrors()) {
$errors_arr = $details_model->getErrors();
foreach ($errors_arr as $error) {
CustomVarDamp::dump(array_values($error));
}
}
|
474f35bf
Mihail
add DynamicFormHe...
|
212
|
|
3cf42f5c
Mihail
init commit - bas...
|
213
|
|
8894c93a
Mihail
add Importers fil...
|
214
215
216
217
218
219
|
}
}
}
|
3cf42f5c
Mihail
init commit - bas...
|
220
|
|
dd60c760
Mihail
add menu and chec...
|
221
222
223
224
225
226
227
228
229
230
231
232
233
234
|
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]);
}
|
3cf42f5c
Mihail
init commit - bas...
|
235
|
}
|