From: fomichev Date: Fri, 21 Mar 2025 07:16:58 +0000 (+0300) Subject: Чистка кода и рефакторинг X-Git-Url: https://gitweb.erp-flowers.ru/?a=commitdiff_plain;h=1bbb54bb8339cd883278ded141926307b1014a6e;p=erp24_rep%2Fyii-erp24%2F.git Чистка кода и рефакторинг --- diff --git a/erp24/commands/MarketplaceController.php b/erp24/commands/MarketplaceController.php index cc145bd7..a1af78ca 100644 --- a/erp24/commands/MarketplaceController.php +++ b/erp24/commands/MarketplaceController.php @@ -97,10 +97,7 @@ class MarketplaceController extends Controller $countMessages = 0; $count = 0; - $this->stdout( - "Удалось сохранить {$date} новых заказов из {$this->date} сообщений почты.\n", - BaseConsole::FG_GREEN - ); + $progressCallback = function ($message) { $this->stdout($message . "\n", BaseConsole::FG_YELLOW); }; diff --git a/erp24/media/controllers/FlowwowController.php b/erp24/media/controllers/FlowwowController.php index a7212b5c..76ea851b 100644 --- a/erp24/media/controllers/FlowwowController.php +++ b/erp24/media/controllers/FlowwowController.php @@ -56,302 +56,18 @@ class FlowwowController extends Controller { set_time_limit(300); Yii::$app->response->format = Response::FORMAT_JSON; - // $hostname = '{imap.yandex.ru:993/imap/ssl}INBOX'; - $username = 'flow@bazacvetov24.ru'; - $password = 'ctqamxqeshgxwsgn'; - - // $hostname = '{imap.yandex.ru:993/imap/ssl}INBOX'; - // $username = 'Zakaz-bazacvetov24@yandex.ru'; - // $password = 'jyxnwwwvgpwhzbdu'; - - $mailbox = '{imap.yandex.ru:993/imap/ssl}'; - $inbox = imap_open($mailbox . 'INBOX', $username, $password); - $folders = imap_list($inbox, $mailbox, '*'); // Получение всех папок - imap_close($inbox); - $count = 0; - foreach ($folders as $folder) { - $inbox = imap_open($folder, $username, $password); - if (!$inbox) { - Yii::error('Ошибка подключения: ' . imap_last_error(), __METHOD__); - } - - - $emails = imap_search($inbox,'SINCE "20-Mar-2025" FROM "" SEEN'); - - $count += $emails ? count($emails) : 0; - imap_close($inbox); - } - return $count; - // Устанавливаем таймауты IMAP - imap_timeout(IMAP_OPENTIMEOUT, 120); - imap_timeout(IMAP_READTIMEOUT, 120); - imap_timeout(IMAP_WRITETIMEOUT, 120); - imap_timeout(IMAP_CLOSETIMEOUT, 120); - - $inbox = imap_open($hostname, $username, $password); - if (!$inbox) { - Yii::error('Ошибка подключения: ' . imap_last_error(), __METHOD__); - return ['success' => false]; - } - //$inboxInfo = imap_mailboxmsginfo($inbox); - //Yii::warning(' Состояние ящика: ' . print_r($inboxInfo, true), __METHOD__); - $emails = imap_search($inbox, 'ON "14-Feb-2025" FROM "info@flowwow.com" '); - $count = $emails ? count($emails) : 0; - $orders = []; - $messages = []; - - $subjectPatterns = [ - '/^Новый_оплаченный_заказ$/', - '/^Заказ_№\d+_принят!$/', - '/^Flowwow. Заказ_выполнен._Напишите_отзыв_о_клиенте$/', - '/^Заказ_№\d+_отменён$/', - '/^Изменения_в_заказе_№\d+$/', - ]; - - if ($emails) { - foreach ($emails as $email_number) { - $overview = imap_fetch_overview($inbox, $email_number, 0); - $structure = imap_fetchstructure($inbox, $email_number); - $htmlMessage = ''; - $subject = mb_decode_mimeheader($overview[0]->subject); - $from = mb_decode_mimeheader($overview[0]->from); - $to = mb_decode_mimeheader($overview[0]->to); - $date = date('Y-m-d H:i:s', strtotime(mb_decode_mimeheader($overview[0]->date))); - Yii::warning('Тема: ' . json_encode($subject, JSON_UNESCAPED_UNICODE), __METHOD__); - foreach ($subjectPatterns as $pattern) { - if (preg_match($pattern, $subject)) { - $subjectIndex = self::SUBJECT_INDEX[$pattern]; - Yii::warning('Тема прошла: ' . json_encode($subject, JSON_UNESCAPED_UNICODE), __METHOD__); - if (isset($structure->parts) && count($structure->parts)) { - foreach ($structure->parts as $partNum => $part) { - if ($part->subtype == 'HTML') { - $htmlMessage = imap_fetchbody($inbox, $email_number, $partNum + 1); - $htmlMessage = quoted_printable_decode($htmlMessage); - break; - } - } - } - $htmlMessage = html_entity_decode($htmlMessage, ENT_QUOTES, 'UTF-8'); - // $htmlMessage = str_replace('\"', '"', $htmlMessage); - // $htmlMessage = str_replace(['\r', '\n', '\r\n'], '', $htmlMessage); - $htmlMessage = preg_replace('/\s+/', ' ', $htmlMessage); - // $htmlMessage = stripslashes($htmlMessage); - return $htmlMessage; - $doc = new HtmlDomParser($htmlMessage); - $orderNumber = ''; - $main = $doc->findOneOrFalse("body"); - - if ($main !== false) { - $orderTitleNode = $main->findOne("h1"); - - if ($orderTitleNode && preg_match('/№(\d+)/', $orderTitleNode->innertext, $matches)) { - $orderNumber = (int)$matches[1]; - } - } - return $orderNumber; - $messages[] = [ - 'subject' => $subject, - 'subject_index' => $subjectIndex, - 'from' => $from, - 'to' => $to, - 'date' => $date, - //'body' => $htmlMessage, - ]; - //break; - } - } - // imap_setflag_full($inbox, $email_number, "\\Seen"); - } - } - imap_close($inbox); - usort($messages, fn($a, $b) => $a['subject_index'] <=> $b['subject_index']); - return $messages; - if ($messages) { - foreach ($messages as $message) { - $html = $message['body']; - $orderNumber = null; - $items = []; - $totalSum = 0; - if (!empty($html)) { - $html = html_entity_decode($html, ENT_QUOTES | ENT_HTML5, 'UTF-8'); - - $doc = new HtmlDomParser($html); - - $main = $doc->findOneOrFalse("body"); - $body = new SimpleHtmlDom($main->getNode()); - if ($main !== false) { - $orderTitleNode = $main->findOne("h1"); - - if ($orderTitleNode && preg_match('/№(\d+)/', $orderTitleNode->innertext, $matches)) { - $orderNumber = (int)$matches[1]; - } - } - } - if (preg_match($subjectPatterns[0], $message['subject'])) { // Новый заказ - continue; - - try { - // Извлечение товаров - $elements = $main->findOne("p:contains('Детали заказа')")->parentNode(); - if ($elements) { - foreach ($elements->findMultiOrFalse("tr") as $itemRow) { - $img = $itemRow->findOne("td img"); - $nameNode = $itemRow->findOne("td:nth-child(2) p"); - if (!$img || !trim($nameNode->plaintext)) { - continue; - } - - $name = trim($nameNode->plaintext); - - // Количество - $countNode = $itemRow->findOne("td:nth-child(2) p[style*='#8C8C8C']"); - $countText = $countNode ? $countNode->plaintext : '1'; - $count = (int)filter_var($countText, FILTER_SANITIZE_NUMBER_INT); - - // Сумма - $sumNode = $itemRow->findOne("td:nth-child(3) p"); - $sumText = $sumNode ? $sumNode->plaintext : '0'; - $sum = (float)str_replace([' ', '₽'], '', $sumText); - - $items[] = ['name' => $name, 'count' => $count, 'sum' => $sum]; - } - } - - // Общая сумма - $totalSumNodes = $elements->parentNode()->getElementsByTagName('table'); - $totalSumNode = ($totalSumNodes[3])->findOne("tr:contains('Итого оплачено')"); - if ($totalSumNode) { - $totalSum = (float)str_replace([' ', '₽'], - '', - trim(($totalSumNode->findMulti("td"))[1]->plaintext)); - } - } catch (\Exception $e) { - Yii::error( - 'Ошибка: ' . json_encode($e->getMessage(), JSON_UNESCAPED_UNICODE) . " " . $e->getLine( - ) . " " . json_encode($e->getTrace(), JSON_UNESCAPED_UNICODE), - __METHOD__ - ); - } - - if ($orderNumber !== null) { - $orders[$orderNumber] = [ - 'items' => $items, - 'totalSum' => $totalSum, - 'number' => $orderNumber, - 'date' => $message['date'], - - ]; - } - Yii::warning( - 'HTML Тело письма: ' . json_encode($message['body'], JSON_UNESCAPED_UNICODE), - __METHOD__ - ); - Yii::warning('Новые заказы: ' . json_encode($orders, JSON_UNESCAPED_UNICODE), __METHOD__); - } elseif (preg_match($subjectPatterns[1], $message['subject'])) { - $orderDetails = []; - -// Блок "Доставить" - $deliveryBlock = $main->findOne('p:contains("Доставить")'); - return $main->html(); - if ($deliveryBlock) { - $deliveryBlock = $deliveryBlock->parentNode()->findMulti('p'); - - return json_encode(($deliveryBlock[1])->html(), JSON_UNESCAPED_UNICODE); - $deliveryText = $deliveryBlock->innertext; - Yii::warning('Текст заказа: ' . json_encode($deliveryText, JSON_UNESCAPED_UNICODE), __METHOD__); - $orderDetails['delivery'] = trim($deliveryText); - } - -// Блок "Комментарий" - $commentBlock = $main->findOne('p:contains("Комментарий")'); - if ($commentBlock) { - $commentBlock = $commentBlock->nextSibling(); - $orderDetails['comment'] = trim($commentBlock->innerText()); - } - -// Блок "Клиент" (Отправитель) - $clientBlock = $main->findOne('p:contains("Клиент")'); - if ($clientBlock) { - $clientBlock = $clientBlock->nextSibling(); - $clientText = trim($clientBlock->innerText()); - $orderDetails['sender'] = $clientText; - } - - - // Извлечение товаров - - - Yii::warning( - 'HTML Тело письма: ' . json_encode($message['body'], JSON_UNESCAPED_UNICODE), - __METHOD__ - ); - - $orderItems = []; + $date = date('Y-m-d'); + $since = 0; + $oldMail = 0; + $seen = 0; -// Ищем все комментарии - $startComments = $main->find('comment:contains("START ITEM")'); - - foreach ($startComments as $startComment) { - $itemData = [ - 'image' => '', - 'name' => '', - 'count' => '', - 'price' => '', - ]; - - // Находим следующий элемент после комментария - $tr = $startComment->nextSibling(); - if ($tr && $tr->tag === 'tr') { - // Извлекаем изображение - $img = $tr->find('img')[0]; - if ($img) { - $itemData['image'] = $img->src; - } - - // Извлекаем название и количество из второго - $tds = $tr->find('td'); - if (count($tds) >= 2) { - $itemData['name'] = trim($tds[1]->find('p')[0]->innerText()); - $itemData['count'] = trim($tds[1]->find('p')[1]->innerText()); - } - - // Извлекаем цену из третьего - if (count($tds) >= 3) { - $itemData['price'] = trim($tds[2]->find('p')[0]->innerText()); - } - } - - // Добавляем данные в массив - $orderItems[] = $itemData; - } + $countMessages = 0; + $count = 0; - $orderDetails['items'] = $orderItems; - // Общая сумма - $total = ''; - -// Ищем комментарий - $startTotalComment = $main->findOne('comment:contains("START TOTAL")'); - if ($startTotalComment) { - // Находим следующий элемент после комментария - $tr = $startTotalComment->nextSibling(); - if ($tr && $tr->tag === 'tr') { - // Извлекаем текст из второго - $tds = $tr->find('td'); - if (count($tds) >= 2) { - $totalSum = trim($tds[1]->find('p')[0]->innerText()); - } - } - } - $orderDetails['totalSum'] = $totalSum; - $orders[$orderNumber] = $orderDetails; + $messages = MarketplaceService::getFlowwowOrdersFromMail($date, $since, $oldMail, null, $seen); - Yii::warning('Принятые заказы: ' . json_encode($orders, JSON_UNESCAPED_UNICODE), __METHOD__); - } - // Yii::warning('HTML Тело письма: ' . json_encode($message['body'], JSON_UNESCAPED_UNICODE), __METHOD__); - } - } else { - Yii::warning('Новых сообщений не обнаружено.', __METHOD__); - } + $countMessages = count($messages); + $count = MarketplaceService::processMessages($messages); return ['success' => true, 'count' => $count]; }