Commit 78684ed4d04ef4309b1780dc27ec5559c9e29520

Authored by Mihail
1 parent 14ab0a80

add multiply price funktional in Converter

backend/controllers/ParserController.php
... ... @@ -266,13 +266,15 @@ class ParserController extends BaseController
266 266 foreach (glob(Yii::getAlias('@temp_upload') . '/*.csv') as $server_file) {
267 267  
268 268 $file_name = basename($server_file,".csv");
269   - // rename( $server_file, Yii::getAlias('@auto_upload') . '/' . $file_name . '.csv');
270 269 copy( $server_file, Yii::getAlias('@auto_upload') . '/' . $file_name . '.csv' );
271 270  
272 271 }
  272 +
273 273 Yii::$app->session->setFlash( 'server-files', 'Файл успешно загружен' );
274 274 $this->redirect('server-files');
275 275  
  276 +// $csv = new \console\controllers\ParserController( 'parse-csv', $this->module );
  277 +// $csv->actionParseCsv();
276 278 }
277 279  
278 280  
... ...
backend/models/Importers.php
... ... @@ -2,6 +2,7 @@
2 2  
3 3 namespace backend\models;
4 4  
  5 +use common\components\CustomVarDamp;
5 6 use Yii;
6 7 use backend\components\base\BaseActiveRecord;
7 8  
... ... @@ -93,6 +94,7 @@ class Importers extends BaseActiveRecord
93 94 {
94 95 // возьмем только поля описанные в fields() - там как раз наши настройки парсера
95 96 $arr = $this->toArray();
  97 +
96 98 // отсортируем по ключам с учетом преобразования в число
97 99 asort($arr, SORT_NUMERIC);
98 100 // уберем нулевые колонки
... ... @@ -101,10 +103,21 @@ class Importers extends BaseActiveRecord
101 103 });
102 104 // нам нужны именно ключи
103 105 $arr = array_keys($arr);
  106 +
104 107 return $arr;
  108 + }
  109 +
  110 +
  111 + public function getMultiply ()
  112 + {
  113 + $arr['sign'] = $this->PARSER_FIELD_SIGN;
  114 + $arr['multiplier'] = $this->PARSER_FIELD_MULTIPLIER;
105 115  
  116 + return $arr;
106 117 }
107 118  
  119 +
  120 +
