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w9SJ1K9bGMDvO1qqiLFxqMpNe_VaYnXSdQKPSjNIg0qGIizvwifWo5EfoshoOIWBu0LBT0GulhVN42XcADwwkZnQhCOnO4gp2Sms3bc4Wf8u6BOW_EB5ZESVzf2Q1DetcxXz8Oo6NTAD8tJiEHEGpLJfFNI_2fUC_elCpr3i_Qn9XbnNfnFOi6APkTCtGOFUBUjOmJZz0RHlj9elPfK2_mJRGnAVb1TEumWg' const REFRESH_TOKEN = 'def5020054ff9f61f3a1d4908fad5fbb447c3411e943cd5b658707882fdf7e00652719cf68e195e864e025cd01eff1dc10610ccd53f0f9c8738288ac3712b15f7378af17746e7d2c4830cacf2dfb887349d009a63a8759238038fc9b10bdc9445584405798adb06c83cd2190d1be9b6d18da92bbbcdc45bf9a0b5d537879ed2dc7b17e001a49d8645be88ed1733425824489645fbe64c36f954cfacb83388181a113c3db9d960c0e3aa9553aa9fb948c575302606f0908fe937242ce683787b68435243950eb957110b94119c1b10cb73850ee2c8bf7b1f4af4038708e73adf4713dd2ab138fa091e52f18e17cc43ba9a58ef60748ff7fd1c6cbe2b91a4123cc54807685b93739c70622c34e4bf212c656d8bfdef22597845daafef73d503d0e63f93a5297f01d22226aa5a841a179730c44f25193efb03bec6e17aebeea55ed12745ab5739cd18db21d6e128f25a24c69bd4a751d2c303455e46ed3767e9dadb157c09ae9360c15a93da16e7f59b1f54c22fb96cf69e64e73f8c94c1cba41906186021d3304dd1032e1d63df32e818e2518243484457e5f142ca13068d2841e14b6ce6f6e9d4a7c538c0d0432c276e605418e7f46b6b3d43b96acebd99d0ab5da10f35f534a61b1476b80aadf113b0e2cd28ae2072c47f6c85dec1ac3c5681186f08f46320aac28de3e93f0aea4' const TZ_OFFSET = new Date().getTimezoneOffset() / 60 const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) const time = () => Math.ceil(Date.now() / 1000) const isToday = timestamp => { const offsetSeconds = TZ_OFFSET * 3600000 // 60 * 60 * 1000 const date = new Date(timestamp * 1000 + offsetSeconds) const today = new Date(Date.now() + offsetSeconds) date.setHours(0, 0, 0, 0) today.setHours(0, 0, 0, 0) return date.getTime() === today.getTime() } const getDdMmYyyy = timestamp => { const date = new Date(timestamp * 1000) let day = date.getDate() let month = date.getMonth() + 1 const year = date.getFullYear() if (day < 10) { day = '0' + day; } if (month < 10) { month = '0' + month; } return `${day}.${month}.${year}` } const getTokens = async authCode => { try { const response = await fetch(`https://${DOMAIN}/oauth2/access_token`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ client_id: CLIENT_ID, client_secret: CLIENT_SECRET, grant_type: 'authorization_code', code: authCode, redirect_uri: REDIRECT_URI }) }) if (!response.ok) { throw new Error(`Ошибка: ${response.status}`) } const data = await response.json() return { access_token: data.access_token, refresh_token: data.refresh_token } } catch (error) { console.error('Ошибка при получении токенов:', error) throw error } } const getContact = async id => { try { const response = await fetch(`https://${DOMAIN}/api/v4/contacts/${id}`, { method: 'GET', headers: { 'Authorization': `Bearer ${ACCESS_TOKEN}`, 'Content-Type': 'application/json' } }) if (!response.ok) { throw new Error(`Ошибка: ${response.status}`) } const data = await response.json() return data } catch (error) { console.error('Ошибка при получении контактов:', error) throw error } } const getLead = async (id) => { try { const response = await fetch(`https://${DOMAIN}/api/v4/leads/${id}?with=catalog_elements`, { method: 'GET', headers: { 'Authorization': `Bearer ${ACCESS_TOKEN}`, 'Content-Type': 'application/json' } }) if (!response.ok) { throw new Error(`Ошибка: ${response.status}`) } const data = await response.json() return data } catch (error) { console.error('Ошибка при получении сделки:', error) throw error } } const getLeads = async (page = 1, limit = 2) => { try { const response = await fetch(`https://${DOMAIN}/api/v4/leads?page=${page}&limit=${limit}&with=contacts&order[id]=desc`, { method: 'GET', headers: { 'Authorization': `Bearer ${ACCESS_TOKEN}`, 'Content-Type': 'application/json' } }) if (!response.ok) { throw new Error(`Ошибка: ${response.status}`) } const data = await response.json() const leads = await Promise.all(data._embedded.leads.map(async lead => { const contact = lead._embedded.contacts.length ? await getContact(lead._embedded.contacts[0].id) : null return { lead: lead, contact: contact } })) return leads } catch (error) { console.error('Сделок больше нет') throw error } } const getAllLeads = async () => { let page = 1 while (true) { try { const leads = await getLeads(page++) console.log(leads) for (const lead of leads) { console.log(lead) const row = document.getElementById('table').insertRow() row.id = `lead-${lead.lead.id}` row.classList.add('main-row') row.onclick = async () => await getLeadInfo(lead.lead.id) const cell1 = row.insertCell() const cell2 = row.insertCell() const cell3 = row.insertCell() const cell4 = row.insertCell() const cell5 = row.insertCell() cell1.textContent = lead.lead.id cell2.textContent = lead.lead.name cell3.textContent = lead.lead.price cell4.textContent = lead.contact?.name cell5.textContent = lead.contact ?.custom_fields_values[0] ?.values[0]?.value } } catch (error) { document.getElementById('loader').classList.add('none') console.log(error) throw error break } await sleep(1000) } } const getLeadInfo = async id => { const leadDiv = document.getElementById(`lead-${id}`) const leadDivInfo = document.getElementById(`leadinfo-${id}`) if (leadDivInfo) { leadDivInfo.remove() return } leadDiv.classList.add('loading') const lead = await getLead(id) const row = document.getElementById('table').insertRow(leadDiv.rowIndex + 1) row.id = `leadinfo-${id}` row.onclick = async () => await getLeadInfo(id) const cell0 = row.insertCell() const cell1 = row.insertCell() const cell2 = row.insertCell() const date = getDdMmYyyy(lead.closest_task_at) cell1.textContent = `Дата: ${date}` cell1.colSpan = 2 const status = lead.closest_task_at === null || lead.closest_task_at < time() ? '#f00' : isToday(lead.closest_task_at) ? '#0f0' : '#ff0' const svgns = "http://www.w3.org/2000/svg" const svg = document.createElementNS(svgns, "svg") svg.setAttribute("width", "16") svg.setAttribute("height", "16") const circle = document.createElementNS(svgns, "circle") circle.setAttribute("cx", "8") circle.setAttribute("cy", "8") circle.setAttribute("r", "8") circle.setAttribute("fill", status) svg.appendChild(circle) cell2.textContent = 'Статус: ' cell2.append(svg) cell2.colSpan = 2 leadDiv.classList.remove('loading') } (async () => { await getAllLeads() })()