ParserController.php
11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
<?php
namespace backend\controllers;
use Yii;
use yii\data\ActiveDataProvider;
use yii\filters\AccessControl;
use backend\components\base\BaseController;
use yii\filters\VerbFilter;
use backend\models\UploadFileParsingForm;
use yii\web\UploadedFile;
use yii\data\ArrayDataProvider;
use yii\multiparser\DynamicFormHelper;
use backend\models\ImportersFiles;
use backend\models\Importers;
use yii\base\ErrorException;
use common\components\PriceWriter;
use common\components\CustomVarDamp;
use common\components\CustomArrayHelper;
/**
* Parser controller
*/
class ParserController extends BaseController
{
public $layout = "/column";
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@'],
],
],
],
// 'verbs' => [
// 'class' => VerbFilter::className(),
// 'actions' => [
// 'logout' => ['post'],
// ],
// ],
];
}
public function actionIndex($mode = 0)
{
// $path = 'common\components\parsers\CustomConverter';
// CustomVarDamp::dumpAndDie(new $path());
$model = new UploadFileParsingForm();
// установим режим, 0 - ручная загрузка, 1 - автозагрузка
$model->mode = $mode;
return $this->render('index', ['model' => $model]);
}
public function actionError()
{
$exception = Yii::$app->errorHandler->exception;
if ($exception !== null) {
return $this->render('error', ['message' => $exception->getMessage()]);
}
}
public function actionResults($mode = 0)
{
$model = new UploadFileParsingForm(['mode' => $mode]);
$data = [];
if ($model->load(Yii::$app->request->post())) {
$model->file = UploadedFile::getInstance($model, 'file');
// первый проход - валидируем, сохраняем файл, ложим в кеш (для ручной загрузки) отпарсенные данные и параметры модели (потом при записи в базу данных они пригодятся)
if ($model->validate()) {
// запишем дату загрузки файла в таблицу файлов поставщика (ImportersFiles)
$files_model = new ImportersFiles();
// id поставщика получим из конфигурации
$files_model->load(['ImportersFiles' => $model->toArray()]);
try {
$files_model->save();
} catch (ErrorException $e) {
throw $e;
}
// получим id только что записанной записи - его запишем в название файла
$model->record_id = $files_model->find()
->where(['importer_id' => $files_model->importer_id])
->orderBy(['id' => SORT_DESC])
->one()
->id;
$file_name = $model->record_id . '.' . $model->file->extension;
if ($model->mode) {
$model->file_path = Yii::getAlias('@temp_upload') . '/' . $file_name;
} else {
$model->file_path = Yii::getAlias('@manual_upload') . '/' . $file_name;
}
$model->file->saveAs($model->file_path);
// для авто загрузки, обработка завершена
if ($model->mode) {
$model->success = true;
return $this->render('index', ['model' => $model]);
}
// === ручная загрузка ===========
//запускаем парсинг
// доп. опции для парсера
$options = ['converter_conf' =>
['importer_id' => $files_model->importer_id]
];
if( ! $model->action ) // обработка с кастомным разделителем
$options['$delimiter'] = $model->delimiter;
$data = $model->readFile( $options );
// сохраняем в кеш отпарсенные даные
Yii::$app->getCache()->set('parser_data', json_encode($data));
// сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных
Yii::$app->getCache()->set('parser_configuration', serialize($model));
} else {
// не прошла валидация форма загрузки файлов
$errors_str = '';
foreach ($model->getErrors() as $error) {
$errors_str .= implode( array_values($error) );
}
throw new ErrorException( $errors_str );
}
// листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные
} else if (Yii::$app->getCache()->get('parser_data')) {
$data = json_decode(Yii::$app->getCache()->get('parser_data'), true);
}
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
]);
$last_index = end( array_flip( $data[0] ) );
$header_counts = $last_index + 1;
//формируем заголовок для пользователя, где он сможет выбрать соответсвие полей (выпадающий список)
$header_model = DynamicFormHelper::CreateDynamicModel( $header_counts );
return $this->render('results',
['model' => $data,
'header_model' => $header_model,
// список колонок для выбора
'basic_column' => Yii::$app->multiparser->getConfiguration('csv', 'basic_column'),
'dataProvider' => $provider]);
}
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 {
throw new \ErrorException('Ошибка кеша');
}
// соотнесем отпарсенные данные с соответсивем полученным от пользователя
// для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию
$data = CustomArrayHelper::createAssocArray( $data, $arr , 'attr_' );
// запустим специальный класс который запишет данные в таблицы связанные с прайсами
$writer = new PriceWriter();
$writer->configuration = $configuration;
$writer->data = $data;
$writer->mode = 0; //web-режим
if ( $writer->writeDataToDB() ) {
$configuration['success'] = true;
// все прошло успешно - очищаем кеш
Yii::$app->getCache()->delete('parser_data');
Yii::$app->getCache()->delete('parser_configuration');
if( file_exists($configuration['file_path']) )
unlink($configuration['file_path']);
return $this->render('index', ['model' => $configuration]);
};
}
}
public function actionAutoUpload()
{
$query = Importers::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]);
}
public function actionServerFiles ()
{
$arr_id_files = [];
// получим список файлов которые ожидают к загрузке
foreach ( glob(Yii::getAlias('@temp_upload') . '/*.csv' ) as $server_file ) {
$file_id = basename($server_file,".csv");
$arr_id_files[] = (int) $file_id;
}
$query = ImportersFiles::find()->where(['in', 'id', $arr_id_files])->orderBy(['upload_time' => SORT_DESC]);
$provider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('server-files',
[
'dataProvider' => $provider]);
}
public function actionDelete ()
{
if ( Yii::$app->request->isAjax ) {
$files_model = new ImportersFiles();
if ( isset(Yii::$app->request->post()['id'] )) {
$id = Yii::$app->request->post()['id'];
try {
$files_model->delete($id);
unlink(Yii::getAlias('@temp_upload') . '/' . $id . '.csv' );
// сообщим скрипту что все ОК
echo 1;
} catch (ErrorException $e) {
throw $e;
}
}
}
}
public function actionLaunchCroneUploads ()
{
foreach (glob(Yii::getAlias('@temp_upload') . '/*.csv') as $server_file) {
$file_name = basename($server_file,".csv");
copy( $server_file, Yii::getAlias('@auto_upload') . '/' . $file_name . '.csv' );
}
Yii::$app->session->setFlash( 'server-files', 'Файл успешно загружен' );
$this->redirect('server-files');
// $csv = new \console\controllers\ParserController( 'parse-csv', $this->module );
// $csv->actionParseCsv();
}
}