PriceWriter.php
7.52 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
<?php
/**
* Created by PhpStorm.
* User: Cibermag
* Date: 30.09.2015
* Time: 9:34
*/
namespace common\components;
use yii\base\ErrorException;
use backend\models\ImportersFiles;
use backend\models\Importers;
use backend\models\Details;
/**
* Class PriceWriter
* @package common\components
* записывает в БД отпарсенные данные
* запись происходит в несколько таблиц
*/
class PriceWriter
{
/**
* @var - int - 0 - интерактивный режим, 1 - консольный
*/
protected $mode;
/**
* @var - массив с настройками записи
*/
protected $configuration;
/**
* @var - массив с данными которые нужно записать
*/
protected $data;
function __construct()
{
set_time_limit(300);
}
/**
* @param mixed $mode
*/
public function setMode($mode)
{
$this->mode = $mode;
}
/**
* @param mixed $configuration
*/
public function setConfiguration($configuration)
{
$this->configuration = $configuration;
}
/**
* @param mixed $data
*/
public function setData($data)
{
$this->data = $data;
}
public function writePriceToDB()
{
// 1. запишем дату старта в таблицу файлов поставщика (ImportersFiles)
// id загруженного файла получим из конфигурации
$files_model = ImportersFiles::findOne($this->configuration['record_id']);
$update_date = date('Y-m-d H:i:s');
$files_model->time_start = $update_date;
// запишем дату начала загрузки
if (!$files_model->save()) {
throw new \ErrorException(implode(', ', $files_model->getErrors()));
}
// 2. запишем полученные данные в таблицу товаров (Details)
$details_model = new Details();
// только для ручной загрузки, в авто режиме все делает конвертер при первом же проходе (в процессе парсинга)
if ($this->mode == 0) {
// преобразуем числовые значения
foreach ($this->data as &$row) {
if (isset($row['PRICE']))
$row['PRICE'] = \Yii::$app->converter->convertTo('float', $row['PRICE']);
if (isset($row['BOX']))
$row['BOX'] = \Yii::$app->converter->convertTo('integer', $row['BOX']);
// присвоим полный артикул
if (isset($row['ARTICLE'])) {
$row['FULL_ARTICLE'] = $row['ARTICLE'];
if ((int)$this->configuration['delete_prefix']) {
$row = \Yii::$app->converter->convertTo('Article', $row, ['importer_id' => $this->configuration['importer_id']]);
} else {
if (isset($row['ARTICLE']))
$row['ARTICLE'] = \Yii::$app->converter->convertTo('Article', $row['ARTICLE']);
}
}
if (isset($row['ADD_BOX']))
$row['ADD_BOX'] = \Yii::$app->converter->convertTo('integer', $row['ADD_BOX']);
// проверим все ли обязательные колонки были указаны пользователем
$details_model->load(['Details' => $row]);
if (!$details_model->validate())
$details_model->throwStringErrorException(key($this->data));
}
}
// дополним данные значением импортера и даты обновления цены
$this->data = CustomArrayHelper::addColumns($this->data, ['IMPORT_ID' => $this->configuration['importer_id'], 'timestamp' => $update_date]);
$transaction = \Yii::$app->db->beginTransaction();
try {
if (isset($this->configuration['delete_price']) && (int)$this->configuration['delete_price']) {
$details_model->delete_price = true;
}
//2. попытаемся вставить данные в БД с апдейтом по ключам
$details_model->manualInsert($this->data, $this->configuration['importer_id']);
// 3. зафиксируем дату конца загрузки в файлах поставщика
if (!$files_model->save()) {
$transaction->rollBack();
throw new \ErrorException(implode(', ', $files_model->getErrors()));
}
// 4. зафиксируем дату загрузки в таблице поставщиков
$imp_model = Importers::findOne($this->configuration['importer_id']);
$imp_model->price_date_update = $update_date;
if (!$imp_model->save()) {
$transaction->rollBack();
$imp_model->throwStringErrorException();
}
$transaction->commit();
} catch (ErrorException $e) {
$transaction->rollBack();
throw new \ErrorException($e->getMessage());
}
return true;
}
public function deletePriceFromDB()
{
$importer_id = '';
$update_date = '';
if (isset($this->configuration['importer_id']))
$importer_id = $this->configuration['importer_id'];
if (isset($this->configuration['update_date']))
$update_date = $this->configuration['update_date'];
if (!$importer_id) {
throw new \ErrorException('Не указан поставщик прайса для удаления');
} elseif (!$update_date) {
throw new \ErrorException('Не указана дата загрузки прайса для удаления');
}
$transaction = \Yii::$app->db->beginTransaction();
try {
// 1. удалим из таблицы файлов поставщика (ImportersFiles)
$rows = ImportersFiles::deleteAll(['importer_id' => $importer_id, 'time_start' => $update_date]);
if ($rows != 1) {
$transaction->rollBack();
throw new \ErrorException('Ошибка удаления из таблицы файлов поставщиков. Указанный прайс не найден');
}
$last_upload_time = ImportersFiles::find()->where(['importer_id' => $importer_id])->orderBy(['time_start' => SORT_DESC])->one()->time_start;
// 2. удалим прайс из таблицы товаров (Details)
$details_model = new Details();
$conditions = "import_id = {$importer_id} AND timestamp ='$update_date'";
$details_model->manualDelete( $conditions );
// 3. откатимся до старой даты загрузки в таблице поставщиков
$imp_model = Importers::findOne( $importer_id );
$imp_model->price_date_update = $last_upload_time;
if (!$imp_model->save()) {
$transaction->rollBack();
$imp_model->throwStringErrorException();
}
$transaction->commit();
} catch (ErrorException $e) {
$transaction->rollBack();
throw new \ErrorException($e->getMessage());
}
return true;
}
}