Newer
Older
vmk-demo-bot / frontend / dist / js / main.js
function doQuestionEventHandler(t){const e=t.currentTarget.dataset.doQuestion;document.querySelector(".chat-container").appendChild(createRenderBubble("user",!0,e).message);sendMessages(makeAssistantMsg(),prepareUserMessage(e),(function(t,e){if("done"!=t.status)return;updateMsgContent(e,marked.parse(t.content).trim()),updateMsgHistory()}))}const specialViewMap={product_card:t=>{console.log("product_card",t);let e=`<div class="kb-card kb-product-card">\n\t\t\t<h4 class="heading">${t.title}</h4>\n\t\t\t<div class="actions-group">\n\t\t\t\t<div class="price">\n\t\t\t\t\t<span class="now">${t.price}</span>\n\t\t\t\t</div>\n\t\t\t\t<div>\n\t\t\t\t\t<a href="${t.link}" class="kb-btn tricky go-to-product">\n\t\t\t\t\t\tКупити\n\t\t\t\t\t\t<svg class="kb-icon" width="24" height="24">\n\t\t\t\t\t\t\t<use href="#kb-arrow-right"></use>\n\t\t\t\t\t\t</svg>\n\t\t\t\t\t</a>\n\t\t\t\t</div>\n\t\t\t</div>\t\t\n\t\t</div>`,n=document.createElement("div");return n.innerHTML=e,n.querySelector(".kb-card")},identification_card:t=>{console.log("identification_card",t);let e=document.createElement("div");e.innerHTML='\n\t\t\t<div class="kb-card kb-auth-card">\n\t\t\t\t<div class="description">Введіть номер телефону для перевірки статусу замовлення</div>\n\n\t\t\t\t<div class="kb-input-form">\n\t\t\t\t\t<label for="kb-phone" class="kb-input-label">Номер телефону</label>\n\t\t\t\t\t<div class="kb-input-container">\n\t\t\t\t\t\t<div class="prefix">\n\t\t\t\t\t\t\t<svg class="kb-icon" width="16" height="16">\n\t\t\t\t\t\t\t\t<use href="#kb-ua-flag"></use>\n\t\t\t\t\t\t\t</svg>\n\t\t\t\t\t\t\t<span>+380</span>\n\t\t\t\t\t\t\t<div class="sep"></div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<input type="phone" id="kb-phone" maxlength="9" placeholder="000000000" class="kb-input">\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\n\t\t\t\t<button class="kb-btn large disabled kb-auth-btn">Відправити</button>\n\t\t\t</div>\n\t\t';const n=e.querySelector(".kb-auth-card"),s=n.querySelector(".kb-auth-btn");return n.querySelector("#kb-phone").addEventListener("input",(t=>{t.currentTarget.value=t.currentTarget.value.replace(/\D/g,""),t.currentTarget.value.length<9?s.classList.add("disabled"):s.classList.remove("disabled")})),n},frequentlyQuestions:t=>{let e="";for(let n of t.questions)e+=`\n\t\t\t\t<button class="kb-btn tricky question" data-do-question="${n}">${n}</button>\n\t\t\t`;const n=`\n\t\t\t<div class="frequently-questions">\n\t\t\t\t<h4 class="heading">Часті запитання:</h4>\n\t\t\t\t<div class="questions-container">\n\t\t\t\t\t${e}\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t`;let s=document.createElement("div");s.innerHTML=n;const a=s.querySelector(".frequently-questions");return a.querySelectorAll("[data-do-question]").forEach((t=>{t.addEventListener("click",(t=>{doQuestionEventHandler(t)}))})),a},frequentlyAsked:t=>{let e="";for(let n of t.questions)e+=`\n\t\t\t\t<button class="kb-btn tricky question" data-do-question="Мене цікавить ${n}">\n\t\t\t\t\t<svg class="kb-icon" width="16" height="16">\n\t\t\t\t\t\t<use href="#kb-star"></use>\n\t\t\t\t\t</svg>\n\t\t\t\t\t${n}\n\t\t\t\t</button>\n\t\t\t`;const n=`\n\t\t\t<div class="frequently-asked">\n\t\t\t\t<h4 class="heading">Поширені запити:</h4>\n\t\t\t\t<div class="questions-container">\n\t\t\t\t\t${e}\n\n\t\t\t\t\t<button class="kb-btn tricky question" onclick="showFreqQuests()">\n\t\t\t\t\t\t<svg class="kb-icon" width="16" height="16">\n\t\t\t\t\t\t\t<use href="#kb-star"></use>\n\t\t\t\t\t\t</svg>\n\t\t\t\t\t\tЧасті запитання\n\t\t\t\t\t</button>\n\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t`;let s=document.createElement("div");s.innerHTML=n;const a=s.querySelector(".frequently-asked");return a.querySelectorAll("[data-do-question]").forEach((t=>{t.addEventListener("click",(t=>{doQuestionEventHandler(t)}))})),a}};function showFreqQuests(){const t=specialViewMap.frequentlyQuestions({questions:["Мені потрібна допомога у виборі засобу догляду","Які умови співпраці?","Я хочу записатись на курс","Де можна отримати консультацію?","Який статус мого замовлення?"]});document.querySelector(".chat-container").appendChild(t),scrollMsgsContainerDown(),updateMsgHistory()}async function sendMessages(t,e,n){url=AISERV,hostMap={"kitanbot.vmk-group.tech":"kitan-group","localhost:3000":"kitan-group","kitan-group.com":"kitan-group","hbloom.com.ua":"hbloom","nubea.com.ua":"nubea","mediceuticals.com.ua":"mediceuticals","bosleymd.com.ua":"bosleymd"},e.site=hostMap[document.location.host]??document.location.host;try{const s=await fetch(url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"kitan",message:e})});if(!s.ok)throw new Error(`Ошибка при отправке: ${s.status} ${s.statusText}`);const a=s.body.getReader(),o=new TextDecoder("utf-8");let i="";for(;;){const{done:e,value:s}=await a.read();if(e)break;i+=o.decode(s,{stream:!0});let r=i.split("\n");i=r.pop();for(const e of r)if(e.trim())try{const s=JSON.parse(e);n&&n(s,t)}catch(t){console.warn("Ошибка разбора JSON:",t,e)}}if(i)try{const t=JSON.parse(i);n&&n(t)}catch(t){console.warn("Ошибка разбора последнего чанка:",t,i)}}catch(t){console.error("Ошибка при отправке сообщений:",t)}}function prepareUserMessage(t){return{message:{id:1,date:getCurrentDateTime(),text:t,reply_to_message:null,entities:null,photo:null,document:null,voice:null,audio:null,video:null,sticker:null,caption:null},author:{id:1,username:"",first_name:"",last_name:"",title:null,type:"user"},is_forwarding:!1,origin:{from:"kitan_bot",chat_id:getChatId()}}}function getTimeView(){const t=new Date,e=t.getHours().toString().padStart(2,"0"),n=t.getMinutes().toString().padStart(2,"0");return time=`${e}:${n}`}function getCurrentDateTime(){const t=new Date,e=t=>t.toString().padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())} ${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}`}function updateMsgHistory(){const t=document.querySelector(".chat-container");localStorage.setItem("chat",t.innerHTML)}function restoreMsgStorage(){const t=document.querySelector(".chat-container");let e=localStorage.getItem("chat");e&&(t.innerHTML=e),t.querySelectorAll("[data-do-question]").forEach((t=>{t.addEventListener("click",(t=>{doQuestionEventHandler(t)}))}))}function getChatId(){return chatId=localStorage.getItem("chatId"),chatId||(chatId=Math.floor(99e6*Math.random())+1e6,localStorage.setItem("chatId",chatId)),chatId}function resetChat(){localStorage.removeItem("chatId"),localStorage.removeItem("chat"),localStorage.removeItem("user_rating")}function genMsgId(){return"msgid"+(new Date).getTime()}function createRenderBubble(t,e,n,s,a){a=a||getTimeView(),s=s||genMsgId(),waitingLoader='\n\t\t<span class="waiting">\n\t\t\t<span></span>\n\t\t\t<span></span>\n\t\t\t<span></span>\n\t\t</span>\n\t',n=n||waitingLoader;const o=[];let i="";"user"==t?(o.push("user"),i='\n\t\t\t<svg class="kb-icon" width="16" height="16">\n\t\t\t\t<use href="#kb-user"></use>\n\t\t\t</svg>\n\t\t'):(o.push("agent"),o.push("assistant"),o.push("state-waiting"),i='\n\t\t\t<svg class="kb-icon" width="32" height="32">\n\t\t\t\t<use href="#kb-redes-sm-avatar"></use>\n\t\t\t</svg>\n\t\t');const r=`\n\t\t<div class="message ${o.join(" ")}" id="${s}">\n\t\t\t<div class="leftside">\n\t\t\t\t<div class="avatar">\n\t\t\t\t\t${i}\n\t\t\t\t</div>\n\t\t\t</div>\n\n\t\t\t<div class="rightside">\n\t\t\t\t<div class="kb-card bubble first">\n\t\t\t\t\t${n}\n\t\t\t\t</div>\n\t\t\t\t<div class="foot">\n\t\t\t\t\t<span class="timestamp">${a}</span>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</div>\n\t`,c=document.createElement("DIV");return c.innerHTML=r,{id:s,message:c.querySelector(".message")}}function updateMsgContent(t,e){const n=document.querySelector(`.assistant#${t}`);n.classList.remove("state-waiting"),n.querySelector(".bubble").innerHTML=e,updateMsgHistory(),scrollMsgsContainerDown()}function doAction(t,e,n){url=BACKSERV,fetch(url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,params:e})}).then((t=>t.json())).then((t=>{n(t)})).catch((t=>{console.error("Err of request:",t)}))}function getSpecialViewFromMsg(t){const e="front_special_view";if(-1==t.indexOf(e))return!1;let n=t.split(e)[1].trim(),s=document.createElement("textarea");return s.innerHTML=n,n=s.value,!!n&&(n=JSON.parse(n),void 0!==specialViewMap[n.special_view]&&specialViewMap[n.special_view](n.data))}function initAuthCard(){}document.addEventListener("DOMContentLoaded",(t=>{console.log("App start")}));
//# sourceMappingURL=main.js.map