293f57f9
Mihail
add upload rg gro...
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?php
/**
* Created by PhpStorm.
* User: Tsurkanov
* Date: 27.10.2015
* Time: 15:22
*/
namespace backend\controllers;
use backend\components\base\BaseController;
use backend\models\UploadFileRgForm;
use common\components\CustomVarDamp;
|
8e7f5c9b
Mihail
add MailAttachmen...
|
14
|
use common\components\parsers\MailAttachmentsSaver;
|
293f57f9
Mihail
add upload rg gro...
|
15
16
|
use common\models\Margins;
use common\models\MarginsGroups;
|
f5b3baf1
Administrator
access in admin
|
17
|
use yii\filters\VerbFilter;
|
293f57f9
Mihail
add upload rg gro...
|
18
19
20
21
22
23
24
|
use yii\filters\AccessControl;
use Yii;
use yii\web\UploadedFile;
use yii\data\ArrayDataProvider;
use yii\multiparser\DynamicFormHelper;
use common\components\CustomArrayHelper;
|
8b8083ef
Mihail
add manual insert...
|
25
26
|
class RgGrupController extends BaseController
{
|
293f57f9
Mihail
add upload rg gro...
|
27
28
29
30
31
32
33
34
35
36
37
38
|
public $layout = "/column";
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
|
f5b3baf1
Administrator
access in admin
|
39
40
41
42
|
'actions' => ['login', 'error', 'download-photo','delete-image' ],
'allow' => true,
],
[
|
0123b1a3
Administrator
access in admin
|
43
|
'actions' => ['logout', 'index','create','update','view','delete',],
|
293f57f9
Mihail
add upload rg gro...
|
44
45
46
47
48
|
'allow' => true,
'roles' => ['@'],
],
],
],
|
f5b3baf1
Administrator
access in admin
|
49
50
51
52
53
54
|
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
|
293f57f9
Mihail
add upload rg gro...
|
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
|
];
}
public function actionIndex()
{
$model = new UploadFileRgForm();
return $this->render('index', ['model' => $model]);
}
public function actionResults()
{
$model = new UploadFileRgForm();
$data = [];
if ($model->load(Yii::$app->request->post())) {
$model->file = UploadedFile::getInstance($model, 'file');
// первый проход - валидируем, сохраняем файл, ложим в кеш отпарсенные данные и параметры модели (потом при записи в базу данных они пригодятся)
if ($model->validate()) {
$model->file_path = Yii::getAlias('@manual_upload') . '/' . $model->file->name;
$model->file->saveAs($model->file_path);
//запускаем парсинг
$data = $model->readFile();
// сохраняем в кеш отпарсенные даные
|
a80ff469
Mihail
add expiration ti...
|
81
|
Yii::$app->getCache()->set('parser_data', json_encode($data), 1800);
|
293f57f9
Mihail
add upload rg gro...
|
82
|
// сохраняем в кеш модель - в ней настройки для дальнейшей обработки данных
|
a80ff469
Mihail
add expiration ti...
|
83
|
Yii::$app->getCache()->set('parser_configuration', serialize($model), 1800);
|
293f57f9
Mihail
add upload rg gro...
|
84
85
86
87
88
89
|
} else {
// не прошла валидация форма загрузки файлов
$errors_str = '';
foreach ($model->getErrors() as $error) {
|
8b8083ef
Mihail
add manual insert...
|
90
|
$errors_str .= implode(array_values($error));
|
293f57f9
Mihail
add upload rg gro...
|
91
|
}
|
8b8083ef
Mihail
add manual insert...
|
92
|
throw new \ErrorException($errors_str);
|
293f57f9
Mihail
add upload rg gro...
|
93
94
95
96
97
98
99
100
101
102
103
104
105
|
}
// листаем пагинатором, или повторно вызываем - считываем из кеша отпрасенные данные
} 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,
],
]);
|
293f57f9
Mihail
add upload rg gro...
|
106
|
// создадим модель на столько реквизитов сколько колонок в отпарсенном файле
|
8b8083ef
Mihail
add manual insert...
|
107
|
$last_index = end(array_flip($data[0]));
|
293f57f9
Mihail
add upload rg gro...
|
108
|
$header_counts = $last_index + 1;
|
8b8083ef
Mihail
add manual insert...
|
109
|
$header_model = DynamicFormHelper::CreateDynamicModel($header_counts);
|
293f57f9
Mihail
add upload rg gro...
|
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
|
// соберем массив данных из которых будет пользователь выбирать значения в конструкторе (выпадающий список)
$header_array = Margins::getHeader();
return $this->render('results',
['model' => $data,
'header_model' => $header_model,
// список колонок для выбора
'basic_column' => $header_array,
'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(Margins::getHeader())]);
}
// провалидируем выбранные колонки
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('Ошибка кеша');
}
|
8b8083ef
Mihail
add manual insert...
|
147
148
|
array_walk($arr, function (&$val) {
$val = '!' . $val;
|
293f57f9
Mihail
add upload rg gro...
|
149
150
151
152
|
});
// соотнесем отпарсенные данные с соответсивем полученным от пользователя
// для этого преобразуем массив отпарсенных данных - назначим ключи согласно соответствию
|
8b8083ef
Mihail
add manual insert...
|
153
|
$data = CustomArrayHelper::createAssocArray($data, $arr, 'attr_');
|
293f57f9
Mihail
add upload rg gro...
|
154
155
156
157
|
// в первой строке у нас заголовки - уберем
unset($data[0]);
// подготовим данные для записи в таблицу w_margins_groups
|
8b8083ef
Mihail
add manual insert...
|
158
|
$arr_values = [];
|
293f57f9
Mihail
add upload rg gro...
|
159
160
161
162
163
164
165
166
167
168
169
170
171
|
$group = '';
$importer_id = $configuration['importer_id'];
foreach ($data as $row_data) {
if (isset($row_data['!group'])) {
$group = $row_data['!group'];
unset($row_data['!group']);
}
if (isset($row_data['!_null'])) {
unset($row_data['!_null']);
}
foreach ($row_data as $key => $value) {
|
8b8083ef
Mihail
add manual insert...
|
172
173
174
175
176
|
if ($group)
$row['group'] = trim($group);
$row['importer_id'] = trim($importer_id);
$row['margin_id'] = ltrim($key, '!');
|
49bb0055
Mihail
add round for koe...
|
177
178
|
$row['koef'] = \Yii::$app->converter->convertTo('float', $value, ['precision' => 6]);
|
8b8083ef
Mihail
add manual insert...
|
179
180
181
|
$arr_values[] = $row;
|
293f57f9
Mihail
add upload rg gro...
|
182
|
}
|
293f57f9
Mihail
add upload rg gro...
|
183
|
|
8b8083ef
Mihail
add manual insert...
|
184
185
186
|
}
// сохраним подготовленные данные
MarginsGroups::ManualInsertWithUpdate( $arr_values, [ 'group','importer_id','margin_id' ] );
|
293f57f9
Mihail
add upload rg gro...
|
187
|
|
293f57f9
Mihail
add upload rg gro...
|
188
|
|
8b8083ef
Mihail
add manual insert...
|
189
190
191
192
|
Yii::$app->session->setFlash('success', "Файл {$configuration['file']} успешно загружен");
// все прошло успешно - очищаем кеш
Yii::$app->getCache()->delete('parser_data');
Yii::$app->getCache()->delete('parser_configuration');
|
293f57f9
Mihail
add upload rg gro...
|
193
|
|
8b8083ef
Mihail
add manual insert...
|
194
195
|
if (file_exists($configuration['file_path']))
unlink($configuration['file_path']);
|
293f57f9
Mihail
add upload rg gro...
|
196
|
|
8b8083ef
Mihail
add manual insert...
|
197
|
return $this->render('index', ['model' => $configuration]);
|
293f57f9
Mihail
add upload rg gro...
|
198
|
|
293f57f9
Mihail
add upload rg gro...
|
199
200
201
|
}
}
|
8e7f5c9b
Mihail
add MailAttachmen...
|
202
|
|
1fae1653
Mihail
fixed errors with...
|
203
204
205
206
207
208
|
// public function actionMail()
// {
// $mail_saver = new MailAttachmentsSaver('{imap.gmail.com:993/imap/ssl/novalidate-cert}', 'tsurkanovm@gmail.com', 'Wtvr@2000');
// //$mail_saver = new MailAttachmentsSaver('{imap.gmail.com:993/imap/ssl/novalidate-cert}', 'price@italauto.com.ua', '67853562');
// $mail_saver->saveAttachmentsTo();
// }
|
8e7f5c9b
Mihail
add MailAttachmen...
|
209
210
|
}
|