PageSourceSearch

https://xn--80aeec0cfsgl1g.xn--p1ai/build/assets/AdminSupportChats.store-Ct7vm2fL.js

js xn--80aeec0cfsgl1g.xn--p1ai collected 2026-10-01 14:09:57 UTC 35,038 bytes, 7 lines download raw bytes

1var L=Object.defineProperty;var U=(o,e,t)=>e in o?L(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var a=(o,e,t)=>U(o,typeof e!="symbol"?e+"":e,t);import{s as C,m as T,r as d,G as m,a as W,o as b,U as I}from"./ScreenSize.store-0TrZeDK2.js";import{d as f}from"./dayjsConfig-C7aUJTWx.js";import{a as _}from"./index-CYA3jEbE.js";import{P,E as D}from"./echo-DCV8swk-.js";import{O as H}from"./array-glJMtsb4.js";class ${constructor(){a(this,"countUnreadTickets",0);a(this,"countUnreadMessages",0);a(this,"isInitialized",!1);this.subscribeChannels=this.subscribeChannels.bind(this),T(this,{subscribeChannels:!1}),this.countUnreadTickets=window.countUnreadTickets?countUnreadTickets:0,this.countUnreadMessages=window.countUnreadMessages?countUnreadMessages:0}get countTotalNotifications(){return this.countUnreadMessages+this.countUnreadTickets}addUnreadTickets(){this.countUnreadTickets+=1}addUnreadMessages(){this.countUnreadMessages+=1}init(){if(this.isInitialized||!window.user)return!1;h.connectIntercept().then(()=>{h.startWebSocket(),h.registerChannelSubscriber(this.subscribeChannels),this.subscribeChannels(h.echo),this.isInitialized=!0})}subscribeChannels(e){!e||!window.user||(e.private(`ticket.${window.user.id}`).listen(".ticket.created",t=>{this.addUnreadTickets()}),e.private(`support.${window.user.id}`).listen(".support.message.created",t=>{this.addUnreadMessages()}),e.private(`user.${window.user.id}`).listen("UserMessageCreated",t=>{this.addUnreadMessages()}).listen("OutgoingNotificationChatMessageCreated",t=>{this.addUnreadMessages()}))}}const B=C($,"NotificationStore");function z(){var o,e;if((o=globalThis.crypto)!=null&&o.randomUUID)return globalThis.crypto.randomUUID();if((e=globalThis.crypto)!=null&&e.getRandomValues){const t=globalThis.crypto.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const s=Array.from(t,i=>i.toString(16).padStart(2,"0")).join("");return[s.slice(0,8),s.slice(8,12),s.slice(12,16),s.slice(16,20),s.slice(20)].join("-")}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const s=Math.floor(Math.random()*16);return(t==="x"?s:s&3|8).toString(16)})}class v{constructor(){a(this,"messageItemRef",null);a(this,"messageItem",null);a(this,"route","");a(this,"syncCancelSource",null);a(this,"fileRef",null);a(this,"filesList",[]);a(this,"helloMessage",{id:Math.random().toString(36).substring(2),text:"Пожалуйста распишите Ваш вопрос, чтобы мы смогли на него ответить.",user_id:null});a(this,"typingMessage",{id:0,text:"",user_id:null});a(this,"visibleMessages",new Set);a(this,"observer",null);a(this,"sentMessages",[]);T(this)}get hasFiles(){return this.filesList.length>0}attachFile(e){e.persist();let t=this.filesList.length>0?this.filesList[this.filesList.length-1].id:0,s=Array.from(e.target.files).map((i,n)=>{let r="doc";return i.type.startsWith("image/")&&(r="image"),{id:t+Number(n)+1,name:i.name,size:h.formatBytes(i.size),url:URL.createObjectURL(i),key:r,defaultFileObject:i}});this.fileRef.value="",this.filesList=[...this.filesList,...s]}deleteAttachment(e){this.filesList=this.filesList.filter(t=>t.id!==e),this.fileRef.value=""}isOperatorMessage(e){var t,s,i;return!!(!e.user||(t=e.user)!=null&&t.is_operator||(s=e.user)!=null&&s.is_junior_operator||(i=e.user)!=null&&i.is_senior_operator)}async fetchMessages(e=null){e=e??this.route;let t=await h.axios.get(e);d(()=>{this.messageItem.totalMessages=t.data.totalMessages,this.messageItem.isFetched||(this.messageItem.messages=[...t.data.messages,...this.messageItem.messages])})}scrollMessages(e=!1){return new Promise(t=>{let s=this.messageItemRef;if(!s){t();return}if(e){s.scrollTop=s.scrollHeight,t();return}setTimeout(()=>{s.scrollTop=s.scrollHeight,t()},200),requestAnimationFrame(()=>{s.scrollTop=s.scrollHeight})})}scrollToElement(e,t=null){const s=document.querySelector(t??"body"),i=document.querySelector(e);s&&i&&s.scrollTo({top:i.offsetTop-s.offsetTop})}pushMessage(e,t=null){let s=t??this.messageItem;!s||s.messages.some(n=>n.id===e.id||e.client_message_id&&n.client_message_id===e.client_message_id)||(e.user_id!==window.user.id&&(e.reader=null),s.messages=[...s.messages,e],s.totalMessages++,this.sortMessages(s),this.scrollMessages().then(()=>{this.observeMessages()}))}sortMessagesByCreatedAt(e,t){if(!e.created_at&&!t.created_at)return 0;if(!e.created_at)return-1;if(!t.created_at)return 1;const s=f(e.created_at).valueOf()-f(t.created_at).valueOf();if(s!==0)return s;const i=Number(e.id),n=Number(t.id);return Number.isSafeInteger(i)&&Number.isSafeInteger(n)?i-n:0}sortMessages(e=null){var n;const t=e??this.messageItem;if(!((n=t==null?void 0:t.messages)!=null&&n.length))return;const s=t.messages.filter(r=>r.id===0),i=t.messages.filter(r=>r.id!==0);i.sort(this.sortMessagesByCreatedAt),t.messages=[...i,...s]}async syncMissedMessages(e=null){var n;if(e=e??this.route??"/chat-tickets/messages",!this.messageItem)return;(n=this.syncCancelSource)==null||n.cancel("chat-http-sync-retry"),this.syncCancelSource=_.CancelToken.source();const t=await h.axios.get(e,{timeout:5e3,cancelToken:this.syncCancelSource.token}),s=t.data.messages??[],i=new Map(s.filter(r=>r.client_message_id).map(r=>[r.client_message_id,r]));d(()=>{const r=this.messageItem.messages,u=new Set(s.map(l=>l.id)),S=r.filter(l=>l.id===0?!1:l.id===this.helloMessage.id?s.length===0:!(l.client_message_id&&i.has(l.client_message_id)||u.has(l.id))),y=[...s.map(l=>{if(!l.client_message_id)return l;const g=r.find(O=>O.client_message_id===l.client_message_id);return(g==null?void 0:g.sendStatus)==="pending"||(g==null?void 0:g.sendStatus)==="failed"||(g==null?void 0:g.sendStatus)==="sent"?{...l,sendStatus:"sent"}:l}),...S];y.sort(this.sortMessagesByCreatedAt),this.messageItem.messages=y,this.messageItem.totalMessages=(t.data.totalMessages??s.length)+S.filter(l=>l.sendStatus==="pending").length}),await this.scrollMessages(),this.observeMessages()}addPendingUserMessage({text:e="",attachments:t=[],sendPayload:s=null}){const i=z();return this.pushMessage({id:i,client_message_id:i,text:e,user_id:window.user.id,user:window.user,created_at:f().toISOString(),attachments:t,sendStatus:"pending",isSending:!1,sendPayload:{...s,client_message_id:i}}),i}get pendingUserMessages(){var e;return(((e=this.messageItem)==null?void 0:e.messages)??[]).filter(t=>t.sendStatus==="pending")}setPendingSending(e,t){var i;if(!e)return;const s=(i=this.messageItem)==null?void 0:i.messages.find(n=>n.client_message_id===e);s&&(s.isSending=t)}confirmPendingMessage(e,t){var r;const s=(r=this.messageItem)==null?void 0:r.messages;if(!s)return;const i=s.findIndex(u=>u.client_message_id&&(u.client_message_id===e||u.client_message_id===t.client_message_id)),n={...t,sendStatus:"sent"};if(i===-1){this.pushMessage(n);return}this.messageItem.messages=s.map((u,S)=>
1S===i?n:u),this.sortMessages(),this.scrollMessages().then(()=>{this.observeMessages()})}removeMessage(e,t=null){let s=t??this.messageItem;s.messages=s.messages.filter(i=>i.id!==e),s.totalMessages--}sendVisibleMessages(e){let t=e.filter(s=>!this.sentMessages.includes(s));if(e.length===0||t.length===0)return!1;this.sentMessages=[...this.sentMessages,...t],h.axios.post("/chat-tickets/messages/read",{messagesId:t,userId:window.user.id}).then(s=>{const i=s.data.read_message_ids;this.messageItem.messages=this.messageItem.messages.map(n=>i.includes(n.id)?{...n,reader:window.user.id}:n),B.countUnreadMessages-=i.length}).catch(s=>{})}initObserver(){this.observer=new IntersectionObserver(e=>{e.forEach(t=>{const s=Number(t.target.dataset.id);t.isIntersecting?this.visibleMessages.add(s):this.visibleMessages.delete(s)}),this.sendVisibleMessages(Array.from(this.visibleMessages))},{root:null,rootMargin:"0px",threshold:.5})}observeMessages(){this.observer||this.initObserver(),this.observer.disconnect(),this.messageItem.messages.forEach(e=>{const t=document.getElementById(`message-${e.id}`);t&&e.id!==0&&e.reader===null&&e.user_id!==m.user.id&&!m.user.isSeniorOperator&&(!m.user.isOperator||e.ticket.operator_id===m.user.id)&&!(m.user.isOperator&&e.user_id===null)&&this.observer.observe(t)})}init(e,t,s=!0,i=!1){if(e.isFetched){i||this.scrollMessages();return}const n=window.location.hash.substring(1);if(this.messageItem=e,this.route=t,!s){this.messageItem.isFetched=!0;return}this.messageItem.isLoading=!0,this.fetchMessages(this.route).finally(()=>{d(()=>{this.messageItem.isLoading=!1,this.messageItem.isFetched=!0}),i||this.scrollMessages().then(()=>{n&&this.scrollToElement(`#chat-ticket-${n}`,".support-chat__messages-wrapper"),this.observeMessages()})})}}const c=v=new v,x=o=>new Promise(e=>setTimeout(e,o)),N=[1e3,3e3,5e3,7e3,1e4],w=1e4;function Y(o=[!1,w]){return Array.isArray(o)?{enabled:!!o[0],pause:o[1]??w}:typeof o=="object"&&o!==null?{enabled:!!o.enabled,pause:o.pause??w}:{enabled:!!o,pause:w}}async function E(o,e=N,t=()=>!0,s=[!1,w]){const{enabled:i,pause:n}=Y(s);for(let r=0;;r+=1)try{return await o()}catch(u){if(!t(u))throw u;if(r<e.length){await x(e[r]);continue}if(i){await x(n);continue}throw u}}function A(o){if(!o.response)return!0;const e=o.response.status;return e===408||e===429||e>=500}class j{constructor(){a(this,"defaultRoute","/chat-tickets");a(this,"messagesRoute",this.defaultRoute+"/messages");a(this,"isFetched",!1);a(this,"isWindowOpen",!1);a(this,"isLoading",!1);a(this,"wantsToSendMessage",!1);a(this,"isAudioRecording",!1);a(this,"isFlushingPending",!1);a(this,"pendingFlushPromise",null);a(this,"messages",[]);a(this,"input","");a(this,"operatorAvailable",!0);a(this,"activeChatTicket",null);a(this,"hideResizeButton",!1);a(this,"typingTimeoutId",null);a(this,"ratings",[{rate:1,text:"😠"},{rate:2,text:"😕"},{rate:3,text:"😐"},{rate:4,text:"🙂"},{rate:5,text:"😀"}]);a(this,"file",null);a(this,"client",null);a(this,"isExpanded",!1);a(this,"answerTicketId",-1);a(this,"WIDTH",400);a(this,"HEIGHT",650);a(this,"MAXWIDTH","60vw");a(this,"MAXHEIGHT","90vh");a(this,"rndEl",null);a(this,"mediaQuery",window.matchMedia("(max-width: 768px)"));a(this,"templates",{existingPhone:(e,t,s=null)=>`Здравствуйте! При заполнении данных для уведомления ответчика система показывает, что номер телефона уже зарегистрирован, но данные не совпадают. Прошу проверить информацию.
2
3Номер телефона ответчика: ${e}
4
5ФИО ответчика: ${t}`+(s?`
6
7Адрес места жительства ответчика: ${s}`:"")});this.mediaQuery.matches&&(this.hideResizeButton=!0),this.mediaQuery.addEventListener("change",e=>{this.hideResizeButton=e.matches}),window.addEventListener("load",()=>{const e=new URL(window.location.href);e.searchParams.get("show_chat")==="1"&&(this.toggleWindow(!0),e.searchParams.delete("show_chat"),window.history.replaceState({},document.title,e.pathname+e.search+e.hash))}),this.subscribeChannels=this.subscribeChannels.bind(this),T(this,{isFlushingPending:!1,pendingFlushPromise:!1,typingTimeoutId:!1,subscribeChannels:!1})}async loadChatTickets(){this.isLoading=!0;const t=(await h.axios.get(this.defaultRoute)).data.lastChatTicket;t?this.activeChatTicket=new p(t):this.activeChatTicket=new p({messages:[c.helloMessage]}),this.isLoading=!1,this.isFetched=!0}setAnswerTicketId(e){this.answerTicketId=parseInt(e)}async sendMessage(e,t=null){var s;e.preventDefault(),t===null&&(t=h.getForm(e,this.input)),t&&(c.addPendingUserMessage({text:this.input,attachments:[...c.filesList],sendPayload:{text:this.input,attachments:[...c.filesList],audio:t.get("audio"),chatTicketId:(s=this.activeChatTicket)==null?void 0:s.id,answerTicketId:this.answerTicketId}}),this.input="",c.filesList=[],await this.sendPendingMessages())}resolveChatTicketId(e={}){var s;const t=(s=this.activeChatTicket)==null?void 0:s.id;return t||e.chatTicketId||null}
7assignChatTicketIdToPending(e){e&&c.pendingUserMessages.forEach(t=>{t.sendPayload&&(t.sendPayload.chatTicketId=e)})}buildFormFromPayload(e){const t=new FormData;e.text&&t.append("text",e.text),(e.attachments??[]).forEach(i=>{i.defaultFileObject&&t.append("attachments[]",i.defaultFileObject)}),e.audio&&t.append("audio",e.audio);const s=this.resolveChatTicketId(e);return s&&t.append("chatTicketId",s),e.answerTicketId!==void 0&&e.answerTicketId!==-1&&t.append("answerTicketId",e.answerTicketId),e.client_message_id&&t.append("client_message_id",e.client_message_id),t}async postPendingMessage(e,t){c.setPendingSending(e,!0);try{e&&!t.has("client_message_id")&&t.append("client_message_id",e);const s=await E(()=>h.axios.post("/chat-tickets/message",t,{timeout:5e3}),[1e3,2e3,3e3],A);return d(()=>{var i;s.data.chatTicket.id!==((i=this.activeChatTicket)==null?void 0:i.id)&&(s.data.chatTicket.messageItem=this.activeChatTicket.messageItem,this.activeChatTicket=new p(s.data.chatTicket)),this.activeChatTicket.operator=s.data.operator,this.operatorAvailable=s.data.operatorAvailable,this.wantsToSendMessage=!1,s.data.message?c.confirmPendingMessage(e,s.data.message):c.setPendingSending(e,!1),this.assignChatTicketIdToPending(s.data.chatTicket.id),this.setAnswerTicketId(-1)}),s.data.message?{sent:!0,retryLater:!1}:(c.setPendingSending(e,!1),{sent:!1,retryLater:!1})}catch(s){return c.setPendingSending(e,!1),{sent:!1,retryLater:A(s)&&!h.isSocketConnected}}}async sendPendingMessages(){if(this.pendingFlushPromise)return this.pendingFlushPromise;const e=(async()=>{this.isFlushingPending=!0;try{for(;;){const t=c.pendingUserMessages.find(i=>i.sendPayload);if(!t)return;const s=await this.postPendingMessage(t.client_message_id,this.buildFormFromPayload(t.sendPayload));if(!s.sent){if(s.retryLater){t.sendStatus="pending";return}t.sendStatus="failed"}}}finally{this.isFlushingPending=!1}})();this.pendingFlushPromise=e;try{await e}finally{this.pendingFlushPromise===e&&(this.pendingFlushPromise=null)}}async syncMissedMessages(){await c.syncMissedMessages(this.messagesRoute)}async manageRecording(){this.isAudioRecording?await this.stopAudioRecording():await this.startAudioRecording()}async rateChatTicket(e){const t=await h.axios.post(`/chat-tickets/${this.activeChatTicket.id}/rate`,{rating:e});this.activeChatTicket.rating=t.data.chatTicket.rating}async startAudioRecording(){if(!navigator.mediaDevices){alert("Ваш браузер не поддерживает запись голосовых сообщений.");return}try{this.stream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{alert("Отсутствует доступ к микрофону");return}this.recorder=new window.MediaRecorder(this.stream),this.isAudioRecording=!0;let e=[];this.recorder.addEventListener("dataavailable",t=>e.push(t.data)),this.recorder.addEventListener("stop",async t=>{const s=new Blob(e,{type:"audio/mpeg"}),i=new FormData;e=[],i.append("audio",s),await this.sendMessage(t,i)}),this.recorder.start()}async stopAudioRecording(){this.recorder.stop(),this.isAudioRecording=!1,this.stream.getTracks().forEach(e=>e.stop())}reopen(){this.wantsToSendMessage=!0}setInputValue(e){this.input=e}toggleWindow(e=null){var t;(t=window.pvsMobileApp)!=null&&t.postMessage&&e!==!1||(this.isWindowOpen&&this.setAnswerTicketId(-1),this.isWindowOpen=e!==null?e:!this.isWindowOpen,document.body.classList.toggle("support-chat-open",this.isWindowOpen),this.mediaQuery.matches&&(document.body.style.overflow=this.isWindowOpen?"hidden":"auto"),!this.isFetched&&window.user&&this.loadChatTickets())}toggleExpand(){this.isExpanded=!this.isExpanded;let e={width:this.isExpanded?this.MAXWIDTH:this.WIDTH,height:this.isExpanded?this.MAXHEIGHT:this.HEIGHT};this.rndEl.updateSize(e)}closeChatTicket(){this.activeChatTicket.is_ticket_closed=!0}onResizeHandler(e,t,s){this.rndEl.updatePosition({x:0,y:0}),this.isExpanded=s.clientWidth!==this.WIDTH||s.clientHeight!==this.HEIGHT}init(){if(!window.user||this.isFetched)return!1;h.connectIntercept().then(()=>{h.startWebSocket(),h.registerChannelSubscriber(this.subscribeChannels),this.subscribeChannels(h.echo)})}subscribeChannels(e){!e||!window.user||(e.private(`support.${window.user.id}`).listen(".support.message.created",t=>
7{this.isFetched&&(this.operatorAvailable=!0,c.removeMessage(c.typingMessage.id),c.pushMessage(t.message))}),e.private(`support.${window.user.id}`).listen("ChatTicketClosed",t=>this.closeChatTicket(t.message)),e.private(`user.${window.user.id}`).listen("UserMessageCreated",t=>{c.pushMessage(t.message),!this.mediaQuery.matches&&!this.isWindowOpen&&this.toggleWindow()}).listen("OutgoingNotificationChatMessageCreated",t=>{c.pushMessage(t.message),!this.mediaQuery.matches&&!this.isWindowOpen&&this.toggleWindow()}),e.join(`support.user.${window.user.id}`).listenForWhisper("typing",t=>{c.pushMessage(c.typingMessage),clearTimeout(this.typingTimeoutId),this.typingTimeoutId=setTimeout(()=>{c.removeMessage(c.typingMessage.id)},15e3)}))}appendTemplate(e){this.setInputValue(e),this.isWindowOpen||this.toggleWindow()}}const M=C(j,"SupportStore");class V{constructor(){a(this,"connectionState",null);a(this,"connectionStatus",null);a(this,"isFirstConnection",!1);a(this,"pusher",null);a(this,"recreateTimeoutId",null);a(this,"restoredHideTimeoutId",null);a(this,"recoveryPromise",null);a(this,"handleStateChange",({current:e})=>{switch(d(()=>{this.connectionState=e}),e){case"connecting":case"unavailable":d(()=>{this.connectionStatus=this.isFirstConnection?"reconnecting":"connecting"});break;case"connected":if(clearTimeout(this.recreateTimeoutId),this.recreateTimeoutId=null,!this.isFirstConnection){d(()=>{this.isFirstConnection=!0,this.connectionStatus=null});break}this.runRecovery();break;case"failed":this.failedAction();break}});a(this,"handleBrowserOffline",()=>{this.isFirstConnection&&d(()=>{this.connectionStatus="reconnecting"})});T(this,{pusher:!1,recreateTimeoutId:!1,restoredHideTimeoutId:!1,recoveryPromise:!1,handleStateChange:!1,handleBrowserOffline:!1}),window.addEventListener("offline",this.handleBrowserOffline)}get connectionStatusLabel(){switch(this.connectionStatus){case"connecting":return"Подключение…";case"reconnecting":return"Восстанавливаем соединение…";case"restored":return"Соединение восстановлено";default:return null}}get isReconnecting(){return this.connectionStatus==="reconnecting"}get isConnectionRestored(){return this.connectionStatus==="restored"}bindClient(e){!(e!=null&&e.connection)||this.pusher===e||(this.unbindClient(),this.pusher=e,this.pusher.connection.bind("state_change",this.handleStateChange),this.handleStateChange({current:this.pusher.connection.state}))}unbindClient(){this.pusher&&(this.pusher.connection.unbind("state_change",this.handleStateChange),this.pusher=null)}failedAction(){this.recreateTimeoutId||(this.recreateTimeoutId=setTimeout(()=>{this.recreateTimeoutId=null,h.recreateWebSocket()},2e3))}runRecovery(){if(this.recoveryPromise)return this.recoveryPromise;const e=this.performRecovery();this.recoveryPromise=e;const t=()=>{this.recoveryPromise===e&&(this.recoveryPromise=null)};return e.then(t,t),e}async performRecovery(){try{await E(()=>M.syncMissedMessages(),[1e3,2e3,3e3,5e3],()=>!0)}catch(e){console.error("[chat] failed to sync missed messages",e),window.location.reload();return}d(()=>{this.connectionStatus="restored"}),M.sendPendingMessages().catch(e=>{console.error("[chat] failed to send pending messages",e)}),clearTimeout(this.restoredHideTimeoutId),this.restoredHideTimeoutId=setTimeout(()=>{d(()=>{this.connectionStatus==="restored"&&(this.connectionStatus=null)})},3e3)}}const k=C(V,"ChatConnectionStore");class G{constructor(){a(this,"timezone","Europe/Moscow");a(this,"client",null);a(this,"echo",null);a(this,"axios",null);a(this,"workingHours",{start:"04:00",end:"23:59"});a(this,"chatTicketItemMessagesRef",null);a(this,"channelSubscribers",[]);T(this,{chatTicketItemMessagesRef:b.ref,client:!1,echo:!1,axios:!1,channelSubscribers:!1})}get connectionStatus(){return k.connectionStatus}get connectionStatusLabel(){return k.connectionStatusLabel}get isReconnecting(){return k.isReconnecting}get isConnectionRestored(){return k.isConnectionRestored}get isSocketConnected(){var e,t;return((t=(e=this.client)==null?void 0:e.connection)==null?void 0:t.state)==="connected"}formatBytes(e,t=2){if(e===0)return"0 Bytes";const s=1024,i=t<0?0:t,n=["Байт","КБ","МБ","ГБ","ТБ"],r=Math.floor(Math.log(e)/Math.log(s));return parseFloat((e/Math.pow(s,r)).toFixed(i))+" "+n[r]}getForm(e,t){if(e.preventDefault(),t.length===0&&!c.hasFiles)return;const s=new FormData(e.target);return s.delete("attachments[]"),c.filesList.forEach(i=>
7{s.append("attachments[]",i.defaultFileObject)}),s}get isWorkingHours(){if(globalThis.globalVars.isTestEnv)return!0;const e=f().tz(this.timezone);return e.hour()>=parseInt(this.workingHours.start)&&e.hour()<=parseInt(this.workingHours.end)}getFormatedDateFromDB(e,t=null){let s=f(e);return s.isValid()?s.tz(this.timezone).format(t??"DD.MM.YYYY HH:mm"):null}get userHasChatTicket(){return!M.isLoading&&M.activeChatTicket&&M.activeChatTicket.id!==0}startWebSocket(){return this.client?this.client:(this.createWebSocketClient(),this.client)}registerChannelSubscriber(e){this.channelSubscribers.includes(e)||this.channelSubscribers.push(e)}resubscribeChannels(){this.echo&&this.channelSubscribers.forEach(e=>e(this.echo))}recreateWebSocket(){this.destroyWebSocketClient(),this.createWebSocketClient(),this.resubscribeChannels()}destroyWebSocketClient(){this.client&&(k.unbindClient(),this.client.disconnect(),this.client=null,this.echo=null)}createWebSocketClient(){this.client=new P("app",{cluster:"mt1",wsHost:window.location.hostname,wsPort:window.location.port,forceTLS:window.location.protocol==="https:",enabledTransports:["ws","wss"],disableStats:!0,pongTimeout:4e3,unavailableTimeout:5e3,authorizer:e=>({authorize:(t,s)=>{_.post("/broadcasting/auth",{socket_id:t,channel_name:e.name},{timeout:5e3,headers:{"X-CSRF-Token":document.querySelector('meta[name="csrf-token"]').getAttribute("content"),"X-Requested-With":"XMLHttpRequest"}}).then(i=>s(null,i.data)).catch(i=>s(i,{auth:""}))}})}),this.echo=new D({broadcaster:"reverb",client:this.client}),k.bindClient(this.client)}get Echo(){return this.echo}async connectIntercept(e){return this.axios?this.axios:(e==null&&(e=this),this.axios=await _.create({timeout:4e3}),this.axios.interceptors.request.use(t=>{const s=e.Echo.socketId();return s&&(t.headers["X-Socket-ID"]=s),t}),this.axios)}parseText(e){const t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"},s=/(https?:\/\/[^\s)]+)/g;return e.replace(/[&<>"']/g,i=>t[i]).replace(s,i=>`<a href="${i}" target="_blank" rel="noopener noreferrer">${i}</a>`).replace(/(?:\r\n|\r|\n)/g,"<br>")}get haveMobileAccess(){return!(W.isMobileDevice&&!m.user.isSeniorOperator)}get ratingValues(){return[...Array(5).keys()].map(e=>({label:(e+1).toString(),value:(e+1).toString()}))}}const h=C(G,"GlobalSupportStore"),ie="DD.MM.YYYY",q="YYYY-MM-DD",ae="DD MMMM YYYY",ne="HH:mm";class R{constructor(e,t=null){a(this,"messages",[]);a(this,"isLoading",!1);a(this,"loadingMessages",!1);a(this,"isFetched",!1);a(this,"groupField","created_at");T(this),this.messages=e,this.groupField=t??this.groupField}get groupedMessages(){let e={};return this.messages.forEach(t=>{if(t[this.groupField]===null)return!1;let s=this.groupField==="created_at"?f(t[this.groupField]).format(q):t[this.groupField];s in e||(e[s]=[]),e[s].push(t)}),e}}class p{constructor(e){a(this,"id",0);a(this,"rating",null);a(this,"operator",null);a(this,"closed_at",null);a(this,"created_at",null);a(this,"updated_at",null);a(this,"last_message",null);a(this,"is_ticket_closed",!1);a(this,"is_system",!1);a(this,"familiar",{operators:[]});a(this,"user",null);a(this,"messageItem",null);a(this,"isSelected",!1);a(this,"isTakingToWork",!1);a(this,"diffCreatedAt",0);T(this),Object.keys(this).forEach(t=>{Object.hasOwn(e,t)&&(t==="user"?this.user=new I(e[t]):t==="familiar"&&e[t]?this.familiar={...this.familiar,...e[t]}:this[t]=e[t])}),this.messageItem=e.messageItem??new R(e.messages)}get isReady(){var e;return this.isSelected&&!((e=this.messageItem)!=null&&e.isLoading)}get isTicketTakeToWork(){return!!this.operator}get isTicketCurrentOperator(){return this.isTicketTakeToWork&&this.operator&&this.operator.id===window.user.id}get canViewMessages(){return window.user.is_senior_operator||this.is_ticket_closed||this.isTicketTakeToWork||this.id===0}get isInputVisible(){return!this.is_ticket_closed&&!this.isTicketCurrentOperator?!1:!window.user.is_senior_operator&&this.canViewMessages&&(X.inputAvailableDirectly||this.isTicketTakeToWork&&this.isTicketCurrentOperator)}get canTakeToWork(){return this.operator===null}get hasFamiliarBadge(){var e,t;
7return!this.is_ticket_closed&&((t=(e=this.familiar)==null?void 0:e.operators)==null?void 0:t.length)>0}get familiarOperatorsNames(){var e;return(((e=this.familiar)==null?void 0:e.operators)??[]).map(t=>t.name).filter(Boolean).join(", ")}get formatedCreatedAt(){return h.getFormatedDateFromDB(this.created_at,"DD MMM YYYY HH:mm")}get createdAt(){return f(this.created_at)}get timer(){const e=Math.floor(this.diffCreatedAt/1e3),t=Math.floor(e/3600),s=Math.floor(e%3600/60),i=e%60;return{hours:t,minutes:s,seconds:i}}get isLateTime(){return this.isFirstLateTime||this.isSecondLateTime}get isFirstLateTime(){return this.timer.minutes>=15&&this.timer.hours<1}get isSecondLateTime(){return this.timer.hours>=1}setFields(e){Object.keys(e).forEach(t=>{Object.hasOwn(this,t)&&(t==="user"?this.user=new I(e[t]):t==="familiar"&&e[t]?this.familiar={...this.familiar,...e[t]}:this[t]=e[t])})}}class F{constructor(){a(this,"defaultRoute","/admin/chat-tickets");a(this,"chatTickets",[]);a(this,"isLoading",!0);a(this,"formSend",!1);a(this,"operators",[]);a(this,"isShiftActive",!1);a(this,"isShiftLoading",!1);a(this,"activeShiftId",null);a(this,"input","");a(this,"templateId",[]);a(this,"categories",[]);a(this,"interval",null);a(this,"newMessageAudio","/sounds/admin/for-sure-576.mp3");a(this,"ticketCloseTimeInMinutes",10);a(this,"oneUser",null);a(this,"inputAvailableDirectly",!1);a(this,"chatTicketItemWindowRef",null);a(this,"chatTicketItemMessagesRef",null);a(this,"pagination",null);a(this,"formik",null);a(this,"validationSchema",H().shape());a(this,"formState",{startDate:null,endDate:null});T(this,{chatTicketItemWindowRef:b.ref,chatTicketItemMessagesRef:b.ref})}clearFilterValues(){this.formik.resetForm()}startTimer(){this.chatTickets.length&&(this.chatTickets=this.chatTickets.map(e=>{var r;const t=f(),s=t.diff(e.createdAt,"minute")>=15;if(e.is_ticket_closed||(!s||e.isTicketTakeToWork)&&(!e.operator||e.last_message.user_id!==((r=e.operator)==null?void 0:r.id)))return e.diffCreatedAt=0,e;let n=f(e.last_message.created_at).tz(h.timezone).add(this.ticketCloseTimeInMinutes,"minute").diff(t);return s&&!e.isTicketTakeToWork&&(n=t.diff(e.createdAt)),e.diffCreatedAt=n<0?0:n,e}))}get selectedChatTicket(){return this.chatTickets.find(e=>e.isSelected)}get sortedChatTickets(){return this.chatTickets.slice().filter(e=>{var t,s,i;return((t=e.last_message)==null?void 0:t.message_reason)==="outgoing_notification"||((s=e.last_message)==null?void 0:s.user_id)!==null||this.oneUser&&((i=e.operator)==null?void 0:i.id)!==window.user.id}).sort((e,t)=>(e.is_ticket_closed&&t.createdAt.valueOf())-(t.is_ticket_closed&&e.createdAt.valueOf())||(e.createdAt.valueOf()&&!e.isTicketTakeToWork)-(t.createdAt.valueOf()&&!t.isTicketTakeToWork)||e.isTicketTakeToWork-t.isTicketTakeToWork)}async selectChatTicket(e){var t,s;if(!((t=e.messageItem)!=null&&t.isLoading)){if(e.messageItem=new R([],"ticket_id"),this.selectedChatTicket&&!window.user.is_senior_operator&&window.Echo.leave(`admin.support.chatTickets.${this.selectedChatTicket.id}.operators`),e.id===((s=this.selectedChatTicket)==null?void 0:s.id)){this.operators=[],e.isSelected=!1;return}this.selectedChatTicket&&(this.selectedChatTicket.isSelected=!1),d(()=>{this.input="",c.filesList=[]}),e.isSelected=!0}}get canSendMessage(){return(c.hasFiles||this.input.trim()!=="")&&!this.formSend}handleKeyDown(e){e.ctrlKey&&e.key==="Enter"&&(e.preventDefault(),e.target=e.target.closest("form"),this.sendMessage(e))}async sendMessage(e){var s,i,n;if(!this.canSendMessage)return;e.preventDefault();let t=h.getForm(e,this.input);this.templateId.length!==0&&this.templateId.forEach(r=>{t.append("template_id[]",r)}),this.inputAvailableDirectly&&t.append("inputAvailableDirectly",this.inputAvailableDirectly),t.append("chatTicketId",this.selectedChatTicket.id);try{this.formSend=!0;const r=await h.axios.post(`${this.defaultRoute}/${this.selectedChatTicket.user.id}/messages`,t);d(()=>{this.input="",this.templateId=[],this.formSend=!1,c.filesList=[]}),r.data.chatTicket.id!==((s=this.selectedChatTicket)==null?void 0:s.id)&&this.getChatTicketById(this.selectedChatTicket.id).setFields(r.data.chatTicket),this.pushMessage(r.data.message)}catch(r){alert(((n=(i=r.response)==null?void 0:i.data)==null?void 0:n.error)??"Произошла ошибка, попробуйте отправить сообщение ещё раз."),console.error(r)}}async takeToWork(e,t=null){m.user.isSeniorOperator||(e.isTakingToWork=!0);let s={};return t&&(s={operator_id:t}),h.axios.post(`${this.defaultRoute}/${e.id}/take-to-work`,s).then(({data:i})=>{if(i.error)throw new Error("Тикет взят в работу другим оператором.");d(()=>{m.user.isSeniorOperator||(e.isSelected=!0),this.addOrUpdateChatTicket(i.chatTicket),this.updateShift(i.shift)})}).catch(i=>{let n=i instanceof Error?i.message:"Возникла ошибка";throw alert(n),console.log(i),i})}updateShift(e){this.isShiftActive=e==null?void 0:e.is_active,this.activeShiftId=e==null?void 0:e.id}pushMessage(e){const t=this.getChatTicketById(e.ticket_id);t&&(t.last_message=e),this.selectedChatTicket&&this.selectedChatTicket.id===e.ticket_id&&c.pushMessage(e)}pushSystemMessage(e,t){let s=this.getChatTicketById(e.ticket_id);if(!s&&(t!=null&&t.user)){t={...t,messages:[],last_message:e};const i=this.chatTickets.find(n=>{var r;return((r=n.user)==null?void 0:r.id)===t.user.id});i?(i.setFields(t),s=i):(this.oneUser||!t.is_ticket_closed)&&(s=new p(t),this.chatTickets=[...this.chatTickets,s])}this.pushMessage(e)}playAudio(){try{new Audio(this.newMessageAudio).play()}catch(e){console.error(e)}}pushMessageWithAudio(e){this.playAudio(),this.pushMessage(e)}async setShiftActive(e){this.isShiftLoading=!0;try{let t=await h.axios.post(`${this.defaultRoute}/shift`,{is_shift_active:e?1:0});d(()=>{var s,i;this.isShiftActive=!!((s=t.data)!=null&&s.is_active),this.activeShiftId=((i=t.data)==null?void 0:i.id)??null})}catch(t){alert("Произошла ошибка. Попробуйте еще раз."),console.error(t)}finally{d(()=>{this.isShiftLoading=!1})}}get canTakeToWork(){return!window.user.is_senior_operator&&this.operators.every(e=>e.id===window.user.id)}async fetchShiftStatus(){return h.axios.get(`${this.defaultRoute}/shift`).then(({data:e})=>{d(()=>{this.isShiftActive=!!(e!=null&&e.is_active),this.activeShiftId=(e==null?void 0:e.id)??null})}).catch(e=>{console.error(e)})}async fetchPagination(e={},t=!1){let s={};if(this.formik)for(let[i,n]of Object.entries(this.formik.values))s[i]=i==="rating"&&n?n.value:n;return s.page=e.page?e.page:1,h.axios.get(`${this.defaultRoute}/get${this.oneUser?"/"+this.oneUser:""}`,{params:s}).then(i=>(this.pagination=i.data.chatTickets,t?i.data.chatTickets.data:i.data))}async fetchChatTickets(){this.isLoading=!0,await this.fetchPagination().then(e=>{e.chatTickets.data.length>0?this.chatTickets=e.chatTickets.data.map(t=>new p(t)):this.oneUser&&(this.chatTickets=[new p({messages:[],user:e.user})]),this.startTimer(),this.interval=setInterval(this.startTimer.bind(this),1e3),d(()=>{this.isLoading=!1})})}
7changeContent(e,t=!1){e=e.map(s=>new p(s)),t?this.chatTickets=[...this.chatTickets,...e]:this.chatTickets=e}addOrUpdateChatTicket(e){this.playAudio();let t=this.chatTickets.find(s=>s.user.id===e.user.id);if(t)t.setFields(e);else{if(!(e.operator===null||e.operator&&e.operator.id===window.user.id))return;this.chatTickets=[...this.chatTickets,new p(e)]}}deleteChatTicket(e){this.oneUser||(this.chatTickets=this.chatTickets.filter(t=>t.id!==e))}async closeChatTicket(e){await h.axios.post(`${this.defaultRoute}/${e}/close`).then(t=>{let s=this.getChatTicketById(t.data.chatTicket.id);s&&(s.is_ticket_closed=!0),this.oneUser||this.deleteChatTicket(t.data.chatTicket.id)})}getChatTicketById(e){return this.chatTickets.find(t=>t.id===e)}async startListenWebSocketEvents(){window.Echo.private("admin.support.chatTickets").listen("ChatTicketCreated",e=>this.addOrUpdateChatTicket(e.chatTicket)),window.user.is_senior_operator?(window.Echo.private("admin.support.senior_operators").listen(".support.message.created",e=>this.pushMessageWithAudio(e.message)).listen("OutgoingNotificationChatMessageCreated",e=>this.pushSystemMessage(e.message,e.chatTicket)).listen("ChatTicketClosed",e=>{this.getChatTicketById(e.chatTicket.id).is_ticket_closed=!0}),window.Echo.private("admin.support.chatTickets").listen("ChatTicketTakeToWork",e=>{let t=this.getChatTicketById(e.chatTicket.id);d(()=>{t.operator=e.chatTicket.operator,t.familiar=e.chatTicket.familiar})}),window.Echo.private(`admin.support.${window.user.id}`).listen(".support.message.created",e=>{this.selectedChatTicket.id===e.message.chatTicket.id&&this.pushMessageWithAudio(e.message)}).listen("OutgoingNotificationChatMessageCreated",e=>this.pushSystemMessage(e.message,e.chatTicket)).listen("ChatTicketCreated",e=>this.addOrUpdateChatTicket(e.chatTicket))):(window.Echo.private("admin.support.chatTickets").listen(".support.message.created",e=>this.pushMessage(e.message)).listen("OutgoingNotificationChatMessageCreated",e=>this.pushSystemMessage(e.message,e.chatTicket)).listen("ChatTicketTakeToWork",e=>{var i;let t=this.getChatTicketById(e.chatTicket.id);const s=(i=e.chatTicket.operator)==null?void 0:i.id;this.oneUser||(t&&s!==window.user.id?this.deleteChatTicket(e.chatTicket.id):this.addOrUpdateChatTicket(e.chatTicket))}),window.Echo.private(`admin.support.${window.user.id}`).listen(".support.message.created",e=>this.pushMessageWithAudio(e.message)).listen("OutgoingNotificationChatMessageCreated",e=>this.pushSystemMessage(e.message,e.chatTicket)).listen("ChatTicketCreated",e=>this.addOrUpdateChatTicket(e.chatTicket)).listen("ChatTicketClosed",e=>this.deleteChatTicket(e.chatTicket.id)).listen("ShiftUpdated",e=>this.updateShift(e.shift)))}handleChangeInput(e){this.input=e.target.value,window.Echo.join(`support.user.${this.selectedChatTicket.user.id}`).whisper("typing",{userId:this.selectedChatTicket.user.id})}init(e=null,t=!1){this.oneUser=e,this.inputAvailableDirectly=t,h.connectIntercept(window).then(()=>{let s=this.fetchChatTickets().then(this.startListenWebSocketEvents.bind(this));e&&s.then(()=>this.selectChatTicket(this.chatTickets[0])),this.fetchShiftStatus()})}}const X=F=new F;export{X as A,ie as D,ae as F,h as G,c as M,B as N,M as S,ne as T,R as a};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.