Blame view

common/components/PriceWriter.php 4.25 KB
f0dbd829   Mihail   add PriceWriter a...
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
  <?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;
     // public $errors = [];
  
      public function writeDataToDB ()
      {
          // 1. запишем дату старта в таблицу файлов поставщика (ImportersFiles)
          // id  загруженного файла получим из конфигурации
1fe29bbe   Mihail   fixed parser and ...
27
          $files_model = ImportersFiles::findOne( $this->configuration['record_id'] );
f0dbd829   Mihail   add PriceWriter a...
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
  
          //$files_model->load(['ImportersFiles' => $this->configuration->toArray()]);
          $update_date = date('Y-m-d H:i:s');
          $files_model->time_start = $update_date;
          // запишем дату начала загрузки
          if (!$files_model->save()) {
              $this->errors[] = implode( ', ', $files_model->getErrors());
              return false;
              //CustomVarDamp::dumpAndDie($files_model->implode ( ', ', getErrors())());
          }
  
  
          // 2. запишем полученные данные в таблицу товаров (Details)
          $details_model = new Details();
          // преобразуем числовые значения
          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]);
  
              if (!$details_model->validate())
                  break;
          }
  
          if ($details_model->hasErrors()) {
              //@todo предоставить более детальную информацию об ошибке
              throw new \ErrorException('Ошибка записи товаров');
          }
              else{
              // дополним данные значением импортера и даты обновления цены
1fe29bbe   Mihail   fixed parser and ...
64
              $this->data = \Yii::$app->multiparser->addColumns($this->data, ['IMPORT_ID' => $this->configuration['importer_id'], 'timestamp' => $update_date]);
f0dbd829   Mihail   add PriceWriter a...
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
  
              try {
                  //@todo add transaction
                  // попытаемся вставить данные в БД с апдейтом по ключам
                  $details_model->ManualInsert($this->data);
  
                  // 3. зафиксируем дату конца загрузки в файлах поставщика
  
                  $files_model->time_end = date('Y-m-d H:i:s');
                  // CustomVarDamp::dumpAndDie($files_model);
                  if (!$files_model->save()) {
                      throw new \ErrorException(implode( ', ', $files_model->getErrors()));
  //                    $this->errors[] = $files_model->implode ( ', ', getErrors());
  //                    return false;
                     // CustomVarDamp::dumpAndDie($files_model->implode ( ', ', getErrors())());
                  }
  
                  // 4. зафиксируем дату загрузки в таблице поставщиков
                  $imp_model = Importers::findOne($this->configuration['importer_id']);
                  $imp_model->price_date_update = $update_date;
  
                  if (!$imp_model->save()) {
  //                    $this->errors[] = $imp_model->implode ( ', ', getErrors())();
  //                    return false;
                      throw new \ErrorException(implode( ', ', $imp_model->getErrors()));
                     // CustomVarDamp::dumpAndDie($imp_model->implode ( ', ', getErrors())());
                  }
  
  
              } catch (ErrorException  $e) {
                  //CustomVarDamp::dump($e->getMessage());
                  throw new \ErrorException( $e->getMessage() );
              }
          }
  
  
          return true;
      }
  }