Blame view

common/components/PriceWriter.php 8.85 KB
f0dbd829   Mihail   add PriceWriter a...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  <?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;
b6247a0e   Mihail   rewrite parser wr...
16
  use common\components\ModelArrayValidator;
f0dbd829   Mihail   add PriceWriter a...
17
  
40cac1b6   Mihail   add delete func i...
18
19
20
21
22
23
24
25
26
27
28
  /**
   * Class PriceWriter
   * @package common\components
   * записывает в БД отпарсенные данные
   * запись происходит в несколько таблиц
   */
  class PriceWriter
  {
      /**
       * @var - int - 0 - интерактивный режим, 1 - консольный
       */
edfa67b1   Mihail   add delete price ...
29
      protected $mode;
40cac1b6   Mihail   add delete func i...
30
31
32
33
  
      /**
       * @var - массив с настройками записи
       */
edfa67b1   Mihail   add delete price ...
34
      protected $configuration;
40cac1b6   Mihail   add delete func i...
35
36
37
38
  
      /**
       * @var - массив с данными которые нужно записать
       */
edfa67b1   Mihail   add delete price ...
39
      protected $data;
f0dbd829   Mihail   add PriceWriter a...
40
  
b6247a0e   Mihail   rewrite parser wr...
41
42
43
44
45
46
47
48
49
50
51
      /**
       * @var - сообщение валидатора об ошибках
       */
      protected $validated_msg;
      /**
       * @var - тип сообщения валидатора - success, warning
       */
      protected $validated_type_msg;
  
  
  
40cac1b6   Mihail   add delete func i...
52
53
54
55
56
      function __construct()
      {
          set_time_limit(300);
      }
  
edfa67b1   Mihail   add delete price ...
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
      /**
       * @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;
      }
  
b6247a0e   Mihail   rewrite parser wr...
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
      /**
       * @return mixed
       */
      public function getValidatedMsg()
      {
          return $this->validated_msg;
      }
  
      /**
       * @return mixed
       */
      public function getValidatedTypeMsg()
      {
          return $this->validated_type_msg;
      }
edfa67b1   Mihail   add delete price ...
96
97
98
  
  
      public function writePriceToDB()
f0dbd829   Mihail   add PriceWriter a...
99
100
101
      {
          // 1. запишем дату старта в таблицу файлов поставщика (ImportersFiles)
          // id  загруженного файла получим из конфигурации
40cac1b6   Mihail   add delete func i...
102
          $files_model = ImportersFiles::findOne($this->configuration['record_id']);
f0dbd829   Mihail   add PriceWriter a...
103
  
f0dbd829   Mihail   add PriceWriter a...
104
105
106
107
          $update_date = date('Y-m-d H:i:s');
          $files_model->time_start = $update_date;
          // запишем дату начала загрузки
          if (!$files_model->save()) {
40cac1b6   Mihail   add delete func i...
108
              throw new \ErrorException(implode(', ', $files_model->getErrors()));
f0dbd829   Mihail   add PriceWriter a...
109
110
          }
  
b6247a0e   Mihail   rewrite parser wr...
111
          // 2. конвертируем данные
ef41533d   Mihail   temp commit - wor...
112
          // только для ручной загрузки, в авто режиме все делает конвертер при первом же проходе (в процессе парсинга)
b6247a0e   Mihail   rewrite parser wr...
113
114
115
          if ( $this->mode == 0 ) {
              // преобразуем значения перед записью в БД
              $this->convertDataByConfiguration();
7776ca75   Mihail   add form, model a...
116
  
b6247a0e   Mihail   rewrite parser wr...
117
118
119
          }
          //3. провалидируем полученные данные моделью - Details
          $details_model = $this->validateByDetailsModel();
ef41533d   Mihail   temp commit - wor...
120
  
b6247a0e   Mihail   rewrite parser wr...
121
122
          //4. дополним данные значением импортера и даты обновления цены
          $this->data = CustomArrayHelper::addColumns($this->data, ['IMPORT_ID' => $this->configuration['importer_id'], 'timestamp' => $update_date]);
ef41533d   Mihail   temp commit - wor...
123
  
b6247a0e   Mihail   rewrite parser wr...
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
          //5. запишем данные в связанные таблицы
          $this->writePriceInTransaction($details_model, $files_model, $update_date);
  
          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('Не указана дата загрузки прайса для удаления');
          }
  
          $this->deletePriceInTransaction( $importer_id, $update_date );
  
          return true;
      }
  
      /**
       * ковертирует отпарсенные данные конвертером по конфигурации
       */
      protected function convertDataByConfiguration ()
      {
          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']);
                  }
ef41533d   Mihail   temp commit - wor...
175
              }
b6247a0e   Mihail   rewrite parser wr...
176
177
178
  
              if (isset($row['ADD_BOX']))
                  $row['ADD_BOX'] = \Yii::$app->converter->convertTo('integer', $row['ADD_BOX']);
f0dbd829   Mihail   add PriceWriter a...
179
          }
b6247a0e   Mihail   rewrite parser wr...
180
      }
