(function () { const CONFIG = { GOOGLE_SCRIPT_URL: 'https://script.google.com/macros/s/AKfycbwS-XppfeVDuwzxcqomt9ScmQQAZRCyg-J6eNEZy0t3wpAoygTXgAK2eKY2oqIhRUVreA/exec', ACCESS_USERS: window.accessToAddMailingsInExcel, TARGET_PATH: '/pl/notifications/control/mailings/log' }; const templateButton = (id) => ``; async function sendToGoogleSheets(data) { return new Promise(async (resolve) => { let form; let iframe; try { console.log('Отправка данных:', data); form = document.createElement('form'); form.method = 'POST'; form.action = CONFIG.GOOGLE_SCRIPT_URL; form.target = 'hiddenFrame'; form.style.display = 'none'; const input = document.createElement('input'); input.name = 'data'; input.value = JSON.stringify(data); form.appendChild(input); iframe = document.getElementById('hiddenFrame'); if (!iframe) { iframe = document.createElement('iframe'); iframe.name = 'hiddenFrame'; iframe.id = 'hiddenFrame'; iframe.style.display = 'none'; iframe.style.width = '0'; iframe.style.height = '0'; iframe.style.border = '0'; document.body.appendChild(iframe); } iframe.onload = function () { console.log('Форма отправлена успешно'); if (form && form.parentNode) { form.parentNode.removeChild(form); } resolve({ success: true, action: 'added' }); }; iframe.onerror = function () { console.log('Ошибка отправки формы'); if (form && form.parentNode) { form.parentNode.removeChild(form); } resolve({ success: true, action: 'added' }); }; document.body.appendChild(form); form.submit(); setTimeout(() => { if (form && form.parentNode) { form.parentNode.removeChild(form); } resolve({ success: true, action: 'added' }); }, 5000); } catch (error) { console.error('Ошибка отправки:', error); if (form && form.parentNode) { form.parentNode.removeChild(form); } resolve({ success: false, error: error.message }); } }); } function extractDataFromRow(td, id) { const getText = (selector) => td.querySelector(selector)?.textContent?.trim() || ''; const getStat = (selector, splitText) => { const element = td.querySelector(selector); return element ? element.textContent.trim().split(splitText)[0].trim() : ''; }; const title = getText('[data-col-seq="5"] > a'); const dateResponse = getText('[data-col-seq="5"] > .text-muted .small').split(',')[1]?.trim() || ''; const author = getText('.user-profile-link'); const type = getText('[data-col-seq="4"]'); const transport = getText('[data-col-seq="6"]'); const link = id ? `https://5-quantum.com/notifications/control/mailings/update/id/${id}` : ''; const messageText = getText('[data-col-seq="9"] .bar-percentage'); const messageParts = messageText.split(' / '); const [deliveredMessage = '', totalMessage = ''] = messageParts; const views = getStat(`[href="/pl/notifications/control/messages/index?mailingId=${id}&status=sent&viewed=1"]`, ' просмотр'); const clicks = getStat(`[href="/pl/notifications/control/messages/index?mailingId=${id}&status=sent&clicked=1"]`, ' клик'); const responses = getStat(`[href="/pl/notifications/control/messages/message-comment?mailingId=${id}"]`, ' ответ'); const notDelivered = getStat(`[href="/pl/notifications/control/messages/index?mailingId=${id}&status=error"]`, ' не достав'); return { id: id, link: link, title: title, author: author, dateResponse: dateResponse, type: type, transport: transport, message: { totalMessage: totalMessage, deliveredMessage: deliveredMessage, }, stat: { notDelivered: notDelivered, views: views, clicks: clicks, responses: responses, } }; } function showButtonLoading(button) { const originalHTML = button.innerHTML; button.innerHTML = '
'; button.disabled = true; button.dataset.originalHTML = originalHTML; return originalHTML; } function restoreButton(button, success = true) { if (success) { button.innerHTML = '✅'; setTimeout(() => { button.innerHTML = button.dataset.originalHTML; button.disabled = false; }, 2000); } else { button.innerHTML = '❌'; setTimeout(() => { button.innerHTML = button.dataset.originalHTML; button.disabled = false; }, 2000); } } async function handleExportClick(evt) { evt.preventDefault(); evt.stopPropagation(); const askAdmin = confirm('Отправить запрос на добавление/обновление статистики в Google Таблицу?'); if (!askAdmin) return; const button = evt.currentTarget; showButtonLoading(button); try { const td = evt.target.closest('.w2.has-archived-row') || document.querySelector(`.w2.has-archived-row[data-key="${evt.target.dataset.id}"]`); const id = td?.dataset?.key; if (!id) throw new Error('ID рассылки не найден'); const data = extractDataFromRow(td, id); console.log('Отправляем данные:', data); const result = await sendToGoogleSheets(data); if (result.success) { restoreButton(button, true); alert('✅ Данные успешно отправлены в Google Таблицу!'); console.log('✅ Данные успешно отправлены в Google Таблицу!'); } else { throw new Error(result.error || 'Неизвестная ошибка'); } } catch (error) { console.error('Ошибка:', error); restoreButton(button, false); alert('❌ Ошибка при отправке: ' + error.message); } } if (location.pathname === CONFIG.TARGET_PATH && CONFIG.ACCESS_USERS.includes(window.accountUserId)) { const check = setInterval(() => { const tableCells = document.querySelectorAll('.kv-grid-table .w2.has-archived-row'); if (tableCells.length > 0) { tableCells.forEach((td) => { if (!td.querySelector('.cst-insert-to-excel')) { const id = td.dataset.key; td.insertAdjacentHTML('beforeend', templateButton(id)); } }); document.querySelectorAll('.cst-insert-to-excel').forEach((button) => { button.removeEventListener('click', handleExportClick); button.addEventListener('click', handleExportClick); }); clearInterval(check); } }, 100); } })();