3cf42f5c
Mihail
init commit - bas...
|
1
2
3
4
|
<?php
namespace backend\controllers;
use Yii;
|
642796c8
Mihail
merge with server
|
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;
|
3c5edb9b
Mihail
edit createAssocA...
|
12
|
use yii\multiparser\DynamicFormHelper;
|
474f35bf
Mihail
add DynamicFormHe...
|
13
|
use backend\components\parsers\CustomParserConfigurator;
|
642796c8
Mihail
merge with server
|
14
15
16
17
18
|
use backend\models\Details;
use backend\models\ImporterFiles;
use backend\models\Importer;
use yii\base\ErrorException;
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";
|
642796c8
Mihail
merge with server
|
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' => [
[
|
3cf42f5c
Mihail
init commit - bas...
|
39
40
41
42
43
|
'allow' => true,
'roles' => ['@'],
],
],
],
|
e774f057
Mihail
work with custome...
|
44
45
46
47
48
49
|
// 'verbs' => [
// 'class' => VerbFilter::className(),
// 'actions' => [
// 'logout' => ['post'],
// ],
// ],
|
3cf42f5c
Mihail
init commit - bas...
|
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
}
|
500b481a
Administrator
JSON
|
65
|
|
642796c8
Mihail
merge with server
|
66
|
public function actionIndex($mode = 0)
|
3cf42f5c
Mihail
init commit - bas...
|
67
|
{
|
77422ce3
Mihail
edit upload form
|
68
|
$model = new UploadFileParsingForm();
|
642796c8
Mihail
merge with server
|
69
70
71
|
// установим режим, 0 - ручная загрузка, 1 - автозагрузка
$model->mode = $mode;
//CustomVarDamp::dumpAndDie(phpinfo());
|
500b481a
Administrator
JSON
|
72
73
74
|
return $this->render('index', ['model' => $model]);
}
|
642796c8
Mihail
merge with server
|
75
76
77
78
79
80
|
// public function beforeAction($action)
// {
// if($action->actionMethod ='actionResults'){
// CustomVarDamp::dumpAndDie(phpinfo());
// }
// }
|
500b481a
Administrator
JSON
|
81
|
|
642796c8
Mihail
merge with server
|
82
83
84
|
public function actionResults($mode = 0)
{
$model = new UploadFileParsingForm(['mode' => $mode]);
|
474f35bf
Mihail
add DynamicFormHe...
|
85
|
$data = [];
|
b13b1c83
Mihail
final version par...
|
86
|
if ($model->load(Yii::$app->request->post())) {
|
3cf42f5c
Mihail
init commit - bas...
|
87
|
$model->file = UploadedFile::getInstance($model, 'file');
|
642796c8
Mihail
merge with server
|
88
|
// первый проход - валидируем, сохраняем файл, ложим в кеш (для ручной загрузки) отпарсенные данные и параметры модели (потом при записи в базу данных они пригодятся)
|
3663f570
Mihail
draft commit
|
89
|
if ($model->validate()) {
|
642796c8
Mihail
merge with server
|
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
// запишем дату загрузки файла в таблицу файлов поставщика (ImportersFiles)
$files_model = new ImporterFiles();
// id поставщика получим из конфигурации
$files_model->load(['ImporterFiles' => $model->toArray()]);
try {
$files_model->save();
} catch (ErrorException $e) {
CustomVarDamp::dump($e->getMessage());
}
// получим id только что записанной записи - его запишем в название файла
$model->record_id = $files_model->find()
->where(['importer_id' => $files_model->importer_id])
->orderBy(['id' => SORT_DESC])
->one()
->id;
|
500b481a
Administrator
JSON
|
105
|
|
642796c8
Mihail
merge with server
|
106
|
$file_name = $model->record_id . '.' . $model->file->extension;
|
500b481a
Administrator
JSON
|
107
|
|
642796c8
Mihail
merge with server
|
108
109
110
111
112
|
if ($model->mode) {
$model->file_path = Yii::getAlias('@auto_upload') . '/' . $file_name;
} else {
$model->file_path = Yii::getAlias('@manual_upload') . '/' . $file_name;
}
|
500b481a
Administrator
JSON
|
113
|
|
642796c8
Mihail
merge with server
|
114
|
$model->file->saveAs($model->file_path);
|
500b481a
Administrator
JSON
|
115
|
|
642796c8
Mihail
merge with server
|
116
117
118
119
120
|
// для авто загрузки, обработка завершена
if ($model->mode) {
$model->success = true;
return $this->render('index', ['model' => $model]);
}
|
500b481a
Administrator
JSON
|
121
|
|
642796c8
Mihail
merge with server
|
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
|
// === ручная загрузка ===========
//запускаем парсинг
$data = $model->readFile();
// сохраняем в кеш отпарсенные даные
Yii::$app->getCache()->set('parser_data', json_encode($data));
// сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных
Yii::$app->getCache()->set('parser_configuration', serialize($model));
} else {
// не прошла валидация форма загрузки файлов
//@todo - отправка на страницу ошибок
$errors_arr = $model->getErrors();
foreach ($errors_arr as $error) {
CustomVarDamp::dump(array_values($error));
}
die;
}
// листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные
} else if (Yii::$app->getCache()->get('parser_data')) {
$data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
|
500b481a
Administrator
JSON
|
144
|
|
3cf42f5c
Mihail
init commit - bas...
|
145
146
|
}
|
474f35bf
Mihail
add DynamicFormHe...
|
147
148
149
150
151
152
153
|
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
|
642796c8
Mihail
merge with server
|
154
155
|
//формируем заголовок для пользователя, где он сможет выбрать соответсвие полей (выпадающий список)
$header_model = DynamicFormHelper::CreateDynamicModel(count($data[0]));
|
474f35bf
Mihail
add DynamicFormHe...
|
156
|
|
474f35bf
Mihail
add DynamicFormHe...
|
157
158
159
|
return $this->render('results',
['model' => $data,
'header_model' => $header_model,
|
642796c8
Mihail
merge with server
|
160
161
|
// список колонок для выбора
'basic_column' => Yii::$app->multiparser->getConfiguration('csv', 'basic_column'),
|
474f35bf
Mihail
add DynamicFormHe...
|
162
|
'dataProvider' => $provider]);
|
3cf42f5c
Mihail
init commit - bas...
|
163
|
}
|
474f35bf
Mihail
add DynamicFormHe...
|
164
|
|
642796c8
Mihail
merge with server
|
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
|
public function actionWrite()
{
//получим колонки которые выбрал пользователь
$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'))]);
}
// провалидируем выбранные колонки
if ($model->validate()) {
// валидация успешна у нас есть соответсвие колонок, преобразуем в массив данное соответсвие для дальнейшей работы
$arr = $model->toArray();
// получим данные из кеша
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('Ошибка кеша');
}
// соотнесем отпарсенные данные с соответсивем полученным от пользователя
// для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию
$data = \Yii::$app->multiparser->convertToAssocArray($data, $arr, 'attr_');
// 1. запишем дату старта в таблицу файлов поставщика (ImportersFiles)
// id загруженного файла получим из конфигурации
$files_model = ImporterFiles::findOne( $configuration->record_id );
//$files_model->load(['ImporterFiles' => $configuration->toArray()]);
$update_date = date('Y-m-d H:i:s');
$files_model->time_start = $update_date;
// запишем дату начала загрузки
if (!$files_model->save()) {
CustomVarDamp::dumpAndDie($files_model->getErrors());
}
// 2. запишем полученные данные в таблицу товаров (Details)
$details_model = new Details();
// проверим все ли обязательные колонки были указаны пользователем
$details_model->load(['Details' => $data[0]]);
if ($details_model->validate()) {
// дополним данные значением импортера и даты обновления цены
$data = \Yii::$app->multiparser->addColumns($data, ['IMPORT_ID' => $configuration->importer_id, 'timestamp' => $update_date]);
try {
//@todo add transaction
// попытаемся вставить данные в БД с апдейтом по ключам
$details_model->ManualInsert($data);
// 3. зафиксируем дату конца загрузки в файлах поставщика
$files_model->time_end = date('Y-m-d H:i:s');
// CustomVarDamp::dumpAndDie($files_model);
if (!$files_model->save()) {
CustomVarDamp::dumpAndDie($files_model->getErrors());
}
// 4. зафиксируем дату загрузки в таблице поставщиков
$imp_model = Importer::findOne($configuration['importer_id']);
$imp_model->price_date_update = $update_date;
if (!$imp_model->save()) {
CustomVarDamp::dumpAndDie($imp_model->getErrors());
}
$configuration['success'] = true;
// все прошло успешно - очищаем кеш
Yii::$app->getCache()->delete('parser_data');
Yii::$app->getCache()->delete('parser_configuration');
unlink($configuration['file_path']);
return $this->render('index', ['model' => $configuration]);
} 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...
|
258
|
|
474f35bf
Mihail
add DynamicFormHe...
|
259
260
|
}
|
642796c8
Mihail
merge with server
|
261
262
263
|
public function actionAutoUpload()
{
$query = Importer::find()->where(['active' => true])->orderBy(['price_date_update' => SORT_DESC]);
|
3c5edb9b
Mihail
edit createAssocA...
|
264
|
|
642796c8
Mihail
merge with server
|
265
266
267
268
269
270
271
272
273
|
$provider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('check_price',
[
'dataProvider' => $provider]);
|
474f35bf
Mihail
add DynamicFormHe...
|
274
275
|
}
|
642796c8
Mihail
merge with server
|
276
277
278
279
280
281
282
283
|
public function actionServerFiles ()
{
$arr_id = [];
// получим список файлов которые ожидают к загрузке
foreach (glob(Yii::getAlias('@auto_upload') . '/*') as $server_file) {
$file_id = basename($server_file,".csv");
$arr_id[] = (int) $file_id;
}
|
474f35bf
Mihail
add DynamicFormHe...
|
284
|
|
642796c8
Mihail
merge with server
|
285
|
$query = ImporterFiles::find()->where(['in', 'id', $arr_id])->orderBy(['upload_time' => SORT_DESC]);
|
3cf42f5c
Mihail
init commit - bas...
|
286
|
|
642796c8
Mihail
merge with server
|
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
|
$provider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('server-files',
[
'dataProvider' => $provider]);
}
public function actionDelete ($id)
{
if(Yii::$app->request->isAjax){
CustomVarDamp::dumpAndDie(1);
}
$files_model = new ImporterFiles();
try {
$files_model->delete($id);
unlink(Yii::getAlias('@auto_upload') . '/' . $id . '.csv' );
} catch (ErrorException $e) {
|
3cf42f5c
Mihail
init commit - bas...
|
311
|
|
642796c8
Mihail
merge with server
|
312
313
314
315
316
317
|
CustomVarDamp::dump($e->getMessage());
}
$this->redirect('server-files');
}
|
3cf42f5c
Mihail
init commit - bas...
|
318
|
}
|