ef41533d   Mihail   temp commit - wor...
181
  
b6247a0e   Mihail   rewrite parser wr...
182
      protected function  writePriceInTransaction($details_model, $files_model, $update_date){
edfa67b1   Mihail   add delete price ...
183
          $transaction = \Yii::$app->db->beginTransaction();
40cac1b6   Mihail   add delete func i...
184
          try {
f0dbd829   Mihail   add PriceWriter a...
185
  
edfa67b1   Mihail   add delete price ...
186
              if (isset($this->configuration['delete_price']) && (int)$this->configuration['delete_price']) {
40cac1b6   Mihail   add delete func i...
187
188
                  $details_model->delete_price = true;
              }
edfa67b1   Mihail   add delete price ...
189
  
40cac1b6   Mihail   add delete func i...
190
              //2. попытаемся вставить данные в БД с апдейтом по ключам
edfa67b1   Mihail   add delete price ...
191
              $details_model->manualInsert($this->data, $this->configuration['importer_id']);
f0dbd829   Mihail   add PriceWriter a...
192
  
40cac1b6   Mihail   add delete func i...
193
194
              // 3. зафиксируем дату конца загрузки в файлах поставщика
              if (!$files_model->save()) {
61795805   Mihail   fixed testing iss...
195
                  $transaction->rollBack();
40cac1b6   Mihail   add delete func i...
196
197
                  throw new \ErrorException(implode(', ', $files_model->getErrors()));
              }
f0dbd829   Mihail   add PriceWriter a...
198
  
40cac1b6   Mihail   add delete func i...
199
200
201
              // 4. зафиксируем дату загрузки в таблице поставщиков
              $imp_model = Importers::findOne($this->configuration['importer_id']);
              $imp_model->price_date_update = $update_date;
f0dbd829   Mihail   add PriceWriter a...
202
  
40cac1b6   Mihail   add delete func i...
203
              if (!$imp_model->save()) {
61795805   Mihail   fixed testing iss...
204
                  $transaction->rollBack();
6ccb6e69   Mihail   add delete price ...
205
                  $imp_model->throwStringErrorException();
f0dbd829   Mihail   add PriceWriter a...
206
              }
61795805   Mihail   fixed testing iss...
207
208
              $transaction->commit();
  
40cac1b6   Mihail   add delete func i...
209
          } catch (ErrorException  $e) {
61795805   Mihail   fixed testing iss...
210
              $transaction->rollBack();
40cac1b6   Mihail   add delete func i...
211
212
              throw new \ErrorException($e->getMessage());
          }
f0dbd829   Mihail   add PriceWriter a...
213
  
f0dbd829   Mihail   add PriceWriter a...
214
      }
ea4ecf3d   Mihail   console csv parsing
215
  
b6247a0e   Mihail   rewrite parser wr...
216
      protected function  deletePriceInTransaction( $importer_id, $update_date ){
edfa67b1   Mihail   add delete price ...
217
218
219
220
          $transaction = \Yii::$app->db->beginTransaction();
          try {
              // 1. удалим из таблицы файлов поставщика (ImportersFiles)
  
6ccb6e69   Mihail   add delete price ...
221
              $rows = ImportersFiles::deleteAll(['importer_id' => $importer_id, 'time_start' => $update_date]);
edfa67b1   Mihail   add delete price ...
222
223
              if ($rows != 1) {
                  $transaction->rollBack();
6ccb6e69   Mihail   add delete price ...
224
                  throw new \ErrorException('Ошибка удаления из таблицы файлов поставщиков. Указанный прайс не найден');
edfa67b1   Mihail   add delete price ...
225
226
              }
  
6ccb6e69   Mihail   add delete price ...
227
              $last_upload_time = ImportersFiles::find()->where(['importer_id' => $importer_id])->orderBy(['time_start' => SORT_DESC])->one()->time_start;
edfa67b1   Mihail   add delete price ...
228
  
b6247a0e   Mihail   rewrite parser wr...
229
230
              // 2. удалим прайс из таблицы товаров (Details)
              $details_model = new Details();
6ccb6e69   Mihail   add delete price ...
231
232
233
              $conditions = "import_id = {$importer_id} AND  timestamp ='$update_date'";
  
              $details_model->manualDelete( $conditions );
edfa67b1   Mihail   add delete price ...
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
  
              // 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());
          }
edfa67b1   Mihail   add delete price ...
249
      }
ea4ecf3d   Mihail   console csv parsing
250
  
b6247a0e   Mihail   rewrite parser wr...
251
252
253
254
255
256
257
258
259
260
261
262
263
      protected function validateByDetailsModel(){
  
          $details_model = new Details();
  
          $model_validator = new ModelArrayValidator( $details_model );
          $this->data = $model_validator->validate( $this->data );
          $this->validated_msg = $model_validator->getMassage();
          $this->validated_type_msg =  $model_validator->hasError() ?  'warning' : 'success';
  
          $model_validator->close();
  
          return $details_model;
      }
f0dbd829   Mihail   add PriceWriter a...
264
  }