ParserController.php
6.37 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
<?php
namespace console\controllers;
use common\components\archive_reader\ArchiveCreator;
use common\components\CustomVarDamp;
use common\components\mail\ImapMailReader;
use common\components\mail\MailAttachmentsSaver;
use yii\console\Controller;
use yii\helpers\Console;
use common\components\PriceWriter;
use backend\models\ImportersFiles;
use backend\models\Importers;
use yii\base\ErrorException;
class ParserController extends Controller
{
public function actionParseCsv()
{
\Yii::info('Начало загрузки файлов прайсов csv', 'parser');
foreach (glob(\Yii::getAlias('@auto_upload') . '/*.csv') as $file_path) {
$file_name = basename($file_path, ".csv");
\Yii::info("Обработка файла - $file_path", 'parser');
$importer_id = ImportersFiles::findOne(['id' => $file_name])->importer_id;
$current_importer = Importers::findOne(['id' => $importer_id]);
$keys = $current_importer->keys;
$mult_array = $current_importer->multiply;
// получим настройки ценообразования и передадим их отдельно в конвертер
$sign = '';
$multiplier = '';
extract( $mult_array );
$config = ['record_id' => $file_name,
'importer_id' => $importer_id,
'parser_config' => ['keys' => $keys,
'converter_conf' =>
[ 'sign' => $sign, 'multiplier' => $multiplier, 'importer_id' => $importer_id ],
'mode' => 'console']
];
if ($this->parseFileConsole($file_path, $config)) {
unlink(\Yii::getAlias('@temp_upload') . '/' . $file_name . '.csv');
\Yii::info("Загрузка файла - $file_path успешно завершена", 'parser');
} else {
\Yii::error("Загрузка файла - $file_path завершена с ошибкой", 'parser');
}
//при любом завершении скрипта файл с очереди автозагрузки нужно удалить
unlink(\Yii::getAlias('@auto_upload') . '/' . $file_name . '.csv');
}
}
protected function parseFileConsole( $file_path, $configuration ){
if( !file_exists( $file_path ) )
throw new ErrorException("$file_path - файл не найден!");
$parser_config = [];
if ( isset( $configuration['parser_config'] ) ) {
$parser_config = $configuration['parser_config'];
}
$data = \Yii::$app->multiparser->parse( $file_path, $parser_config );
if ( ! $data ) {
throw new ErrorException("Ошибка обработки файла прайса!");
}
$writer = new PriceWriter();
$writer->configuration = $configuration;
$writer->data = $data;
$writer->mode = 1; //console-режим
if ( $writer->writeDataToDB() ){
return true;
}
return false;
}
public function actionParseXml ()
{
\Yii::info('Начало загрузки файлов прайсов xml', 'parser');
foreach (glob(\Yii::getAlias('@auto_upload') . '/*.xml') as $file_path) {
$file_name = basename($file_path, ".xml");
\Yii::info("Обработка файла - $file_path", 'parser');
$files_model = new ImportersFiles();
// id поставщика всегда = 1 - Склад
$files_model->importer_id = 1;
try {
$files_model->save();
} catch (ErrorException $e) {
throw $e;
}
// получим id только что записанной записи
$record_id = $files_model->find()
->where(['importer_id' => $files_model->importer_id])
->orderBy(['id' => SORT_DESC])
->one()
->id;
$config = ['record_id' => $record_id,
'importer_id' => 1,
'parser_config' => [
'mode' => 'console']
];
if ($this->parseFileConsole($file_path, $config)) {
//unlink(\Yii::getAlias('@auto_upload') . '/' . $file_name . '.xml');
\Yii::info("Загрузка файла - $file_path успешно завершена", 'parser');
} else {
\Yii::error("Загрузка файла - $file_path завершена с ошибкой", 'parser');
}
}
}
public function actionTest()
{
Console::output('It is working');
\Yii::info('2', 'parser');
}
public function actionSaveMailAttachments()
{
\Yii::info('Начало сохранения файлов почты', 'mail');
$mail_reader = new ImapMailReader( '{imap.gmail.com:993/imap/ssl/novalidate-cert}', 'tsurkanovm@gmail.com', 'Wtvr@2000' );
$mailboxes = $mail_reader->getListMailboxes();
foreach ( $mailboxes as $custom_label ) {
$words = explode(" ",str_replace( array($mail_reader->getHostname(),"!"),"",imap_utf7_decode($custom_label)) );
$importer_id = (int)preg_replace("/[^A-Z0-9]+/","", strtoupper($words[0]));
$mail_reader->reOpen( $custom_label );
$saver = new MailAttachmentsSaver( $mail_reader, 'UNSEEN' );
$saver->file_name_parefix = $importer_id . '~!~';
$saver->saveAttachmentsTo(\Yii::getAlias('@temp_upload'));
}
$files = $saver->getSavedFilesArr();
$arch_creator = new ArchiveCreator();
$arch_extensions = $arch_creator->getHandleExtension();
$files_on_unpack = array_intersect( $files , $arch_extensions );
foreach ($files_on_unpack as $arch_ext => $arch_name) {
$arch_reader = $arch_creator->create( $arch_name, $arch_ext);
$arch_reader->extractTo(\Yii::getAlias('@temp_upload'));
unset( $files[$arch_name] );
$files = array_merge( $files, $arch_reader->getExtractedFiles());
}
foreach ( $files as $file => $key ) {
// $files_model = new ImportersFiles();
// $files_model->importer_id = $importer_id;
// $db->lastInsertId()
}
}
}