108 121 public function fields()
109 122 {
110 123 return [
... ... @@ -119,5 +132,4 @@ class Importers extends BaseActiveRecord
119 132  
120 133 }
121 134  
122   -
123 135 }
... ...
common/components/parsers/CustomConverter.php
... ... @@ -11,6 +11,9 @@ class CustomConverter extends Converter {
11 11 * @param $key_array - ключи для вложенного массива
12 12 * @return array - таблица с проименованными колонками
13 13 */
  14 + public static $sign;
  15 + public static $multiplier;
  16 +
14 17 public static function convertToAssocArray ( array $value_arr, array $key_array, $key_prefix = '' )
15 18 {
16 19 // очистка служебного префикса в массиве заголовков
... ... @@ -82,6 +85,40 @@ class CustomConverter extends Converter {
82 85 return $row;
83 86 }
84 87  
  88 + public function ConvertToMultiply ( array $row )
  89 + {
  90 + $PRICE = $row[ 'PRICE' ];
  91 + $sign = self::$sign;
  92 + $multiplier = self::$multiplier;
  93 + //CustomVarDamp::dumpAndDie(self);
  94 + if (isset($sign)) {
  95 + if ($sign == '+') {
  96 + if ($multiplier > 0) {
  97 + $PRICE += $multiplier;
  98 + }
  99 + }
  100 + else if ($sign == '-') {
  101 + if ($multiplier > 0) {
  102 + $PRICE -= $multiplier;
  103 + }
  104 + }
  105 + else if ($sign == '*') {
  106 + if ($multiplier > 0) {
  107 + $PRICE *= $multiplier;
  108 + }
  109 + }
  110 + else if ($sign == '/') {
  111 + if ($multiplier > 0) {
  112 + $PRICE /= $multiplier;
  113 + }
  114 + }
  115 + }
  116 +
  117 + $row[ 'PRICE' ] = $PRICE;
  118 +
  119 + return $row;
  120 +
  121 + }
85 122  
86 123  
87 124 }
88 125 \ No newline at end of file
... ...
common/components/parsers/CustomCsvParser.php
... ... @@ -25,10 +25,12 @@ class CustomCsvParser extends \yii\multiparser\CsvParser {
25 25 if ($this->hasHeaderRow) {
26 26 // если у файла есть заголовок, то в результате имеем ассоциативный массив
27 27 $this->converter_conf['hasKey'] = 1;
  28 +
28 29 }
29 30  
30 31 }
31   -
  32 +// $this->converter = \Yii::createObject( $this->converter_conf );
  33 +// CustomVarDamp::dumpAndDie($this->converter);
32 34 }
33 35  
34 36 /**
... ... @@ -38,7 +40,7 @@ class CustomCsvParser extends \yii\multiparser\CsvParser {
38 40 */
39 41 protected function convert($arr)
40 42 {
41   - $arr = \Yii::$app->multiparser->convertByConfiguration($arr, $this->converter_conf);
  43 + $arr = \Yii::$app->multiparser->convertByConfiguration( $arr, $this->converter_conf );
42 44  
43 45 return $arr;
44 46  
... ...
common/components/parsers/config.php
... ... @@ -4,18 +4,21 @@
4 4 ['web' =>
5 5 ['class' => 'common\components\parsers\CustomCsvParser',
6 6 'auto_detect_first_line' => true,
7   - 'converter_conf' => ['class' => ' common\components\parsers\CustomConverter',
  7 + 'converter_conf' => [
  8 + //'class' => ' common\components\parsers\CustomConverter', // @todo переделать на подключаемый behavior
8 9 'configuration' => ["string" => 'DESCR'],]
9 10 ],
10 11 'console' =>
11 12 ['class' => 'common\components\parsers\CustomCsvParser',
12 13 'auto_detect_first_line' => true,
13 14 'hasHeaderRow' => true,
14   - 'converter_conf' => ['class' => ' common\components\parsers\CustomConverter',
  15 + 'converter_conf' => [
  16 + //'class' => ' common\components\parsers\CustomConverter',
15 17 'hasKey' => 1,
16 18 'configuration' => ["string" => 'DESCR',
17 19 "float" => 'PRICE',
18 20 "integer" => ['BOX','ADD_BOX'],
  21 + "multiply" => [],
19 22 "details" => [] // @todo сделать отдельно конфигурирование валидации
20 23  
21 24 ]
... ... @@ -36,7 +39,8 @@
36 39 ['console' =>
37 40 ['class' => 'yii\multiparser\XmlParser',
38 41 'node' => 'Товар',
39   - 'converter_conf' => ['class' => ' common\components\parsers\CustomConverter',
  42 + 'converter_conf' => [
  43 + //'class' => ' common\components\parsers\CustomConverter',
40 44 'hasKey' => 1,
41 45 'configuration' => ["details" => []
42 46 ],],
... ...
console/controllers/ParserController.php
1 1 <?php
2 2 namespace console\controllers;
3 3  
  4 +use common\components\CustomVarDamp;
4 5 use yii\console\Controller;
5 6 use yii\helpers\Console;
6 7 use common\components\PriceWriter;
... ... @@ -10,7 +11,6 @@ use yii\base\ErrorException;
10 11  
11 12 class ParserController extends Controller
12 13 {
13   -
14 14 public function actionParseCsv()
15 15 {
16 16 \Yii::info('Начало загрузки файлов прайсов csv', 'parser');
... ... @@ -18,11 +18,22 @@ class ParserController extends Controller
18 18 $file_name = basename($file_path, ".csv");
19 19 \Yii::info("Обработка файла - $file_path", 'parser');
20 20 $importer_id = ImportersFiles::findOne(['id' => $file_name])->importer_id;
21   - $keys = Importers::findOne(['id' => $importer_id])->keys;
  21 + $current_importer = Importers::findOne(['id' => $importer_id]);
  22 + $keys = $current_importer->keys;
  23 + $mult_array = $current_importer->multiply;
  24 +
  25 + // получим настройки ценообразования и передадим их отдельно в конвертер
  26 + $sign = '';
  27 + $multiplier = '';
  28 + extract( $mult_array );
  29 +
22 30  
23 31 $config = ['record_id' => $file_name,
24 32 'importer_id' => $importer_id,
25 33 'parser_config' => ['keys' => $keys,
  34 + 'converter_conf' =>
  35 + ['sign' => $sign,
  36 + 'multiplier' => $multiplier],
26 37 'mode' => 'console']
27 38 ];
28 39 if ($this->parseFileConsole($file_path, $config)) {
... ... @@ -48,7 +59,7 @@ class ParserController extends Controller
48 59 $parser_config = $configuration['parser_config'];
49 60 }
50 61 $data = \Yii::$app->multiparser->parse( $file_path, $parser_config );
51   - if (! $data) {
  62 + if ( ! $data ) {
52 63 // @todo переделать, что бы ошибка автоматически останавливала сценарий
53 64 return false;
54 65 }
... ...