Blame view

common/components/PriceWriter.php 3.65 KB
2edfb901   Mihail   add PriceWriter a...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  <?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 {
      public $mode;
      public $configuration;
      public $data;
2edfb901   Mihail   add PriceWriter a...
21
22
23
24
25
  
      public function writeDataToDB ()
      {
          // 1. запишем дату старта в таблицу файлов поставщика (ImportersFiles)
          // id  загруженного файла получим из конфигурации
93e39994   Mihail   fixed parser and ...
26
          $files_model = ImportersFiles::findOne( $this->configuration['record_id'] );
2edfb901   Mihail   add PriceWriter a...
27
  
2edfb901   Mihail   add PriceWriter a...
28
29
30
31
          $update_date = date('Y-m-d H:i:s');
          $files_model->time_start = $update_date;
          // запишем дату начала загрузки
          if (!$files_model->save()) {
34d480b7   Mihail   temp commit - wor...
32
              throw new \ErrorException(implode( ', ', $files_model->getErrors()));
2edfb901   Mihail   add PriceWriter a...
33
34
          }
  
2edfb901   Mihail   add PriceWriter a...
35
36
          // 2. запишем полученные данные в таблицу товаров (Details)
          $details_model = new Details();
34d480b7   Mihail   temp commit - wor...
37
          // только для ручной загрузки, в авто режиме все делает конвертер при первом же проходе (в процессе парсинга)
df629228   Mihail   console csv parsing
38
          if ($this->mode == 0) {
34d480b7   Mihail   temp commit - wor...
39
40
41
42
43
44
45
46
47
48
49
              // преобразуем числовые значения
              foreach ($this->data as &$row) {
                  $row['PRICE'] = \Yii::$app->multiparser->convertToFloat($row['PRICE']);
                  $row['BOX'] = \Yii::$app->multiparser->convertToInteger($row['BOX']);
                  // присвоим полный артикул
                  $row['FULL_ARTICLE'] = $row['ARTICLE'];
                  if(isset($row['ADD_BOX']))
                      $row['ADD_BOX'] = \Yii::$app->multiparser->convertToInteger($row['ADD_BOX']);
  
                  // проверим все ли обязательные колонки были указаны пользователем
                  $details_model->load(['Details' => $row]);
34d480b7   Mihail   temp commit - wor...
50
51
52
53
54
                  if (!$details_model->validate())
                      //@todo предоставить более детальную информацию об ошибке
                      throw new \ErrorException('Ошибка записи товаров');
  
              }
2edfb901   Mihail   add PriceWriter a...
55
          }
34d480b7   Mihail   temp commit - wor...
56
  
2edfb901   Mihail   add PriceWriter a...
57
              // дополним данные значением импортера и даты обновления цены
93e39994   Mihail   fixed parser and ...
58
              $this->data = \Yii::$app->multiparser->addColumns($this->data, ['IMPORT_ID' => $this->configuration['importer_id'], 'timestamp' => $update_date]);
2edfb901   Mihail   add PriceWriter a...
59
60
61
62
63
64
65
66
  
              try {
                  //@todo add transaction
                  // попытаемся вставить данные в БД с апдейтом по ключам
                  $details_model->ManualInsert($this->data);
  
                  // 3. зафиксируем дату конца загрузки в файлах поставщика
  
2edfb901   Mihail   add PriceWriter a...
67
68
                  if (!$files_model->save()) {
                      throw new \ErrorException(implode( ', ', $files_model->getErrors()));
2edfb901   Mihail   add PriceWriter a...
69
70
71
72
73
74
75
                  }
  
                  // 4. зафиксируем дату загрузки в таблице поставщиков
                  $imp_model = Importers::findOne($this->configuration['importer_id']);
                  $imp_model->price_date_update = $update_date;
  
                  if (!$imp_model->save()) {
2edfb901   Mihail   add PriceWriter a...
76
                      throw new \ErrorException(implode( ', ', $imp_model->getErrors()));
2edfb901   Mihail   add PriceWriter a...
77
                  }
2edfb901   Mihail   add PriceWriter a...
78
              } catch (ErrorException  $e) {
2edfb901   Mihail   add PriceWriter a...
79
80
                  throw new \ErrorException( $e->getMessage() );
              }
34d480b7   Mihail   temp commit - wor...
81
  
2edfb901   Mihail   add PriceWriter a...
82
83
84
85
  
  
          return true;
      }
df629228   Mihail   console csv parsing
86
87
  
  
2edfb901   Mihail   add PriceWriter a...
88
  }