(()=>{"use strict";var e,t,n,r={27915(e,t,n){var r=n(5338),i=n(97665),s=n(20867),l=n(85015),a=n(22658),o=(n(62796),{token:{colorPrimary:"#1F2937",colorPrimaryHover:"#374151",colorPrimaryActive:"#111827",colorLink:"#1F2937",colorLinkHover:"#374151",colorText:"#1A1A1A",colorTextSecondary:"#6B7280",colorTextTertiary:"#9CA3AF",colorBorder:"#E5E7EB",colorBorderSecondary:"#F3F4F6",colorBgLayout:"#F9FAFB",colorBgContainer:"#FFFFFF",borderRadius:6,borderRadiusLG:12,fontFamily:'"Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:14,fontSizeHeading1:28,fontSizeHeading2:22,fontSizeHeading3:18,fontWeightStrong:500,controlHeight:36,controlHeightLG:42,paddingContentHorizontal:16},components:{Button:{fontWeight:500,primaryShadow:"none",defaultShadow:"none"},Layout:{headerBg:"#FFFFFF",siderBg:"#F9FAFB",bodyBg:"#F9FAFB",headerHeight:56,headerPadding:"0 24px"},Menu:{itemBg:"transparent",itemSelectedBg:"#F3F4F6",itemSelectedColor:"#1F2937",itemHoverBg:"#F3F4F6",itemHoverColor:"#1F2937",itemHeight:40,iconSize:16},Card:{headerFontSize:16,paddingLG:24},Input:{activeShadow:"0 0 0 2px rgba(31, 41, 55, 0.1)"},Form:{labelColor:"#6B7280",labelFontSize:13,verticalLabelPadding:"0 0 4px"}}}),c=new(n(37865).E)({defaultOptions:{queries:{staleTime:3e4,gcTime:3e5,retry:1,refetchOnWindowFocus:!0},mutations:{retry:0}}}),d=n(84976),u=n(47767),h=n(74637),y=n(677),m=n(97072),p=n(27197),g=n(79249),f=n(22395),x=n(71083),v={API_BASE_URL:null!=="https://cabinet.richat.ru/api"?"https://cabinet.richat.ru/api":"http://localhost:8003",APP_NAME:"RiChat",IS_DEV:!1,IS_PROD:!0};function j(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}var b=!1,A=[];function w(e){A.forEach(t=>t(e)),A=[]}var _=x.A.create({baseURL:v.API_BASE_URL,withCredentials:!0,timeout:3e4,headers:{"Content-Type":"application/json"}});_.interceptors.request.use(e=>{var t;return v.IS_DEV&&console.debug("[http]",null===(t=e.method)||void 0===t?void 0:t.toUpperCase(),e.url),e},e=>Promise.reject(e)),_.interceptors.response.use(e=>e,function(){var e,t=(e=function*(e){var t,n,r=e.config;if(!r||401!==(null===(t=e.response)||void 0===t?void 0:t.status)||r._retried)return Promise.reject(e);if(null!==(n=r.url)&&void 0!==n&&n.startsWith("/auth/"))return Promise.reject(e);if(r._retried=!0,b)return new Promise((t,n)=>{A.push(i=>{i?_(r).then(t).catch(n):n(e)})});b=!0;try{return yield _.post("/auth/refresh"),w(!0),_(r)}catch(e){return w(!1),"undefined"==typeof window||window.location.pathname.startsWith("/login")||window.location.assign("/login"),Promise.reject(e)}finally{b=!1}},function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){j(s,r,i,l,a,"next",e)}function a(e){j(s,r,i,l,a,"throw",e)}l(void 0)})});return function(e){return t.apply(this,arguments)}}());var S=n(53110);function F(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Что-то пошло не так";if(e instanceof S.pe){if(!e.response)return"ECONNABORTED"===e.code?"Сервер не отвечает. Попробуйте ещё раз.":"Нет связи с сервером. Проверьте подключение.";var n=e.response.data;if(null!=n&&n.detail){var r;if("string"==typeof n.detail)return n.detail;if(Array.isArray(n.detail)&&null!==(r=n.detail[0])&&void 0!==r&&r.msg)return n.detail[0].msg}return"Ошибка ".concat(e.response.status)}return e instanceof Error&&e.message||t}function T(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function I(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){T(s,r,i,l,a,"next",e)}function a(e){T(s,r,i,l,a,"throw",e)}l(void 0)})}}var k=e=>I(function*(){return(yield _.post("/assistants/",e)).data})(),C=(e,t)=>I(function*(){return(yield _.get("/assistants/".concat(e),{params:t?{include:t}:void 0})).data})(),z=(e,t)=>I(function*(){return(yield _.patch("/assistants/".concat(e),t)).data})(),B=e=>I(function*(){yield _.delete("/assistants/".concat(e))})(),E=n(33930),P=n(57097),O=n(81621),q=(0,O.vt)(e=>({user:null,isAuthenticated:!1,setUser:t=>e({user:t,isAuthenticated:!!t}),reset:()=>e({user:null,isAuthenticated:!1})})),L=n(96540);function R(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function D(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){R(s,r,i,l,a,"next",e)}function a(e){R(s,r,i,l,a,"throw",e)}l(void 0)})}}var W=()=>D(function*(){return(yield _.get("/user/",{params:{include:"assistants"}})).data})();function M(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function U(e,t,n){return(t=function(e){var t=function(e){if("object"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var n=t.call(e,"string");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var N={all:["user"],me:()=>[...N.all,"me"]};var K={all:["assistants"],detail:e=>[...K.all,"detail",e]};function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);nte(function*(){var t=new FormData;return t.append("assistant_id",e.assistant_id),t.append("file",e.file),(yield _.post("/knowledge/upload",t,{headers:{"Content-Type":void 0},timeout:3e5})).data})(),re=(e,t)=>te(function*(){return(yield _.post("/knowledge/sources/".concat(e,"/confirm"),t)).data})(),ie=e=>te(function*(){return(yield _.get("/knowledge/sources",{params:{assistant_id:e}})).data})(),se=e=>te(function*(){return(yield _.get("/knowledge/ingestion/".concat(e))).data})(),le=e=>te(function*(){yield _.delete("/sources/".concat(e))})(),ae=e=>te(function*(){return(yield _.post("/knowledge/scrape/estimate",e)).data})(),oe=e=>te(function*(){return(yield _.get("/knowledge/scrape/estimate/".concat(e))).data})(),ce=e=>te(function*(){return(yield _.post("/knowledge/scrape/confirm",e)).data})(),de=e=>te(function*(){return(yield _.get("/knowledge/scrape/".concat(e,"/progress"))).data})(),ue=e=>te(function*(){return(yield _.get("/knowledge/sources/".concat(e,"/billing-summary"))).data})(),he=e=>te(function*(){return(yield _.get("/knowledge/sources/".concat(e,"/pages"))).data})(),ye={all:["sources"],list:e=>[...ye.all,"list",e],ingestion:e=>[...ye.all,"ingestion",e],scrapeEstimate:e=>[...ye.all,"scrape","estimate",e],scrapeProgress:e=>[...ye.all,"scrape","progress",e],billingSummary:e=>[...ye.all,"billing-summary",e],pages:e=>[...ye.all,"pages",e]};function me(e){return(0,E.I)({queryKey:ye.list(null!=e?e:""),queryFn:()=>ie(e),enabled:!!e,staleTime:1e4})}function pe(e){return(0,E.I)({queryKey:ye.ingestion(null!=e?e:""),queryFn:()=>se(e),enabled:!!e,refetchInterval:e=>{var t,n=null===(t=e.state.data)||void 0===t?void 0:t.status;return n?!J(n)&&2e3:2e3},retry:(e,t)=>{var n,r=null===(n=t.response)||void 0===n?void 0:n.status;return 401!==r&&403!==r&&404!==r&&e<2}})}function ge(e){return(0,E.I)({queryKey:ye.scrapeProgress(null!=e?e:""),queryFn:()=>de(e),enabled:!!e,refetchInterval:e=>{var t=e.state.data;return t?"vision_done"!==t.vision_status&&"fail"!==t.source_status&&2500:2500},retry:(e,t)=>{var n,r=null===(n=t.response)||void 0===n?void 0:n.status;return 401!==r&&403!==r&&404!==r&&e<2},staleTime:0})}function fe(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return(0,E.I)({queryKey:ye.billingSummary(null!=e?e:""),queryFn:()=>ue(e),enabled:!!e&&t,staleTime:6e4,retry:(e,t)=>{var n,r=null===(n=t.response)||void 0===n?void 0:n.status;return 401!==r&&403!==r&&404!==r&&e<2}})}var xe=n(6754),ve=n(56914),je=n(74848),be=h.A.Text;function Ae(e){var t,n,r,i,s,l,a=e.source,o=e.isSelected,c=e.onSelect,d=!!(i=a.name)&&/^https?:\/\//i.test(i),u="in_queue"===a.status||"in_progress"===a.status||"pending_confirm"===a.status,h=pe(u?a.source_id:void 0).data,m=null!==(t=null==h?void 0:h.status)&&void 0!==t?t:a.status,p=ge(d&&u?a.source_id:void 0).data,g="success"===m||"partial_success"===m||"fail"===m,f=fe(a.source_id,g).data;return(0,je.jsx)(y.A,{size:"small",hoverable:!0,onClick:c,styles:{body:{padding:12}},style:{marginBottom:8,cursor:"pointer",borderColor:o?"#1677ff":void 0,borderWidth:o?2:1},children:(0,je.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:10},children:[(0,je.jsx)("div",{style:{flexShrink:0,color:"#1677ff",fontSize:16,marginTop:2},children:d?(0,je.jsx)(G.A,{}):(0,je.jsx)(Z.A,{})}),(0,je.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,je.jsx)("div",{style:{fontSize:13,color:"#1A1A1A",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginBottom:4},title:null!==(n=a.name)&&void 0!==n?n:"Без имени",children:null!==(r=a.name)&&void 0!==r?r:"Без имени"}),(0,je.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,je.jsx)(_e,{status:m}),(0,je.jsx)(be,{type:"secondary",style:{fontSize:11},children:(s=a.created_at,l=new Date(s),l.toLocaleString("ru-RU",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}))})]}),"in_progress"===m&&(0,je.jsx)(je.Fragment,{children:d&&p?(0,je.jsx)(we,{progress:p}):(0,je.jsx)(xe.A,{percent:50,size:"small",showInfo:!1,status:"active",style:{marginTop:6,marginBottom:0}})}),g&&f&&parseFloat(f.total_rub)>0&&(0,je.jsxs)(be,{type:"secondary",style:{fontSize:11,display:"block",marginTop:4},children:["Списано: ",parseFloat(f.total_rub).toFixed(2)," ₽"]})]})]})})}function we(e){var t=e.progress,n=function(e){if(null===e||e<60)return null;var t=Math.round(e/60);if(t<60)return"~".concat(t," мин");var n=Math.floor(t/60),r=t%60;return 0===r?"~".concat(n," ч"):"~".concat(n," ч ").concat(r," мин")}(t.eta_seconds);return(0,je.jsxs)("div",{style:{marginTop:6},children:[(0,je.jsx)(xe.A,{percent:t.pages_percent,size:"small",showInfo:!1,status:"active",style:{marginBottom:4}}),(0,je.jsxs)(be,{type:"secondary",style:{fontSize:11},children:[t.pages_done," / ",t.pages_total," страниц",t.images_done>0&&(0,je.jsxs)(je.Fragment,{children:[" · ",t.images_done," картинок"]}),n&&(0,je.jsxs)(je.Fragment,{children:[" · ",n]})]})]})}function _e(e){var t=e.status,n=Se[t];return(0,je.jsx)(ve.A,{color:n.color,bordered:!1,style:{fontSize:11,margin:0},children:n.label})}var Se={pending_confirm:{label:"Ждёт подтверждения",color:"default"},in_queue:{label:"В очереди",color:"default"},in_progress:{label:"Обработка...",color:"blue"},success:{label:"Готов",color:"success"},partial_success:{label:"Частично",color:"warning"},fail:{label:"Ошибка",color:"error"}},Fe=h.A.Text;function Te(e){var t=e.assistantId,n=e.selectedSourceId,r=e.onSelectSource,i=e.onAddDocument,s=e.onAddSite,l=me(t),a=l.data,o=l.isLoading,c=l.error,d=[{key:"document",icon:(0,je.jsx)(Z.A,{}),label:"Документ",onClick:i},{key:"site",icon:(0,je.jsx)(G.A,{}),label:"Сайт",onClick:s}];return(0,je.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,je.jsx)("div",{style:{marginBottom:12},children:(0,je.jsx)(Q.A,{menu:{items:d},trigger:["click"],children:(0,je.jsxs)(g.Ay,{type:"primary",icon:(0,je.jsx)($.A,{}),block:!0,children:["Добавить источник ",(0,je.jsx)(V.A,{})]})})}),(0,je.jsxs)("div",{style:{flex:1,overflowY:"auto",minHeight:0},children:[o&&(0,je.jsx)(m.A,{active:!0,paragraph:{rows:2}}),c&&(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:"Не удалось загрузить список",description:F(c)}),a&&0===a.length&&!o&&(0,je.jsx)(X.A,{image:X.A.PRESENTED_IMAGE_SIMPLE,description:(0,je.jsx)(Fe,{type:"secondary",style:{fontSize:12},children:"Пока пусто"}),style:{marginTop:24}}),a&&a.length>0&&(0,je.jsx)("div",{children:a.map(e=>(0,je.jsx)(Ae,{source:e,isSelected:e.source_id===n,onSelect:()=>r(e.source_id)},e.source_id))})]})]})}var Ie=h.A.Title,ke=h.A.Text;function Ce(e){var t=e.onAddDocument,n=e.onAddSite;return(0,je.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:(0,je.jsxs)("div",{style:{textAlign:"center",maxWidth:480},children:[(0,je.jsx)(Ie,{level:4,style:{marginBottom:8},children:"База знаний ассистента"}),(0,je.jsx)(ke,{type:"secondary",style:{display:"block",marginBottom:32},children:"Загрузите документы или подключите сайт, чтобы ассистент использовал эту информацию при ответах. Выберите источник слева для просмотра деталей."}),(0,je.jsxs)("div",{style:{display:"flex",gap:16,justifyContent:"center",flexWrap:"wrap"},children:[(0,je.jsx)(g.Ay,{size:"large",icon:(0,je.jsx)(Z.A,{}),onClick:t,style:{minWidth:200},children:"Добавить документ"}),(0,je.jsx)(g.Ay,{size:"large",type:"primary",icon:(0,je.jsx)(G.A,{}),onClick:n,style:{minWidth:200},children:"Подключить сайт"})]})]})})}var ze=n(36207),Be=n(49222),Ee=n(63496),Pe=n(29029),Oe=n(15039);function qe(e){var t=e.toLocaleString("ru-RU",{minimumFractionDigits:0,maximumFractionDigits:2});return"".concat(t," ₽")}var Le=h.A.Text;function Re(e){var t,n,r,i,s=e.estimate,l=e.processImages,a=e.onProcessImagesChange,o=l?s.estimated_cost_with_vision_rub:s.estimated_cost_without_vision_rub,c=l?s.estimated_cost_without_vision_rub:s.estimated_cost_with_vision_rub,d=o>s.current_balance_rub,u=s.images_count>0;return(0,je.jsxs)(y.A,{size:"small",styles:{body:{padding:16}},children:[(0,je.jsxs)("div",{style:{marginBottom:12},children:[(0,je.jsx)(Le,{strong:!0,children:null!==(t=s.file_name)&&void 0!==t?t:"Файл"}),(0,je.jsx)("div",{children:(0,je.jsxs)(Le,{type:"secondary",style:{fontSize:12},children:[s.page_count," ",(n=s.page_count,r=n%10,i=n%100,i>=11&&i<=14?"страниц":1===r?"страница":r>=2&&r<=4?"страницы":"страниц"),u&&", ".concat(s.images_count," ").concat(De(s.images_count))]})})]}),u&&(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"10px 12px",background:"#F9FAFB",borderRadius:6,marginBottom:12},children:[(0,je.jsxs)("div",{children:[(0,je.jsx)("div",{style:{fontSize:13,color:"#1A1A1A"},children:"Обрабатывать картинки"}),(0,je.jsx)(Le,{type:"secondary",style:{fontSize:11},children:"Vision разберёт изображения в документе"})]}),(0,je.jsx)(Oe.A,{checked:l,onChange:a})]}),(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:4},children:[(0,je.jsx)(Le,{type:"secondary",style:{fontSize:13},children:"К списанию"}),(0,je.jsx)(Le,{strong:!0,style:{fontSize:18},children:qe(o)})]}),u&&(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:8},children:[(0,je.jsx)(Le,{type:"secondary",style:{fontSize:12},children:l?"Без обработки картинок":"С обработкой картинок"}),(0,je.jsx)(Le,{type:"secondary",style:{fontSize:12},children:qe(c)})]}),(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",paddingTop:8,borderTop:"1px solid #F3F4F6"},children:[(0,je.jsx)(Le,{type:"secondary",style:{fontSize:12},children:"Баланс"}),(0,je.jsx)(Le,{type:"secondary",style:{fontSize:12},children:qe(s.current_balance_rub)})]}),d&&(0,je.jsx)(p.A,{type:"info",showIcon:!0,message:"Спишется при пополнении баланса",description:"Документ обработается сейчас. Стоимость спишется с баланса ассистента — пополните его перед публикацией в каналах.",style:{marginTop:12}})]})}function De(e){var t=e%10,n=e%100;return n>=11&&n<=14?"картинок":1===t?"картинка":t>=2&&t<=4?"картинки":"картинок"}function We(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function Me(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){We(s,r,i,l,a,"next",e)}function a(e){We(s,r,i,l,a,"throw",e)}l(void 0)})}}function Ue(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,l,a=[],o=!0,c=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;o=!1}else for(;!(o=(r=s.call(n)).done)&&(a.push(r.value),a.length!==t);o=!0);}catch(e){c=!0,i=e}finally{try{if(!o&&null!=n.return&&(l=n.return(),Object(l)!==l))return}finally{if(c)throw i}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ne(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ne(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Ne(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);nne(e)}),h=function(e){var t=(0,i.jE)();return(0,P.n)({mutationFn:e=>{var t=e.sourceId,n=e.process_images;return re(t,{process_images:n})},onSuccess:()=>{t.invalidateQueries({queryKey:ye.list(e)})}})}(n);(0,L.useEffect)(()=>{t&&(a(null),d(!0),u.reset(),h.reset())},[t]);var y=function(){var e=Me(function*(e){try{var t=yield u.mutateAsync({assistant_id:n,file:e});a(t)}catch(e){}});return function(t){return e.apply(this,arguments)}}(),m=function(){var e=Me(function*(){if(l)try{yield h.mutateAsync({sourceId:l.source_id,process_images:c}),r()}catch(e){}});return function(){return e.apply(this,arguments)}}(),f=u.error?F(u.error):null,x=h.error?F(h.error):null,v=u.isPending,j=h.isPending;return(0,je.jsxs)(Be.A,{open:t,title:"Загрузить документ",onCancel:r,destroyOnClose:!0,width:520,footer:l?[(0,je.jsx)(g.Ay,{onClick:()=>{a(null),u.reset()},disabled:j,children:"Выбрать другой файл"},"back"),(0,je.jsx)(g.Ay,{type:"primary",onClick:m,loading:j,children:"Подтвердить и обработать"},"confirm")]:[(0,je.jsx)(g.Ay,{onClick:r,children:"Отмена"},"cancel")],children:[!l&&!v&&(0,je.jsxs)(je.Fragment,{children:[(0,je.jsxs)(Ee.A.Dragger,{accept:".pdf,.docx,.pptx,.xlsx,.txt",multiple:!1,showUploadList:!1,beforeUpload:e=>(y(e),!1),disabled:v,children:[(0,je.jsx)("p",{style:{fontSize:14,marginBottom:8},children:"Перетащите файл сюда или нажмите для выбора"}),(0,je.jsx)(Ke,{type:"secondary",style:{fontSize:12},children:"PDF, DOCX, PPTX, XLSX, TXT — до 100 МБ"})]}),f&&(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:f,style:{marginTop:12}})]}),v&&(0,je.jsxs)("div",{style:{textAlign:"center",padding:"40px 0"},children:[(0,je.jsx)(Pe.A,{size:"large"}),(0,je.jsx)("div",{style:{marginTop:12},children:(0,je.jsx)(Ke,{type:"secondary",children:"Анализируем файл..."})})]}),l&&(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(Re,{estimate:l,processImages:c,onProcessImagesChange:d}),x&&(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:x,style:{marginTop:12}})]})]})}function Qe(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{a(!0)},[]),(0,je.jsxs)("div",{style:{padding:24},children:[(0,je.jsx)(g.Ay,{type:"text",icon:(0,je.jsx)(ze.A,{}),onClick:i,style:{marginBottom:16},children:"Назад"}),(0,je.jsx)(Xe,{level:4,style:{marginTop:0},children:"Загрузка документа"}),(0,je.jsx)(Ze,{type:"secondary",children:"Поддерживаются PDF, DOCX, PPTX, XLSX, TXT — до 100 МБ каждый."}),(0,je.jsx)(He,{open:l,assistantId:r,onClose:()=>{a(!1),i()}})]})}var $e=n(53691),Ve=n(87959),Ye=n(29957),Je=n(91196),et=n(93567),tt=n(71295),nt=n(52629);function rt(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,l,a=[],o=!0,c=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;o=!1}else for(;!(o=(r=s.call(n)).done)&&(a.push(r.value),a.length!==t);o=!0);}catch(e){c=!0,i=e}finally{try{if(!o&&null!=n.return&&(l=n.return(),Object(l)!==l))return}finally{if(c)throw i}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return it(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?it(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function it(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);nae(e),onSuccess:()=>{t.invalidateQueries({queryKey:ye.list(e)})}})}(n),u=function(e){var t=(0,i.jE)();return(0,P.n)({mutationFn:e=>ce(e),onSuccess:()=>{t.invalidateQueries({queryKey:ye.list(e)})}})}(n),h="scanning"===a.kind||"ready"===a.kind||"failed"===a.kind?a.sourceId:void 0,y=(t=h,(0,E.I)({queryKey:ye.scrapeEstimate(null!=t?t:""),queryFn:()=>oe(t),enabled:!!t,refetchInterval:e=>{var t,n=null===(t=e.state.data)||void 0===t?void 0:t.status;return(!n||"in_progress"===n)&&2500},retry:(e,t)=>{var n,r=null===(n=t.response)||void 0===n?void 0:n.status;return 401!==r&&403!==r&&404!==r&&e<2},staleTime:0})),m=y.data,f=y.error;(0,L.useEffect)(()=>{m&&"form"!==a.kind&&("ready"===m.status&&"ready"!==a.kind?o({kind:"ready",sourceId:m.source_id}):"failed"===m.status&&"failed"!==a.kind&&o({kind:"failed",sourceId:m.source_id}))},[m,a]),(0,L.useEffect)(()=>{if("scanning"===a.kind){var e=window.setTimeout(()=>{Ve.Ay.error("Сканирование занимает слишком много времени. Попробуйте позже."),o({kind:"form"})},3e5);return()=>window.clearTimeout(e)}},[a.kind]);var x=()=>{c.resetFields(),o({kind:"form"})};return(0,je.jsxs)("div",{style:{padding:24},children:[(0,je.jsx)(g.Ay,{type:"text",icon:(0,je.jsx)(ze.A,{}),onClick:"form"===a.kind?r:x,style:{marginBottom:16},children:"Назад"}),(0,je.jsxs)(st,{level:4,style:{marginTop:0},children:[(0,je.jsx)(G.A,{style:{marginRight:8,color:"#1677ff"}}),"Подключить сайт"]}),"form"===a.kind&&(0,je.jsx)(ct,{form:c,onSubmit:e=>{var t=function(e){var t=e.trim();return t&&/^https:\/\/[^/]+/.test(t)?/^https:\/\/[^/]+$/.test(t)?t+"/":t:null}(e.url);t?d.mutate({assistant_id:n,url:t,process_images:e.process_images},{onSuccess:e=>{o({kind:"scanning",sourceId:e.source_id})}}):Ve.Ay.error("Введите валидный URL начиная с https://")},submitting:d.isPending,submitError:d.error}),"scanning"===a.kind&&(0,je.jsx)(dt,{}),"ready"===a.kind&&"ready"===(null==m?void 0:m.status)&&(0,je.jsx)(ut,{estimate:m,onConfirm:()=>{"ready"===a.kind&&u.mutate({source_id:a.sourceId},{onSuccess:()=>{Ve.Ay.success("Парсинг запущен — следите за прогрессом."),s(a.sourceId)}})},confirming:u.isPending,confirmError:u.error}),"failed"===a.kind&&"failed"===(null==m?void 0:m.status)&&(0,je.jsx)(yt,{errorReason:m.error_reason,errorText:m.error,onRetry:x}),f&&"form"!==a.kind&&"failed"!==a.kind&&(0,je.jsx)(p.A,{type:"error",showIcon:!0,style:{marginTop:16},message:"Не удалось получить статус сканирования",description:F(f)})]})}function ct(e){var t=e.form,n=e.onSubmit,r=e.submitting,i=e.submitError;return(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(lt,{type:"secondary",style:{display:"block",marginBottom:24},children:"Введите адрес сайта — мы найдём sitemap.xml, посчитаем страницы и картинки, покажем сколько это будет стоить. До подтверждения деньги не списываются."}),(0,je.jsxs)($e.A,{form:t,layout:"vertical",requiredMark:!1,initialValues:{process_images:!0},onFinish:n,style:{maxWidth:540},children:[(0,je.jsx)($e.A.Item,{label:"URL сайта",name:"url",rules:[{required:!0,message:"Введите URL"},{pattern:/^https:\/\/.+/,message:"Адрес должен начинаться с https://"}],children:(0,je.jsx)(Ye.A,{placeholder:"https://example.com/",size:"large",autoComplete:"off",spellCheck:!1})}),(0,je.jsx)($e.A.Item,{name:"process_images",valuePropName:"checked",style:{marginBottom:8},children:(0,je.jsxs)(Je.A,{children:["Обрабатывать картинки на страницах",(0,je.jsx)(lt,{type:"secondary",style:{display:"block",fontSize:12,marginTop:2},children:"Ассистент сможет учитывать содержимое картинок в ответах. Существенно увеличивает стоимость, но даёт качественные ответы по визуальному контенту."})]})}),i&&(0,je.jsx)(p.A,{type:"error",showIcon:!0,style:{marginTop:16,marginBottom:16},message:"Не удалось запустить сканирование",description:F(i)}),(0,je.jsx)($e.A.Item,{style:{marginTop:16,marginBottom:0},children:(0,je.jsx)(g.Ay,{type:"primary",htmlType:"submit",loading:r,size:"large",children:"Сканировать"})})]}),(0,je.jsx)(p.A,{type:"info",showIcon:!0,style:{marginTop:24,maxWidth:540},message:"Что важно знать",description:(0,je.jsxs)("ul",{style:{marginBottom:0,paddingLeft:18},children:[(0,je.jsx)("li",{children:"Поддерживаются только сайты с sitemap.xml"}),(0,je.jsx)("li",{children:"За один запуск обрабатывается до 200 страниц"}),(0,je.jsx)("li",{children:"Сканирование (без оплаты) занимает 1–3 минуты"})]})})]})}function dt(){return(0,je.jsxs)("div",{style:{textAlign:"center",padding:"48px 24px"},children:[(0,je.jsx)(Pe.A,{indicator:(0,je.jsx)(et.A,{style:{fontSize:40},spin:!0}),style:{marginBottom:16}}),(0,je.jsx)(st,{level:5,style:{marginTop:16,marginBottom:8},children:"Сканируем sitemap..."}),(0,je.jsx)(lt,{type:"secondary",children:"Это может занять 1–3 минуты. Можно закрыть страницу — сканирование продолжится в фоне."})]})}function ut(e){var t,n,r,i,s=e.estimate,l=e.onConfirm,a=e.confirming,o=e.confirmError,c=parseFloat(s.current_balance_rub)-parseFloat(s.estimated_cost_total_rub),d=c<0;return(0,je.jsxs)(je.Fragment,{children:[(0,je.jsxs)(y.A,{size:"small",style:{marginBottom:16,maxWidth:540},title:(0,je.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,je.jsx)(tt.A,{style:{color:"#52c41a"}}),(0,je.jsx)("span",{children:"Сайт проанализирован"})]}),children:[(0,je.jsxs)("div",{style:{marginBottom:12},children:[(0,je.jsx)(lt,{strong:!0,style:{display:"block",fontSize:14},children:null!==(t=s.site_title)&&void 0!==t?t:s.url}),(0,je.jsx)(lt,{type:"secondary",style:{fontSize:12},children:s.url})]}),(0,je.jsx)(ht,{label:"Страниц в sitemap:",value:String(s.total_pages_in_sitemap)}),(0,je.jsx)(ht,{label:"Будет обработано:",value:"".concat(s.pages_to_process," страниц"),highlight:s.too_large}),(0,je.jsx)(ht,{label:"Картинок (примерно):",value:s.process_images?"~".concat(s.estimated_total_images):"не обрабатываются"}),(0,je.jsxs)("div",{style:{borderTop:"1px solid #f0f0f0",marginTop:12,paddingTop:12},children:[(0,je.jsx)(ht,{label:"Текст:",value:"".concat(gt(s.estimated_cost_text_rub)," ₽")}),s.process_images&&(0,je.jsx)(ht,{label:"Картинки:",value:"до ".concat(gt(s.estimated_cost_images_rub)," ₽")}),(0,je.jsx)(ht,{label:"Итого:",value:"до ".concat(gt(s.estimated_cost_total_rub)," ₽"),bold:!0})]}),(0,je.jsxs)("div",{style:{borderTop:"1px solid #f0f0f0",marginTop:12,paddingTop:12},children:[(0,je.jsx)(ht,{label:"Баланс ассистента:",value:"".concat(gt(s.current_balance_rub)," ₽")}),(0,je.jsx)(ht,{label:"После обработки:",value:"".concat(c.toFixed(2)," ₽")})]})]}),s.too_large&&s.contacts&&(0,je.jsx)(mt,{contacts:s.contacts}),d&&(0,je.jsx)(p.A,{type:"info",showIcon:!0,style:{marginBottom:16,maxWidth:540},message:"Спишется при пополнении баланса",description:"Сайт обработается сейчас. Стоимость спишется с баланса ассистента — пополните его перед публикацией в каналах."}),o&&(0,je.jsx)(p.A,{type:"error",showIcon:!0,style:{marginBottom:16,maxWidth:540},message:"Не удалось подтвердить парсинг",description:(n=o,i=null===(r=n.response)||void 0===r?void 0:r.status,402===i?"Недостаточно средств на балансе ассистента. Пополните баланс через поддержку.":410===i?"Срок действия превью истёк. Закройте эту форму и пересканируйте сайт.":400===i?"Парсинг этого сайта уже запускался. Проверьте список источников слева.":F(n))}),(0,je.jsx)(g.Ay,{type:"primary",size:"large",onClick:l,loading:a,children:"Подтвердить и запустить парсинг"})]})}function ht(e){var t=e.label,n=e.value,r=e.bold,i=e.highlight,s=e.error;return(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",padding:"4px 0",fontSize:13},children:[(0,je.jsx)(lt,{type:"secondary",style:{fontSize:13},children:t}),(0,je.jsx)(lt,{strong:r,style:{fontSize:13,color:s?"#ff4d4f":i?"#fa8c16":void 0},children:n})]})}function yt(e){var t,n=e.errorReason,r=e.errorText,i=e.onRetry,s=null!==(t=pt[n])&&void 0!==t?t:r,l="no_sitemap"!==n;return(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)(p.A,{type:"error",showIcon:!0,icon:(0,je.jsx)(nt.A,{}),message:"Не удалось обработать сайт",description:s,style:{marginBottom:16,maxWidth:540}}),"no_sitemap"===n&&(0,je.jsx)(p.A,{type:"info",showIcon:!0,style:{marginBottom:16,maxWidth:540},message:"Что можно сделать",description:(0,je.jsxs)("span",{children:["Загрузите документы (PDF, DOCX, PPTX, XLSX, TXT) — ассистент будет работать на их основе. Если нужна обработка такого сайта, свяжитесь с продажами в Telegram:"," ",(0,je.jsx)(at,{href:"https://t.me/RiChat_sales",target:"_blank",children:"@RiChat_sales"})]})}),(0,je.jsx)(g.Ay,{onClick:i,type:l?"primary":"default",children:l?"Попробовать другой сайт":"Назад"})]})}function mt(e){var t,n=e.contacts;return(0,je.jsx)(p.A,{type:"warning",showIcon:!0,style:{marginBottom:16,maxWidth:540},message:"Сайт большой — обработаем только первые 200 страниц",description:(0,je.jsxs)("span",{children:[null!==(t=n.message)&&void 0!==t?t:"Для полной обработки сайта свяжитесь с отделом продаж.",(0,je.jsx)("br",{}),(0,je.jsx)(at,{href:n.telegram,target:"_blank",rel:"noopener",children:"Связаться в Telegram"}),n.email&&(0,je.jsxs)(je.Fragment,{children:[" · ",(0,je.jsx)(at,{href:"mailto:".concat(n.email),children:n.email})]})]})})}var pt={no_sitemap:"У сайта нет sitemap.xml — мы не сможем его обработать через парсер. Загрузите документы или обратитесь в отдел продаж для индивидуальной настройки.",cloudflare_blocked:"Сайт блокирует наш парсер защитой Cloudflare. Попробуйте ещё раз через несколько минут или обратитесь в отдел продаж.",invalid_url:"Неверный URL. Проверьте что адрес начинается с https:// и сайт доступен.",timeout:"Сайт слишком долго отвечает. Попробуйте ещё раз через несколько минут.",internal_error:"Не удалось обработать сайт из-за внутренней ошибки. Попробуйте ещё раз или обратитесь в поддержку."};function gt(e){return parseFloat(e).toFixed(2)}var ft=n(76511),xt=n(55957),vt=n(42652),jt=n(59102),bt=n(16044);function At(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function wt(e){var t=e.sourceId,n=e.sourceName,r=e.assistantId,s=l.A.useApp().message,a=function(e){var t=(0,i.jE)();return(0,P.n)({mutationFn:e=>le(e),onSuccess:(n,r)=>{t.removeQueries({queryKey:ye.ingestion(r)}),t.removeQueries({queryKey:ye.pages(r)}),t.invalidateQueries({queryKey:ye.list(e)})}})}(r),o=function(){var e,r=(e=function*(){try{yield a.mutateAsync(t),s.success(n?"«".concat(n,"» удалён"):"Документ удалён")}catch(e){s.error(F(e))}},function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){At(s,r,i,l,a,"next",e)}function a(e){At(s,r,i,l,a,"throw",e)}l(void 0)})});return function(){return r.apply(this,arguments)}}();return(0,je.jsx)(bt.A,{title:"Удалить документ?",description:"Удалятся также все извлечённые из него фрагменты. Действие необратимо.",okText:"Удалить",cancelText:"Отмена",okButtonProps:{danger:!0,loading:a.isPending},onConfirm:o,placement:"topRight",children:(0,je.jsx)(g.Ay,{size:"small",type:"text",danger:!0,children:"Удалить"})})}var _t=h.A.Title,St=h.A.Text;function Ft(e){var t,n,r,i,s,l=e.assistantId,a=e.sourceId,o=e.onSourceGone,c=me(l),d=c.data,u=c.isLoading,h=null==d?void 0:d.find(e=>e.source_id===a),m="in_queue"===(null==h?void 0:h.status)||"in_progress"===(null==h?void 0:h.status)||"pending_confirm"===(null==h?void 0:h.status),g=pe(m?a:void 0).data,f=!!(s=null!==(t=null==h?void 0:h.name)&&void 0!==t?t:null)&&/^https?:\/\//i.test(s),x=null!==(n=null==g?void 0:g.status)&&void 0!==n?n:null==h?void 0:h.status,v=ge(f&&m?a:void 0).data,j=function(e,t){return(0,E.I)({queryKey:ye.pages(null!=e?e:""),queryFn:()=>he(e),enabled:!!e,refetchInterval:()=>t?!J(t)&&3e3:3e3,retry:(e,t)=>{var n,r=null===(n=t.response)||void 0===n?void 0:n.status;return 401!==r&&403!==r&&404!==r&&e<2},staleTime:0})}(f?a:void 0,x),b=j.data,A=!!x&&J(x),w=fe(a,A).data,_=(0,L.useRef)(null);return(0,L.useEffect)(()=>{if(x&&h&&_.current!==x){var e,t=_.current;_.current=x,null!==t&&(J(t)||"success"!==x?J(t)||"partial_success"!==x?J(t)||"fail"!==x||ft.Ay.error({message:"Не удалось обработать источник",description:"Попробуйте загрузить снова или свяжитесь с поддержкой.",placement:"topRight",duration:8}):ft.Ay.warning({message:"Источник обработан с замечаниями",description:"Часть страниц не удалось обработать. Ассистент использует то, что есть.",placement:"topRight",duration:6}):ft.Ay.success({message:"Источник обработан",description:f?"Сайт ".concat(null!==(e=h.name)&&void 0!==e?e:"успешно"," обработан и используется ассистентом при ответах."):"Документ обработан и используется ассистентом при ответах.",placement:"topRight",duration:6}))}},[x,h,f]),(0,L.useEffect)(()=>{u||!d||h||o()},[u,d,h,o]),h&&x?(0,je.jsxs)("div",{style:{padding:24},children:[(0,je.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:12,marginBottom:24},children:[(0,je.jsx)("div",{style:{flexShrink:0,color:"#1677ff",fontSize:24,marginTop:2},children:f?(0,je.jsx)(G.A,{}):(0,je.jsx)(Z.A,{})}),(0,je.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,je.jsx)(_t,{level:4,style:{marginTop:0,marginBottom:4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:null!==(r=h.name)&&void 0!==r?r:"Без имени",children:null!==(i=h.name)&&void 0!==i?i:"Без имени"}),(0,je.jsxs)(St,{type:"secondary",style:{fontSize:12},children:[f?"Сайт":"Документ"," · добавлено ",Bt(h.created_at)]})]}),(0,je.jsx)(wt,{sourceId:h.source_id,sourceName:h.name,assistantId:l})]}),(0,je.jsx)(y.A,{size:"small",style:{marginBottom:16},children:(0,je.jsxs)(xt.A,{column:1,size:"small",labelStyle:{fontSize:12,color:"#8c8c8c",width:140},contentStyle:{fontSize:13},children:[(0,je.jsx)(xt.A.Item,{label:"Статус",children:(0,je.jsx)(Ct,{status:x})}),(0,je.jsx)(xt.A.Item,{label:"Обработка картинок",children:h.process_images?"Включена":"Выключена"}),h.confirm_expires_at&&"pending_confirm"===x&&(0,je.jsx)(xt.A.Item,{label:"Подтвердить до",children:Bt(h.confirm_expires_at)})]})}),"in_progress"===x&&f&&v&&(0,je.jsx)(Tt,{progress:v}),"in_progress"===x&&(!f||!v)&&(0,je.jsx)(p.A,{type:"info",showIcon:!0,message:"Идёт обработка",description:"Документ обрабатывается ассистентом. Это может занять несколько минут. Можно закрыть страницу и вернуться чуть позже.",style:{marginBottom:16}}),f&&b&&b.pages.length>0&&(0,je.jsx)(It,{pages:b.pages,totalProcessed:b.total_processed,isInProgress:"in_progress"===x||"in_queue"===x}),"partial_success"===x&&(0,je.jsx)(p.A,{type:"warning",showIcon:!0,message:"Обработка завершена с замечаниями",description:"Часть страниц не удалось обработать. Ассистент уже использует то, что обработалось успешно.",style:{marginBottom:16}}),"fail"===x&&(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:"Ошибка обработки",description:"Не удалось обработать источник. Попробуйте загрузить снова или свяжитесь с поддержкой.",style:{marginBottom:16}}),"success"===x&&(0,je.jsx)(p.A,{type:"success",showIcon:!0,message:"Готово",description:"Источник успешно обработан и используется ассистентом при ответах.",style:{marginBottom:16}}),A&&w&&w.items.length>0&&(0,je.jsx)(kt,{billing:w})]}):null}function Tt(e){var t=e.progress,n=function(e){if(null===e||e<60)return null;var t=Math.round(e/60);if(t<60)return"~".concat(t," мин");var n=Math.floor(t/60),r=t%60;return 0===r?"~".concat(n," ч"):"~".concat(n," ч ").concat(r," мин")}(t.eta_seconds),r="done"===t.progress_status&&"vision_processing"===t.vision_status;return(0,je.jsxs)(y.A,{size:"small",style:{marginBottom:16},children:[(0,je.jsxs)("div",{style:{marginBottom:12},children:[(0,je.jsx)(St,{strong:!0,style:{fontSize:14},children:"Парсинг страниц"}),(0,je.jsx)(xe.A,{percent:t.pages_percent,status:"done"===t.progress_status?"success":"active",format:()=>"".concat(t.pages_done," / ").concat(t.pages_total),style:{marginTop:8}})]}),t.images_done>0&&(0,je.jsxs)("div",{style:{marginBottom:12},children:[(0,je.jsx)(St,{strong:!0,style:{fontSize:14},children:"Обработка картинок"}),(0,je.jsxs)("div",{style:{marginTop:6},children:[(0,je.jsxs)(St,{children:["Обработано: ",(0,je.jsx)(St,{strong:!0,children:t.images_done})]}),t.images_kept>0&&t.images_kept!==t.images_done&&(0,je.jsxs)(St,{type:"secondary",style:{marginLeft:12,fontSize:12},children:["(с описанием: ",t.images_kept,")"]})]}),r&&(0,je.jsx)(xe.A,{percent:100,size:"small",status:"active",showInfo:!1,style:{marginTop:4}})]}),n&&(0,je.jsxs)(St,{type:"secondary",style:{fontSize:12},children:["Осталось примерно: ",n]}),!n&&"done"!==t.progress_status&&(0,je.jsx)(St,{type:"secondary",style:{fontSize:12},children:"Можно закрыть страницу — обработка продолжится в фоне."})]})}function It(e){var t=e.pages,n=e.totalProcessed,r=e.isInProgress;return(0,je.jsx)(y.A,{size:"small",title:(0,je.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[r?(0,je.jsx)(et.A,{style:{color:"#1677ff"},spin:!0}):(0,je.jsx)(jt.A,{twoToneColor:"#52c41a"}),(0,je.jsxs)(St,{strong:!0,style:{fontSize:14},children:["Обработано страниц: ",n]})]}),style:{marginBottom:16},styles:{body:{maxHeight:360,overflowY:"auto",padding:0}},children:(0,je.jsx)(vt.A,{size:"small",dataSource:t,renderItem:e=>{return(0,je.jsx)(vt.A.Item,{style:{padding:"8px 16px"},children:(0,je.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,width:"100%",minWidth:0},children:[(0,je.jsx)(jt.A,{twoToneColor:"#52c41a",style:{flexShrink:0,fontSize:14}}),(0,je.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",style:{fontSize:13,color:"#1A1A1A",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},title:e.url,children:(t=e.url,t.replace(/^https?:\/\//i,""))}),e.chunks_count>1&&(0,je.jsxs)(St,{type:"secondary",style:{fontSize:11,flexShrink:0},children:[e.chunks_count," чанков"]})]})});var t}})})}function kt(e){var t=e.billing;return(0,je.jsxs)(y.A,{size:"small",title:(0,je.jsx)(St,{strong:!0,style:{fontSize:14},children:"Стоимость обработки"}),styles:{body:{padding:16}},children:[t.items.map(e=>(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",padding:"4px 0",fontSize:13},children:[(0,je.jsxs)(St,{children:[e.label," ",(0,je.jsxs)(St,{type:"secondary",style:{fontSize:12},children:["(",e.unit_count," ",e.unit_label," × ",Et(e.unit_price_rub)," ₽)"]})]}),(0,je.jsxs)(St,{children:[Et(e.amount_rub)," ₽"]})]},e.phase)),(0,je.jsxs)("div",{style:{borderTop:"1px solid #f0f0f0",marginTop:8,paddingTop:8,display:"flex",justifyContent:"space-between",alignItems:"baseline"},children:[(0,je.jsx)(St,{strong:!0,children:"Итого списано"}),(0,je.jsxs)(St,{strong:!0,style:{fontSize:15},children:[Et(t.total_rub)," ₽"]})]})]})}function Ct(e){var t=e.status,n=zt[t];return(0,je.jsx)(ve.A,{color:n.color,bordered:!1,style:{fontSize:12,margin:0},children:n.label})}var zt={pending_confirm:{label:"Ждёт подтверждения",color:"default"},in_queue:{label:"В очереди",color:"default"},in_progress:{label:"Обработка...",color:"blue"},success:{label:"Готов",color:"success"},partial_success:{label:"Частично",color:"warning"},fail:{label:"Ошибка",color:"error"}};function Bt(e){return new Date(e).toLocaleString("ru-RU",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})}function Et(e){return parseFloat(e).toFixed(2)}function Pt(e){var t=e.assistantId,n=e.state,r=e.onGoWelcome,i=e.onAddDocument,s=e.onAddSite,l=e.onSelectSource;switch(n.mode){case"welcome":return(0,je.jsx)(Ce,{onAddDocument:i,onAddSite:s});case"add-document":return(0,je.jsx)(Ge,{assistantId:t,onBack:r});case"add-site":return(0,je.jsx)(ot,{assistantId:t,onBack:r,onSourceConfirmed:l});case"detail":return(0,je.jsx)(Ft,{assistantId:t,sourceId:n.sourceId,onSourceGone:r});default:return null}}function Ot(e){var t=e.assistantId,n=function(){var e,t,n=(e=(0,L.useState)({mode:"welcome"}),t=2,function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,l,a=[],o=!0,c=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;o=!1}else for(;!(o=(r=s.call(n)).done)&&(a.push(r.value),a.length!==t);o=!0);}catch(e){c=!0,i=e}finally{try{if(!o&&null!=n.return&&(l=n.return(),Object(l)!==l))return}finally{if(c)throw i}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return H(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?H(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),r=n[0],i=n[1];return{state:r,goWelcome:(0,L.useCallback)(()=>{i({mode:"welcome"})},[]),goAddDocument:(0,L.useCallback)(()=>{i({mode:"add-document"})},[]),goAddSite:(0,L.useCallback)(()=>{i({mode:"add-site"})},[]),selectSource:(0,L.useCallback)(e=>{i({mode:"detail",sourceId:e})},[])}}(),r=n.state,i=n.goWelcome,s=n.goAddDocument,l=n.goAddSite,a=n.selectSource,o="detail"===r.mode?r.sourceId:null;return(0,je.jsxs)("div",{style:{display:"flex",gap:16,minHeight:600},children:[(0,je.jsx)("div",{style:{width:320,flexShrink:0,display:"flex",flexDirection:"column"},children:(0,je.jsx)(Te,{assistantId:t,selectedSourceId:o,onSelectSource:a,onAddDocument:s,onAddSite:l})}),(0,je.jsx)("div",{style:{width:1,background:"#f0f0f0",flexShrink:0}}),(0,je.jsx)("div",{style:{flex:1,minWidth:0,overflow:"auto"},children:(0,je.jsx)(Pt,{assistantId:t,state:r,onGoWelcome:i,onAddDocument:s,onAddSite:l,onSelectSource:a})})]})}var qt=n(36552);function Lt(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function Rt(e){var t,n=e.assistantId,r=e.assistantName,s=(0,u.Zp)(),a=l.A.useApp().message,o=(t=(0,i.jE)(),(0,P.n)({mutationFn:e=>B(e),onSuccess:(e,n)=>{t.removeQueries({queryKey:K.detail(n)}),t.invalidateQueries({queryKey:N.me()})}})),c=function(){var e,t=(e=function*(){try{yield o.mutateAsync(n),a.success("Ассистент «".concat(r,"» удалён")),s("/assistants")}catch(e){a.error(F(e))}},function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){Lt(s,r,i,l,a,"next",e)}function a(e){Lt(s,r,i,l,a,"throw",e)}l(void 0)})});return function(){return t.apply(this,arguments)}}();return(0,je.jsx)(bt.A,{title:"Удалить ассистента?",description:"Удалятся также все документы из базы знаний и история тест-чатов. Действие необратимо.",okText:"Удалить",cancelText:"Отмена",okButtonProps:{danger:!0,loading:o.isPending},onConfirm:c,placement:"topRight",children:(0,je.jsx)(g.Ay,{danger:!0,children:"Удалить ассистента"})})}function Dt(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function Wt(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);nz(r,e),onSuccess:e=>{s.setQueryData(K.detail(r),e),s.invalidateQueries({queryKey:N.me()})}}));(0,L.useEffect)(()=>{var e,t;u.setFieldsValue({name:c.name,prompt:null!==(e=c.prompt)&&void 0!==e?e:"",show_images:null===(t=c.show_images)||void 0===t||t})},[c.id,c.name,c.prompt,c.show_images,u]);var y=function(){var e,t=(e=function*(e){var t,n,r={},i=e.name.trim(),s=e.prompt.trim(),l=null!==(t=c.prompt)&&void 0!==t?t:"";if(i!==c.name&&(r.name=i),s!==l&&(r.prompt=s||null),e.show_images!==(null===(n=c.show_images)||void 0===n||n)&&(r.show_images=e.show_images),0!==Object.keys(r).length)try{yield h.mutateAsync(r),d.success("Сохранено")}catch(e){d.error(F(e))}else d.info("Нет изменений")},function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){Dt(s,r,i,l,a,"next",e)}function a(e){Dt(s,r,i,l,a,"throw",e)}l(void 0)})});return function(e){return t.apply(this,arguments)}}();return(0,je.jsxs)($e.A,{form:u,layout:"vertical",requiredMark:!1,onFinish:y,initialValues:{name:c.name,prompt:null!==(t=c.prompt)&&void 0!==t?t:"",show_images:null===(n=c.show_images)||void 0===n||n},children:[(0,je.jsx)($e.A.Item,{name:"name",label:"Название",rules:[{required:!0,message:"Введите название"},{max:100,message:"Слишком длинное название"}],children:(0,je.jsx)(Ye.A,{size:"large"})}),(0,je.jsx)($e.A.Item,{name:"prompt",label:"Инструкция для ассистента",extra:"Оставьте пустым — будет использована стандартная инструкция.",children:(0,je.jsx)(Ye.A.TextArea,{rows:6,maxLength:1e4,showCount:!0})}),(0,je.jsx)($e.A.Item,{name:"show_images",label:"Картинки в ответах",valuePropName:"checked",extra:"Бот прикрепляет картинки из базы знаний к ответам. Отключите, если картинки бывают нерелевантными.",children:(0,je.jsx)(Oe.A,{checkedChildren:"Вкл",unCheckedChildren:"Выкл"})}),(0,je.jsx)($e.A.Item,{style:{marginBottom:0},children:(0,je.jsx)(g.Ay,{type:"primary",htmlType:"submit",loading:h.isPending,children:"Сохранить"})})]})}h.A.Text;var Ut=h.A.Title,Nt=h.A.Text;function Kt(e){var t=e.assistant;return(0,je.jsxs)("div",{children:[(0,je.jsx)(Mt,{assistant:t}),(0,je.jsx)(qt.A,{style:{margin:"32px 0 24px"}}),(0,je.jsx)(Ut,{level:5,style:{marginTop:0,marginBottom:8},children:"Опасная зона"}),(0,je.jsx)(Nt,{type:"secondary",style:{fontSize:13,display:"block",marginBottom:12},children:"Удаление ассистента сотрёт его базу знаний и историю чатов без возможности восстановления."}),(0,je.jsx)(Rt,{assistantId:t.id,assistantName:t.name})]})}var Ht=n(71925),Qt=n(9110),Xt=n(28482),Zt=n(85408),Gt=n(69107),$t=n(77984),Vt=n(23495),Yt=n(20497),Jt=n(71701),en={telegram:"Telegram",max:"MAX",widget:"Виджет"},tn=[{value:"all",label:"Все платформы"},{value:"telegram",label:"Telegram"},{value:"max",label:"MAX"},{value:"widget",label:"Виджет"}],nn=[{value:"all",label:"Всё время"},{value:"today",label:"Сегодня"},{value:"week",label:"Неделя"},{value:"month",label:"Месяц"}];function rn(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function sn(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){rn(s,r,i,l,a,"next",e)}function a(e){rn(s,r,i,l,a,"throw",e)}l(void 0)})}}var ln={getOverview:(e,t)=>sn(function*(){return(yield _.get("/assistants/".concat(e,"/stats/overview"),{params:{platform:t.platform,period:t.period}})).data})(),getDialogs(e,t){var n=arguments;return sn(function*(){var r=n.length>2&&void 0!==n[2]?n[2]:50,i=n.length>3&&void 0!==n[3]?n[3]:0;return(yield _.get("/assistants/".concat(e,"/stats/dialogs"),{params:{platform:t.platform,period:t.period,limit:r,offset:i}})).data})()},getDialogMessages:(e,t)=>sn(function*(){return(yield _.get("/assistants/".concat(e,"/stats/dialogs/").concat(t,"/messages"))).data})()},an={all:["statistics"],overview:(e,t)=>[...an.all,"overview",e,t],dialogs:(e,t)=>[...an.all,"dialogs",e,t],messages:(e,t)=>[...an.all,"messages",e,t]},on=(e,t)=>{var n,r=null===(n=t.response)||void 0===n?void 0:n.status;return 401!==r&&403!==r&&e<1};function cn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function dn(e){for(var t=1;te.length)&&(t=e.length);for(var n=0,r=Array(t);nln.getOverview(e,t),staleTime:1e4,retry:on})}(n,i),d=c.data,u=c.isLoading,h=function(e,t){return(0,E.I)({queryKey:an.dialogs(e,t),queryFn:()=>ln.getDialogs(e,t),staleTime:1e4,retry:on})}(n,i),p=h.data,g=h.isLoading,f=null!==(t=null==p?void 0:p.dialogs)&&void 0!==t?t:[],x=[{title:"Платформа",dataIndex:"platform",key:"platform",width:120,render:e=>{var t;return(0,je.jsx)(ve.A,{bordered:!1,style:{fontSize:12},children:null!==(t=en[e])&&void 0!==t?t:e})}},{title:"Пользователь",dataIndex:"user_name",key:"user_name",width:160,render:(e,t)=>(0,je.jsx)(pn,{style:{fontSize:13},children:e||t.user_external_id})},{title:"Последний вопрос",dataIndex:"last_question",key:"last_question",ellipsis:!0,render:e=>(0,je.jsx)(pn,{type:"secondary",style:{fontSize:13},children:e||"—"})},{title:"Сообщений",dataIndex:"messages_count",key:"messages_count",width:110,align:"center",render:e=>(0,je.jsx)(pn,{type:"secondary",style:{fontSize:13},children:e})},{title:"Последняя активность",dataIndex:"last_message_at",key:"last_message_at",width:170,render:(e,t)=>(0,je.jsx)(pn,{type:"secondary",style:{fontSize:13},children:An(null!=e?e:t.created_at)})}];return(0,je.jsxs)("div",{children:[(0,je.jsxs)("div",{style:{display:"grid",gap:16,gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))"},children:[(0,je.jsx)(xn,{label:"Всего диалогов",value:null==d?void 0:d.total_dialogs,loading:u}),(0,je.jsx)(xn,{label:"Уникальных пользователей",value:null==d?void 0:d.unique_users,loading:u}),(0,je.jsx)(xn,{label:"Диалогов за период",value:null==d?void 0:d.dialogs_in_period,loading:u})]}),(0,je.jsxs)(y.A,{style:{marginTop:16},styles:{body:{padding:20}},children:[(0,je.jsx)(pn,{type:"secondary",style:{fontSize:12,display:"block",marginBottom:12},children:"Диалоги по дням"}),u?(0,je.jsx)(m.A,{active:!0,paragraph:{rows:3}}):d&&d.by_day.length>0?(0,je.jsx)(vn,{data:d.by_day}):(0,je.jsx)(X.A,{image:X.A.PRESENTED_IMAGE_SIMPLE,description:(0,je.jsx)(pn,{type:"secondary",children:"Нет данных за период"})})]}),(0,je.jsxs)("div",{style:{display:"flex",gap:8,marginTop:24,flexWrap:"wrap"},children:[(0,je.jsx)(Ht.A,{value:i.platform,onChange:e=>s(t=>dn(dn({},t),{},{platform:e})),options:tn,style:{minWidth:160}}),(0,je.jsx)(Ht.A,{value:i.period,onChange:e=>s(t=>dn(dn({},t),{},{period:e})),options:nn,style:{minWidth:140}})]}),(0,je.jsx)("div",{style:{marginTop:16},children:g?(0,je.jsx)(m.A,{active:!0,paragraph:{rows:5}}):0===f.length?(0,je.jsx)(X.A,{image:X.A.PRESENTED_IMAGE_SIMPLE,description:(0,je.jsx)(pn,{type:"secondary",children:"Диалогов пока нет — они появятся после общения пользователей с ассистентом в боевых каналах."})}):(0,je.jsx)(Qt.A,{columns:x,dataSource:f,rowKey:"id",size:"middle",onRow:e=>({onClick:()=>o(e.id),style:{cursor:"pointer"}}),pagination:f.length>20&&{pageSize:20,showSizeChanger:!1}})}),(0,je.jsx)(jn,{assistantId:n,dialogId:a,onClose:()=>o(null)})]})}function xn(e){var t=e.label,n=e.value,r=e.loading;return(0,je.jsxs)(y.A,{styles:{body:{padding:20}},children:[(0,je.jsx)(pn,{type:"secondary",style:{fontSize:12},children:t}),r?(0,je.jsx)(m.A,{active:!0,paragraph:!1,title:{width:60}}):(0,je.jsx)(mn,{level:3,style:{margin:"4px 0 0",fontWeight:500,color:"#1F2937"},children:null!=n?n:0})]})}function vn(e){var t=e.data.map(e=>({date:bn(e.date),count:e.count}));return(0,je.jsx)("div",{style:{width:"100%",height:220},children:(0,je.jsx)(Xt.u,{width:"100%",height:"100%",children:(0,je.jsxs)(Zt.Q,{data:t,margin:{top:8,right:8,left:0,bottom:0},children:[(0,je.jsx)("defs",{children:(0,je.jsxs)("linearGradient",{id:"rchStatsFill",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,je.jsx)("stop",{offset:"0%",stopColor:"#1F2937",stopOpacity:.16}),(0,je.jsx)("stop",{offset:"100%",stopColor:"#1F2937",stopOpacity:.02})]})}),(0,je.jsx)(Gt.d,{stroke:"#F3F4F6",vertical:!1}),(0,je.jsx)($t.W,{dataKey:"date",tick:{fontSize:11,fill:"#9CA3AF"},axisLine:{stroke:"#E5E7EB"},tickLine:!1}),(0,je.jsx)(Vt.h,{width:36,allowDecimals:!1,tick:{fontSize:11,fill:"#9CA3AF"},axisLine:!1,tickLine:!1}),(0,je.jsx)(Yt.m,{formatter:e=>["".concat(e),"Диалогов"],contentStyle:{fontSize:12,borderRadius:6,border:"1px solid #E5E7EB",boxShadow:"0 2px 8px rgba(0,0,0,0.06)"},labelStyle:{color:"#6B7280"},cursor:{stroke:"#E5E7EB"}}),(0,je.jsx)(Jt.Gk,{type:"monotone",dataKey:"count",stroke:"#1F2937",strokeWidth:2,fill:"url(#rchStatsFill)",dot:{r:2.5,fill:"#1F2937",strokeWidth:0},activeDot:{r:4,fill:"#1F2937",strokeWidth:0}})]})})})}function jn(e){var t=e.assistantId,n=e.dialogId,r=e.onClose,i=function(e,t){return(0,E.I)({queryKey:an.messages(e,null!=t?t:""),queryFn:()=>ln.getDialogMessages(e,t),enabled:!!t,staleTime:1e4,retry:on})}(t,n),s=i.data,l=i.isLoading;return(0,je.jsx)(Be.A,{open:!!n,onCancel:r,footer:null,width:640,title:s?"Диалог — ".concat(s.user_name||"пользователь"):"Диалог",children:l?(0,je.jsx)("div",{style:{textAlign:"center",padding:40},children:(0,je.jsx)(Pe.A,{})}):s&&0!==s.messages.length?(0,je.jsx)("div",{style:{maxHeight:"60vh",overflowY:"auto",display:"flex",flexDirection:"column",gap:10,padding:"8px 4px"},children:s.messages.map(e=>{var t="incoming"===e.direction;return(0,je.jsx)("div",{style:{display:"flex",justifyContent:t?"flex-end":"flex-start"},children:(0,je.jsxs)("div",{style:{maxWidth:"78%",background:t?"#1F2937":"#F3F4F6",color:t?"#FFFFFF":"#1A1A1A",borderRadius:12,padding:"8px 12px"},children:[(0,je.jsx)(gn,{style:{margin:0,fontSize:14,whiteSpace:"pre-wrap",color:t?"#FFFFFF":"#1A1A1A"},children:e.content}),(0,je.jsx)("div",{style:{fontSize:10,marginTop:4,textAlign:"right",color:t?"rgba(255,255,255,0.6)":"#9CA3AF"},children:An(e.created_at)})]})},e.id)})}):(0,je.jsx)(X.A,{image:X.A.PRESENTED_IMAGE_SIMPLE,description:(0,je.jsx)(pn,{type:"secondary",children:"Нет сообщений"})})})}function bn(e){try{var t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleDateString("ru-RU",{day:"2-digit",month:"2-digit"})}catch(t){return e}}function An(e){try{var t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString("ru-RU",{day:"2-digit",month:"2-digit",year:"2-digit",hour:"2-digit",minute:"2-digit"})}catch(t){return e}}function wn(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function _n(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){wn(s,r,i,l,a,"next",e)}function a(e){wn(s,r,i,l,a,"throw",e)}l(void 0)})}}var Sn={createThread:e=>_n(function*(){return(yield _.post("/chat/threads",{assistant_id:e})).data})(),listThreads:e=>_n(function*(){return(yield _.get("/chat/threads",{params:{assistant_id:e}})).data})(),getMessages(e){var t=arguments;return _n(function*(){var n=t.length>1&&void 0!==t[1]?t[1]:100;return(yield _.get("/chat/threads/".concat(e,"/messages"),{params:{limit:n}})).data})()},sendMessage:(e,t)=>_n(function*(){return(yield _.post("/chat/threads/".concat(e,"/messages"),{content:t},{timeout:6e4})).data})(),deleteThread:e=>_n(function*(){yield _.delete("/chat/threads/".concat(e))})(),getChunksMeta:e=>_n(function*(){return 0===e.length?[]:(yield _.get("/knowledge/chunks",{params:{ids:e.join(",")}})).data})()};function Fn(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function Tn(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){Fn(s,r,i,l,a,"next",e)}function a(e){Fn(s,r,i,l,a,"throw",e)}l(void 0)})}}var In={all:["chat"],threads:e=>[...In.all,"threads",e],messages:e=>[...In.all,"messages",e],chunksMeta:e=>[...In.all,"chunksMeta",[...e].sort().join(",")]},kn=n(37977);function Cn(e){var t,n,r,i,s,l=e.chunkIds,a=(t=l,(0,E.I)({queryKey:In.chunksMeta(t),queryFn:(n=Tn(function*(){try{return yield Sn.getChunksMeta(t)}catch(t){var e;if(404===(null===(e=t.response)||void 0===e?void 0:e.status))return[];throw t}}),function(){return n.apply(this,arguments)}),enabled:t.length>0,staleTime:3e5})),o=a.data;if(0===l.length)return null;if(!o||0===o.length)return(0,je.jsx)("div",{style:{marginTop:8},children:(0,je.jsxs)(ve.A,{bordered:!1,style:{fontSize:11},children:[l.length," ",(r=l.length,i=r%10,s=r%100,s>=11&&s<=14?"фрагментов":1===i?"фрагмент":i>=2&&i<=4?"фрагмента":"фрагментов")]})});var c=function(e){var t=new Map;for(var n of e){var r=t.get(n.source_id);r?null==n.page_number||r.pages.includes(n.page_number)||r.pages.push(n.page_number):t.set(n.source_id,{sourceId:n.source_id,sourceName:n.source_name,pages:null!=n.page_number?[n.page_number]:[]})}for(var i of t.values())i.pages.sort((e,t)=>e-t);return Array.from(t.values())}(o);return(0,je.jsx)("div",{style:{marginTop:8,display:"flex",flexWrap:"wrap",gap:6},children:c.map(e=>{var t=e.sourceId,n=e.sourceName,r=e.pages,i=null!=n?n:"Документ",s=r.length>0?"стр. ".concat(r.join(", ")):null,l=s?"".concat(i," · ").concat(s):i;return(0,je.jsx)(kn.A,{title:l,children:(0,je.jsxs)(ve.A,{bordered:!1,style:{fontSize:11,maxWidth:240},children:[(0,je.jsx)("span",{style:{display:"inline-block",maxWidth:200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",verticalAlign:"bottom"},children:i}),s&&(0,je.jsx)("span",{style:{marginLeft:6,opacity:.6},children:s})]})},t)})})}var zn=n(26398),Bn=h.A.Text;function En(e){var t=e.images.filter(e=>e.cdn_url);return 0===t.length?null:(0,je.jsx)("div",{style:{marginTop:8},children:(0,je.jsx)(zn.A.PreviewGroup,{children:(0,je.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:t.map(e=>{var t,n,r;return(0,je.jsxs)("div",{style:{display:"flex",flexDirection:"column"},children:[(0,je.jsx)(kn.A,{title:null!==(t=e.caption)&&void 0!==t?t:void 0,placement:"top",children:(0,je.jsx)(zn.A,{src:null!==(n=e.cdn_url)&&void 0!==n?n:void 0,alt:null!==(r=e.caption)&&void 0!==r?r:"Иллюстрация из документа",width:80,height:80,style:{objectFit:"cover",borderRadius:6,border:"1px solid #E5E7EB"},preview:{mask:!1}})}),null!=e.page_number&&(0,je.jsxs)(Bn,{type:"secondary",style:{fontSize:10,marginTop:2,textAlign:"center"},children:["стр. ",e.page_number]})]},e.id)})})})})}var Pn=h.A.Text;function On(e){var t,n,r,i,s=e.message,l="user"===s.role,a=null!==(t=s.retrieved_chunk_ids)&&void 0!==t?t:[],o=null!==(n=s.images)&&void 0!==n?n:[];return(0,je.jsx)("div",{style:{display:"flex",justifyContent:l?"flex-end":"flex-start",marginBottom:12},children:(0,je.jsxs)("div",{style:{maxWidth:"75%"},children:[(0,je.jsx)("div",{style:{padding:"10px 14px",borderRadius:12,background:l?"#1F2937":"#F3F4F6",color:l?"#FFFFFF":"#1A1A1A",fontSize:14,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:s.content}),!l&&o.length>0&&(0,je.jsx)(En,{images:o}),!l&&a.length>0&&(0,je.jsx)(Cn,{chunkIds:a}),(0,je.jsx)(Pn,{type:"secondary",style:{fontSize:11,marginTop:4,display:"block",textAlign:l?"right":"left"},children:(r=s.created_at,i=new Date(r),i.toLocaleTimeString("ru-RU",{hour:"2-digit",minute:"2-digit"}))})]})})}function qn(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n0&&!i&&!s,u=()=>{d&&(r(c),o(""))};return(0,je.jsxs)("div",{style:{display:"flex",gap:8,alignItems:"flex-end",padding:"12px 16px",borderTop:"1px solid #E5E7EB",background:"#FFFFFF"},children:[(0,je.jsx)(Ye.A.TextArea,{value:a,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),u())},placeholder:"Напишите сообщение... (Ctrl+Enter — отправить)",autoSize:{minRows:1,maxRows:6},disabled:i,style:{resize:"none"}}),(0,je.jsx)(g.Ay,{type:"primary",onClick:u,loading:s,disabled:!d,children:"Отправить"})]})}var Rn=h.A.Text;function Dn(e){var t=e.threadId,n=function(e){return(0,E.I)({queryKey:In.messages(null!=e?e:""),queryFn:()=>Sn.getMessages(e),enabled:!!e,staleTime:1/0})}(t),r=n.data,s=n.isLoading,l=n.error,a=function(e){var t,n=(0,i.jE)(),r=In.messages(e);return(0,P.n)({mutationFn:t=>{var n=t.content;return Sn.sendMessage(e,n)},onMutate:(t=Tn(function*(t){var i=t.content;yield n.cancelQueries({queryKey:r});var s=n.getQueryData(r),l={id:"optimistic-".concat(Date.now()),thread_id:e,role:"user",content:i,created_at:(new Date).toISOString(),retrieved_chunk_ids:null,image_ids:null};return n.setQueryData(r,e=>[...null!=e?e:[],l]),{previous:s}}),function(e){return t.apply(this,arguments)}),onError:(e,t,i)=>{null!=i&&i.previous&&n.setQueryData(r,i.previous)},onSuccess:e=>{n.setQueryData(r,t=>t?[...t.filter(e=>!e.id.startsWith("optimistic-")),e]:[e]),n.invalidateQueries({queryKey:r})}})}(t),o=(0,L.useRef)(null);(0,L.useEffect)(()=>{var e;null===(e=o.current)||void 0===e||e.scrollTo({top:o.current.scrollHeight,behavior:"smooth"})},[null==r?void 0:r.length]);var c=a.error?F(a.error):null;return(0,je.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"60vh",minHeight:400,border:"1px solid #E5E7EB",borderRadius:8,overflow:"hidden",background:"#FFFFFF"},children:[(0,je.jsxs)("div",{ref:o,style:{flex:1,overflowY:"auto",padding:"16px 16px 4px"},children:[s&&(0,je.jsx)(m.A,{active:!0,paragraph:{rows:4}}),l&&(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:"Не удалось загрузить историю",description:F(l)}),r&&0===r.length&&!a.isPending&&(0,je.jsx)("div",{style:{textAlign:"center",padding:"40px 0"},children:(0,je.jsx)(Rn,{type:"secondary",children:"Напишите ассистенту что-нибудь, чтобы проверить как он отвечает."})}),null==r?void 0:r.map(e=>(0,je.jsx)(On,{message:e},e.id)),a.isPending&&(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"flex-start",marginBottom:12,paddingLeft:14},children:[(0,je.jsx)(Pe.A,{size:"small"}),(0,je.jsx)(Rn,{type:"secondary",style:{fontSize:13,marginLeft:8},children:"Ассистент думает..."})]}),c&&(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:c,style:{marginBottom:12}})]}),(0,je.jsx)(Ln,{onSend:e=>{a.mutate({content:e})},isPending:a.isPending})]})}function Wn(e){var t=e.assistantId,n=function(e){return(0,E.I)({queryKey:In.threads(null!=e?e:""),queryFn:()=>Sn.listThreads(e),enabled:!!e,staleTime:3e4})}(t),r=n.data,s=n.isLoading,l=n.error,a=function(e){var t=(0,i.jE)();return(0,P.n)({mutationFn:()=>Sn.createThread(e),onSuccess:()=>{t.invalidateQueries({queryKey:In.threads(e)})}})}(t),o=(0,L.useRef)(!1),c=r&&r.length>0?r[0].id:void 0;return(0,L.useEffect)(()=>{s||l||!r||0!==r.length||o.current||(o.current=!0,a.mutate())},[r,s,l,a]),s?(0,je.jsx)(m.A,{active:!0,paragraph:{rows:4}}):l?(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:"Не удалось загрузить тред",description:F(l)}):a.error?(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:"Не удалось создать тред",description:F(a.error)}):c?(0,je.jsx)(Dn,{threadId:c}):(0,je.jsx)(m.A,{active:!0,paragraph:{rows:4}})}var Mn=n(6984),Un={telegram:"Telegram",max:"MAX",widget:"Виджет на сайт"},Nn={telegram:"Бот в Telegram. Нужен токен от @BotFather.",max:"Бот в MAX (российский мессенджер). Нужен токен из dev.max.ru.",widget:"Чат-виджет на сайте клиента. Без токена, по сниппету."},Kn={telegram:"blue",max:"purple",widget:"cyan"},Hn={active:"Активен",paused:"На паузе",disabled:"Отключён"};function Qn(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function Xn(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){Qn(s,r,i,l,a,"next",e)}function a(e){Qn(s,r,i,l,a,"throw",e)}l(void 0)})}}var Zn=e=>Xn(function*(){return(yield _.get("/channels",{params:{assistant_id:e}})).data})(),Gn=e=>Xn(function*(){return(yield _.post("/channels",e)).data})(),$n=e=>Xn(function*(){return(yield _.get("/channels/".concat(e,"/stats"))).data})(),Vn=(e,t)=>Xn(function*(){return(yield _.patch("/channels/".concat(e),t)).data})(),Yn=e=>Xn(function*(){yield _.delete("/channels/".concat(e))})(),Jn={all:["channels"],list:e=>[...Jn.all,"list",e],stats:e=>[...Jn.all,"stats",e]};function er(e){return(0,E.I)({queryKey:Jn.list(null!=e?e:""),queryFn:()=>Zn(e),enabled:!!e,staleTime:1e4})}function tr(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return(0,E.I)({queryKey:Jn.stats(null!=e?e:""),queryFn:()=>$n(e),enabled:!!e&&t,staleTime:3e4})}function nr(e){var t=(0,i.jE)();return(0,P.n)({mutationFn:e=>Gn(e),onSuccess:()=>{t.invalidateQueries({queryKey:Jn.list(e)})}})}var rr=h.A.Text;function ir(e){var t=e.channel,n=e.assistantId,r=(0,u.Zp)(),i=tr(t.id),s=i.data,l=i.isLoading,a="disabled"===t.status,o="widget"===t.platform;return(0,je.jsxs)(y.A,{hoverable:!0,onClick:()=>{r("/assistants/".concat(n,"/channels/").concat(t.id))},size:"small",styles:{body:{padding:16}},style:{opacity:a?.6:1,borderColor:a?"#FECACA":void 0,cursor:"pointer"},children:[(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:12},children:[(0,je.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,je.jsxs)(Mn.A,{size:8,wrap:!0,children:[(0,je.jsx)(rr,{strong:!0,style:{fontSize:14},children:o?t.bot_username:"@".concat(t.bot_username)}),(0,je.jsx)(ve.A,{color:Kn[t.platform],children:Un[t.platform]}),(0,je.jsx)(sr,{status:t.status})]}),t.bot_display_name&&(0,je.jsx)("div",{children:(0,je.jsx)(rr,{type:"secondary",style:{fontSize:12},children:t.bot_display_name})})]}),!o&&(0,je.jsxs)("div",{style:{display:"flex",gap:16,padding:"4px 12px",background:"#F9FAFB",borderRadius:6},children:[(0,je.jsx)(lr,{label:"за 24ч",value:null==s?void 0:s.messages_last_24h,loading:l}),(0,je.jsx)(lr,{label:"₽ за 24ч",value:s?s.cost_last_24h_rub.toFixed(2):void 0,loading:l})]})]}),t.last_error&&(0,je.jsx)(p.A,{type:"warning",showIcon:!0,message:t.last_error,style:{marginTop:12,fontSize:12}})]})}function sr(e){var t=e.status,n="active"===t?"success":"paused"===t?"warning":"error";return(0,je.jsx)(ve.A,{color:n,children:Hn[t]})}function lr(e){var t=e.label,n=e.value,r=e.loading;return(0,je.jsxs)("div",{style:{textAlign:"right"},children:[(0,je.jsx)(rr,{type:"secondary",style:{fontSize:10,display:"block"},children:t}),r?(0,je.jsx)(m.A.Input,{active:!0,size:"small",style:{width:40,height:14}}):(0,je.jsx)(rr,{strong:!0,style:{fontSize:13},children:null!=n?n:"—"})]})}var ar=h.A.Title,or=h.A.Text;function cr(e){var t=e.assistantId,n=(0,u.Zp)(),r=er(t),i=r.data,s=r.isLoading,l=r.error,a=r.refetch;if(s)return(0,je.jsxs)(Mn.A,{direction:"vertical",style:{width:"100%"},size:12,children:[(0,je.jsx)(m.A,{active:!0,paragraph:{rows:2}}),(0,je.jsx)(m.A,{active:!0,paragraph:{rows:2}})]});if(l)return(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:"Не удалось загрузить каналы",description:F(l),action:(0,je.jsx)(g.Ay,{size:"small",onClick:()=>a(),children:"Повторить"})});var o=i&&i.length>0,c=["widget","telegram","max"].map(e=>({key:e,label:(0,je.jsxs)(Mn.A,{direction:"vertical",size:0,style:{padding:"4px 0"},children:[(0,je.jsx)(or,{strong:!0,children:Un[e]}),(0,je.jsx)(or,{type:"secondary",style:{fontSize:11},children:Nn[e]})]}),onClick:()=>{return r=e,void n("/assistants/".concat(t,"/channels/new?type=").concat(r));var r}}));return(0,je.jsxs)("div",{children:[(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:16},children:[(0,je.jsxs)("div",{children:[(0,je.jsx)(ar,{level:5,style:{margin:0},children:"Подключённые каналы"}),(0,je.jsx)(or,{type:"secondary",style:{fontSize:12},children:"Telegram, MAX и виджет на сайт — там где ваш ассистент отвечает пользователям"})]}),o&&(0,je.jsx)(Q.A,{menu:{items:c},placement:"bottomRight",children:(0,je.jsx)(g.Ay,{type:"primary",icon:(0,je.jsx)($.A,{}),children:"Подключить"})})]}),o?(0,je.jsx)(Mn.A,{direction:"vertical",style:{width:"100%"},size:12,children:i.map(e=>(0,je.jsx)(ir,{channel:e,assistantId:t},e.id))}):(0,je.jsx)(X.A,{description:"Каналов пока нет. Подключите первый — ассистент начнёт отвечать.",style:{padding:"24px 0"},children:(0,je.jsx)(Q.A,{menu:{items:c},placement:"bottomRight",children:(0,je.jsx)(g.Ay,{type:"primary",icon:(0,je.jsx)($.A,{}),children:"Подключить канал"})})})]})}function dr(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);nC(e,t),enabled:!!e,staleTime:3e4,retry:(e,t)=>{var n,r=null===(n=t.response)||void 0===n?void 0:n.status;return 401!==r&&403!==r&&404!==r&&e<1}})}(i),c=o.data,h=o.isLoading,x=o.error,v=(e=l.get("tab"),yr.includes(e)?e:mr);return h?(0,je.jsx)(y.A,{children:(0,je.jsx)(m.A,{active:!0,paragraph:{rows:4}})}):x?(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:"Не удалось открыть ассистента",description:F(x),action:(0,je.jsx)(g.Ay,{size:"small",onClick:()=>r("/assistants"),children:"К списку"})}):c?(0,je.jsxs)("div",{children:[(0,je.jsx)(ur,{level:2,style:{marginTop:0,marginBottom:4},children:c.name}),(0,je.jsx)(hr,{type:"secondary",style:{fontSize:12},children:c.gpt_model}),(0,je.jsx)(y.A,{style:{marginTop:24},children:(0,je.jsx)(f.A,{activeKey:v,onChange:e=>{a(e===mr?{}:{tab:e},{replace:!0})},items:[{key:"knowledge",label:"База знаний",children:(0,je.jsx)(Ot,{assistantId:c.id})},{key:"test-chat",label:"Тест-чат",children:(0,je.jsx)(Wn,{assistantId:c.id})},{key:"channels",label:"Каналы",children:(0,je.jsx)(cr,{assistantId:c.id})},{key:"statistics",label:"Статистика",children:(0,je.jsx)(fn,{assistantId:c.id})},{key:"settings",label:"Настройки",children:(0,je.jsx)(Kt,{assistant:c})}]})})]}):null}var gr=n(50770),fr=h.A.Text,xr=[{value:"NONE",title:"Международные сервисы",description:"OpenAI GPT-4o-mini. "},{value:"PARTIAL",title:"Российские сервисы, кроме картинок",description:"YandexGPT для текста. Картинки в документах обрабатываются OpenAI Vision."},{value:"FULL",title:"Только российские сервисы",description:"YandexGPT, без обработки картинок. Все данные обрабатываются в РФ."}];function vr(e){var t=e.value,n=e.onChange;return(0,je.jsx)(gr.Ay.Group,{value:t,onChange:e=>null==n?void 0:n(e.target.value),style:{display:"flex",flexDirection:"column",gap:10,width:"100%"},children:xr.map(e=>{var n=t===e.value;return(0,je.jsx)(gr.Ay,{value:e.value,style:{display:"flex",alignItems:"flex-start",padding:"12px 14px",margin:0,border:"1px solid ".concat(n?"#1F2937":"#E5E7EB"),borderRadius:8,background:n?"#F9FAFB":"#FFFFFF",transition:"border-color 0.15s, background 0.15s"},children:(0,je.jsxs)("div",{style:{marginLeft:4},children:[(0,je.jsx)("div",{style:{fontWeight:500,color:"#1A1A1A",marginBottom:2},children:e.title}),(0,je.jsx)(fr,{type:"secondary",style:{fontSize:12,lineHeight:1.45},children:e.description})]})},e.value)})})}function jr(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function br(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);nk(e),onSuccess:()=>{t.invalidateQueries({queryKey:N.me()})}}));(0,L.useEffect)(()=>{s&&(o.resetFields(),c.reset())},[s,o]);var d=function(){var e,t=(e=function*(e){var t,n={name:e.name.trim(),localization:e.localization},r=null===(t=e.prompt)||void 0===t?void 0:t.trim();r&&(n.prompt=r);try{var i=yield c.mutateAsync(n);l(),a("/assistants/".concat(i.id))}catch(e){}},function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){jr(s,r,i,l,a,"next",e)}function a(e){jr(s,r,i,l,a,"throw",e)}l(void 0)})});return function(e){return t.apply(this,arguments)}}(),h=c.error?F(c.error):null;return(0,je.jsx)(Be.A,{open:s,title:"Создать ассистента",onCancel:l,onOk:()=>o.submit(),okText:"Создать",cancelText:"Отмена",confirmLoading:c.isPending,destroyOnClose:!0,width:520,children:(0,je.jsxs)($e.A,{form:o,layout:"vertical",requiredMark:!1,onFinish:d,initialValues:Ar,children:[(0,je.jsx)($e.A.Item,{name:"name",label:"Название",rules:[{required:!0,message:"Введите название"},{max:100,message:"Слишком длинное название"}],children:(0,je.jsx)(Ye.A,{size:"large",placeholder:"Например, «Поддержка интернет-магазина»",autoFocus:!0})}),(0,je.jsx)($e.A.Item,{name:"localization",label:"Локализация",tooltip:"Где обрабатываются данные ассистента. После создания изменить нельзя.",rules:[{required:!0}],children:(0,je.jsx)(vr,{})}),(0,je.jsx)($e.A.Item,{name:"prompt",label:"Инструкция для ассистента (необязательно)",extra:"Если оставить пустым — будет использована стандартная инструкция.",children:(0,je.jsx)(Ye.A.TextArea,{rows:4,placeholder:"Опишите, как ассистент должен общаться и о чём отвечать",maxLength:1e4,showCount:!0})}),h&&(0,je.jsx)("div",{style:{color:"#DC2626",fontSize:13,marginTop:4},children:h})]})})}function _r(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t,n;return null!==(t=null===(n=e.user)||void 0===n?void 0:n.assistants)&&void 0!==t?t:[]}),i=(e=(0,L.useState)(!1),t=2,function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,l,a=[],o=!0,c=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;o=!1}else for(;!(o=(r=s.call(n)).done)&&(a.push(r.value),a.length!==t);o=!0);}catch(e){c=!0,i=e}finally{try{if(!o&&null!=n.return&&(l=n.return(),Object(l)!==l))return}finally{if(c)throw i}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return _r(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_r(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),s=i[0],l=i[1];return(0,je.jsxs)("div",{children:[(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:24},children:[(0,je.jsx)(Sr,{level:2,style:{margin:0},children:"Ассистенты"}),(0,je.jsx)(g.Ay,{type:"primary",onClick:()=>l(!0),children:"Создать ассистента"})]}),0===r.length?(0,je.jsx)(y.A,{children:(0,je.jsx)(X.A,{description:(0,je.jsx)(Fr,{type:"secondary",children:"Пока ни одного ассистента. Нажмите «Создать ассистента», чтобы начать."})})}):(0,je.jsx)("div",{style:{display:"grid",gap:16,gridTemplateColumns:"repeat(auto-fill, minmax(280px, 1fr))"},children:r.map(e=>(0,je.jsxs)(y.A,{hoverable:!0,onClick:()=>n("/assistants/".concat(e.id)),children:[(0,je.jsx)(Sr,{level:5,style:{margin:0,marginBottom:4},children:e.name}),(0,je.jsx)(Fr,{type:"secondary",style:{fontSize:12},children:e.gpt_model})]},e.id))}),(0,je.jsx)(wr,{open:s,onClose:()=>l(!1)})]})}var Ir=1e3;function kr(e){if(null==e)return 0;if("number"==typeof e)return e;var t=Number(e);return Number.isFinite(t)?t:0}var Cr={topup_paid:"Пополнение картой",topup:"Приветственный бонус",topup_autopay:"Автопополнение",channel_message_max:"Чат (MAX)",channel_message_telegram:"Чат (Telegram)",channel_message_widget:"Чат (виджет)",page_ingest:"Обработка страниц",image_ingest:"Обработка картинок",adjustment:"Резерв средств",refund:"Возврат резерва",paid_expired:"Истечение баланса",admin_adjustment:"Корректировка"};function zr(e){var t;return null!==(t=Cr[e])&&void 0!==t?t:e}function Br(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function Er(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){Br(s,r,i,l,a,"next",e)}function a(e){Br(s,r,i,l,a,"throw",e)}l(void 0)})}}var Pr={createTopup:e=>Er(function*(){return(yield _.post("/billing/topup/create",e)).data})(),getPaymentIntentStatus:e=>Er(function*(){return(yield _.get("/billing/payment-intents/".concat(e))).data})(),getAssistantSummary:e=>Er(function*(){return(yield _.get("/billing/assistant/".concat(e,"/summary"))).data})(),getUserTransactions(){var e=arguments;return Er(function*(){var t=e.length>0&&void 0!==e[0]?e[0]:50,n=e.length>1&&void 0!==e[1]?e[1]:0,r=e.length>2&&void 0!==e[2]?e[2]:{};return(yield _.get("/billing/transactions",{params:{limit:t,offset:n,assistant_id:r.assistant_id||void 0,kind:r.kind||void 0,date_from:r.date_from||void 0,date_to:r.date_to||void 0}})).data})()},getOverview(){var e=arguments;return Er(function*(){var t=e.length>0&&void 0!==e[0]?e[0]:{};return(yield _.get("/billing/overview",{params:{date_from:t.date_from||void 0,date_to:t.date_to||void 0}})).data})()}},Or={all:["billing"],summary:e=>[...Or.all,"summary",e],paymentIntent:e=>[...Or.all,"payment-intent",e],transactions:e=>[...Or.all,"transactions",null!=e?e:{}],overview:e=>[...Or.all,"overview",null!=e?e:{}]},qr=n(81691);function Lr(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function Rr(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t,n=null===(t=e.user)||void 0===t||null===(t=t.assistants)||void 0===t?void 0:t.find(e=>e.id===i);return n?kr(n.balance):0}),o=a<0?-a:0,c=o>0,d=(t=(0,L.useState)(15e3),n=2,function(e){if(Array.isArray(e))return e}(t)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,l,a=[],o=!0,c=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;o=!1}else for(;!(o=(r=s.call(n)).done)&&(a.push(r.value),a.length!==t);o=!0);}catch(e){c=!0,i=e}finally{try{if(!o&&null!=n.return&&(l=n.return(),Object(l)!==l))return}finally{if(c)throw i}}return a}}(t,n)||function(e,t){if(e){if("string"==typeof e)return Rr(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Rr(e,t):void 0}}(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),u=d[0],h=d[1],y=(0,P.n)({mutationFn:e=>Pr.createTopup(e)}),m=(0,L.useMemo)(()=>o+u,[o,u]),f=uh(e.target.value),optionType:"button",buttonStyle:"solid",children:Mr.map(e=>(0,je.jsxs)(gr.Ay.Button,{value:e,children:[Ur(e)," ₽"]},e))})]}),(0,je.jsxs)("div",{children:[(0,je.jsx)(Dr,{strong:!0,style:{display:"block",marginBottom:8},children:"Или своя сумма"}),(0,je.jsx)(qr.A,{value:u,onChange:e=>h(null!=e?e:0),min:0,max:1e6,step:1e3,style:{width:"100%"},formatter:e=>"".concat(e).replace(/\B(?=(\d{3})+(?!\d))/g," "),parser:e=>Number((null!=e?e:"").replace(/\s/g,"")),addonAfter:"₽"}),f&&(0,je.jsxs)(Dr,{type:"danger",style:{fontSize:12},children:["Минимальная сумма пополнения — ",Ur(Ir)," ₽"]})]}),c&&(0,je.jsxs)("div",{style:{background:"#F9FAFB",borderRadius:8,padding:16},children:[(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:6},children:[(0,je.jsx)(Dr,{type:"secondary",style:{fontSize:13},children:"Оплата обработки документов"}),(0,je.jsxs)(Dr,{style:{fontSize:13},children:[Ur(o)," ₽"]})]}),(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",marginBottom:10},children:[(0,je.jsx)(Dr,{type:"secondary",style:{fontSize:13},children:"Пополнение на диалоги"}),(0,je.jsxs)(Dr,{style:{fontSize:13},children:[Ur(u)," ₽"]})]}),(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",paddingTop:10,borderTop:"1px solid #E5E7EB"},children:[(0,je.jsx)(Dr,{strong:!0,style:{fontSize:14},children:"Итого к оплате"}),(0,je.jsxs)(Dr,{strong:!0,style:{fontSize:16},children:[Ur(m)," ₽"]})]})]}),y.error&&(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:F(y.error)}),(0,je.jsxs)(Mn.A,{style:{width:"100%",justifyContent:"flex-end"},children:[(0,je.jsx)(g.Ay,{onClick:l,disabled:y.isPending,children:"Отмена"}),(0,je.jsx)(g.Ay,{type:"primary",onClick:x,loading:y.isPending,disabled:f,children:"Перейти к оплате"})]}),(0,je.jsx)(Dr,{type:"secondary",style:{fontSize:11},children:"Вы будете перенаправлены на защищённую страницу ЮKассы. Баланс пополнится автоматически после успешной оплаты."})]})})}function Kr(e){var t=e.data.map(e=>({date:Hr(e.date),spent:kr(e.spent_rub)}));return(0,je.jsx)("div",{style:{width:"100%",height:180},children:(0,je.jsx)(Xt.u,{width:"100%",height:"100%",children:(0,je.jsxs)(Zt.Q,{data:t,margin:{top:8,right:8,left:0,bottom:0},children:[(0,je.jsx)("defs",{children:(0,je.jsxs)("linearGradient",{id:"rchSpendFill",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,je.jsx)("stop",{offset:"0%",stopColor:"#1F2937",stopOpacity:.16}),(0,je.jsx)("stop",{offset:"100%",stopColor:"#1F2937",stopOpacity:.02})]})}),(0,je.jsx)(Gt.d,{stroke:"#F3F4F6",vertical:!1}),(0,je.jsx)($t.W,{dataKey:"date",tick:{fontSize:11,fill:"#9CA3AF"},axisLine:{stroke:"#E5E7EB"},tickLine:!1}),(0,je.jsx)(Vt.h,{width:48,tick:{fontSize:11,fill:"#9CA3AF"},axisLine:!1,tickLine:!1,tickFormatter:e=>function(e){if(e>=1e3){var t=e/1e3;return"".concat(t%1==0?t:t.toFixed(1),"к")}return String(e)}(e)}),(0,je.jsx)(Yt.m,{formatter:e=>["".concat(e.toLocaleString("ru-RU",{minimumFractionDigits:2,maximumFractionDigits:2})," ₽"),"Расход"],contentStyle:{fontSize:12,borderRadius:6,border:"1px solid #E5E7EB",boxShadow:"0 2px 8px rgba(0,0,0,0.06)"},labelStyle:{color:"#6B7280"},cursor:{stroke:"#E5E7EB"}}),(0,je.jsx)(Jt.Gk,{type:"monotone",dataKey:"spent",stroke:"#1F2937",strokeWidth:2,fill:"url(#rchSpendFill)",dot:{r:2.5,fill:"#1F2937",strokeWidth:0},activeDot:{r:4,fill:"#1F2937",strokeWidth:0}})]})})})}function Hr(e){try{var t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleDateString("ru-RU",{day:"2-digit",month:"2-digit"})}catch(t){return e}}var Qr=h.A.Title,Xr=h.A.Text,Zr={telegram:"Telegram",max:"MAX",widget:"Виджет"};function Gr(e){return kr(e).toLocaleString("ru-RU",{minimumFractionDigits:2,maximumFractionDigits:2})}function $r(){var e=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return(0,E.I)({queryKey:Or.overview(e),queryFn:()=>Pr.getOverview(e),staleTime:1e4,retry:(e,t)=>{var n,r=null===(n=t.response)||void 0===n?void 0:n.status;return 401!==r&&403!==r&&e<1}})}(),t=e.data,n=e.isLoading,r=e.error;return n?(0,je.jsxs)("div",{style:{display:"grid",gap:16,gridTemplateColumns:"repeat(auto-fit, minmax(280px, 1fr))"},children:[(0,je.jsx)(y.A,{children:(0,je.jsx)(m.A,{active:!0,paragraph:{rows:2}})}),(0,je.jsx)(y.A,{children:(0,je.jsx)(m.A,{active:!0,paragraph:{rows:2}})})]}):r||!t?(0,je.jsx)(y.A,{children:(0,je.jsx)(Xr,{type:"secondary",children:"Не удалось загрузить сводку."})}):(0,je.jsxs)("div",{children:[(0,je.jsxs)("div",{style:{display:"grid",gap:16,gridTemplateColumns:"repeat(auto-fit, minmax(280px, 1fr))"},children:[(0,je.jsx)(Vr,{data:t}),(0,je.jsx)(Yr,{data:t})]}),t.by_day.length>0&&(0,je.jsxs)(y.A,{style:{marginTop:16},styles:{body:{padding:20}},children:[(0,je.jsx)(Xr,{type:"secondary",style:{fontSize:12,display:"block",marginBottom:12},children:"Расход по дням"}),(0,je.jsx)(Kr,{data:t.by_day})]})]})}function Vr(e){var t=e.data,n=kr(t.total_welcome_rub);return(0,je.jsxs)(y.A,{styles:{body:{padding:20}},children:[(0,je.jsx)(Xr,{type:"secondary",style:{fontSize:12},children:"Оплачено"}),(0,je.jsxs)(Qr,{level:3,style:{margin:"4px 0 0",fontWeight:500,color:"#1F2937"},children:[Gr(t.total_paid_rub)," ₽"]}),n>0&&(0,je.jsxs)("div",{style:{marginTop:14,paddingTop:14,borderTop:"1px solid #F3F4F6",display:"flex",justifyContent:"space-between",alignItems:"center"},children:[(0,je.jsxs)("span",{children:[(0,je.jsx)(ve.A,{bordered:!1,color:"success",style:{fontSize:11,marginRight:8},children:"бонус"}),(0,je.jsx)(Xr,{type:"secondary",style:{fontSize:13},children:"Приветственный"})]}),(0,je.jsxs)(Xr,{style:{fontSize:13,fontWeight:500},children:[Gr(n)," ₽"]})]})]})}function Yr(e){var t=e.data;return(0,je.jsxs)(y.A,{styles:{body:{padding:20}},children:[(0,je.jsx)(Xr,{type:"secondary",style:{fontSize:12},children:"Израсходовано"}),(0,je.jsxs)(Qr,{level:3,style:{margin:"4px 0 0",fontWeight:500,color:"#1F2937"},children:[Gr(t.total_spent_rub)," ₽"]}),(0,je.jsxs)("div",{style:{marginTop:14,paddingTop:14,borderTop:"1px solid #F3F4F6"},children:[(0,je.jsx)(Jr,{label:"За чат",value:t.total_chat_rub}),t.by_channel.map(e=>{var t;return(0,je.jsx)(Jr,{label:null!==(t=Zr[e.platform])&&void 0!==t?t:e.platform,value:e.spent_rub,nested:!0,suffix:"".concat(e.messages_count," сообщ.")},e.platform)}),(0,je.jsx)("div",{style:{marginTop:8},children:(0,je.jsx)(Jr,{label:"За базу знаний",value:t.total_ingest_rub})})]})]})}function Jr(e){var t=e.label,n=e.value,r=e.nested,i=void 0!==r&&r,s=e.suffix;return(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",padding:"3px 0",paddingLeft:i?14:0},children:[(0,je.jsxs)(Xr,{type:"secondary",style:{fontSize:13,fontWeight:i?400:500},children:[i&&(0,je.jsx)("span",{style:{color:"#9CA3AF",marginRight:6},children:"└"}),t,s&&(0,je.jsx)(Xr,{type:"secondary",style:{fontSize:11,marginLeft:6,color:"#9CA3AF"},children:s})]}),(0,je.jsxs)(Xr,{style:{fontSize:13,fontWeight:i?400:500,color:i?"#6B7280":"#1A1A1A"},children:[Gr(n)," ₽"]})]})}function ei(e){var t,n,r,s,l=e.paymentIntentId,a=e.onResolved,o=(n=l,(0,E.I)({queryKey:Or.paymentIntent(null!=n?n:""),queryFn:()=>Pr.getPaymentIntentStatus(n),enabled:!!n,refetchInterval:e=>{var t=e.state.data;return t?"pending"===t.status&&2e3:2e3},staleTime:0,retry:(e,t)=>{var n,r=null===(n=t.response)||void 0===n?void 0:n.status;return 401!==r&&403!==r&&404!==r&&e<2}})),c=o.data,d=o.isLoading,u=o.error,h=(r=(0,i.jE)(),e=>{r.invalidateQueries({queryKey:Or.summary(e)}),r.invalidateQueries({queryKey:[...Or.all,"transactions"]}),r.invalidateQueries({queryKey:[...Or.all,"overview"]}),r.invalidateQueries({queryKey:N.me()})}),y=(0,L.useRef)(!1);return(0,L.useEffect)(()=>{c&&"pending"!==c.status&&(y.current||(y.current=!0,"succeeded"===c.status&&h(""),null==a||a()))},[c,h,a]),u?(0,je.jsx)(p.A,{type:"error",showIcon:!0,closable:!0,message:"Не удалось проверить статус платежа",description:"Если деньги списались, баланс обновится в течение нескольких минут. Обновите страницу.",style:{marginBottom:16}}):d||!c||"pending"===c.status?(0,je.jsx)(p.A,{type:"info",showIcon:!0,icon:(0,je.jsx)(Pe.A,{size:"small"}),message:"Обрабатываем платёж...",description:"Это занимает несколько секунд. Не закрывайте страницу.",style:{marginBottom:16}}):"succeeded"===c.status?(0,je.jsx)(p.A,{type:"success",showIcon:!0,closable:!0,onClose:a,message:"Баланс пополнен",description:"Платёж на ".concat(kr(c.amount_rub).toLocaleString("ru-RU")," ₽ успешно обработан."),style:{marginBottom:16}}):"canceled"===c.status?(0,je.jsx)(p.A,{type:"warning",showIcon:!0,closable:!0,onClose:a,message:"Платёж отменён",description:null!==(s=c.fail_reason)&&void 0!==s?s:"Вы отменили оплату. Баланс не изменился.",style:{marginBottom:16}}):(0,je.jsx)(p.A,{type:"error",showIcon:!0,closable:!0,onClose:a,message:"Платёж не прошёл",description:null!==(t=c.fail_reason)&&void 0!==t?t:"Что-то пошло не так при оплате. Попробуйте ещё раз.",style:{marginBottom:16}})}var ti=n(93298),ni=n(74353),ri=n.n(ni);function ii(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,l,a=[],o=!0,c=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;o=!1}else for(;!(o=(r=s.call(n)).done)&&(a.push(r.value),a.length!==t);o=!0);}catch(e){c=!0,i=e}finally{try{if(!o&&null!=n.return&&(l=n.return(),Object(l)!==l))return}finally{if(c)throw i}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return si(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?si(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function si(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t,n;return null!==(t=null===(n=e.user)||void 0===n?void 0:n.assistants)&&void 0!==t?t:[]}),n=ii((0,L.useState)(),2),r=n[0],i=n[1],s=ii((0,L.useState)(),2),l=s[0],a=s[1],o=ii((0,L.useState)(null),2),c=o[0],d=o[1],u=(0,L.useMemo)(()=>{var e,t;return{assistant_id:r,kind:l,date_from:null==c||null===(e=c[0])||void 0===e?void 0:e.startOf("day").toISOString(),date_to:null==c||null===(t=c[1])||void 0===t?void 0:t.endOf("day").toISOString()}},[r,l,c]),h=!!(r||l||c),y=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:50,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return(0,E.I)({queryKey:Or.transactions(t),queryFn:()=>Pr.getUserTransactions(e,0,t),staleTime:1e4,retry:(e,t)=>{var n,r=null===(n=t.response)||void 0===n?void 0:n.status;return 401!==r&&403!==r&&e<1}})}(50,u),p=y.data,f=y.isLoading,x=y.error,v=t.map(e=>({value:e.id,label:e.name})),j=[{title:"Дата",dataIndex:"created_at",key:"created_at",width:150,render:e=>(0,je.jsx)(li,{type:"secondary",style:{fontSize:13},children:ui(e)})},{title:"Ассистент",dataIndex:"assistant_name",key:"assistant_name",render:e=>(0,je.jsx)(li,{style:{fontSize:13},children:null!=e?e:"—"})},{title:"Операция",dataIndex:"kind",key:"kind",render:e=>(0,je.jsx)(ve.A,{bordered:!1,color:di(e),style:{fontSize:12},children:zr(e)})},{title:"Сумма",dataIndex:"amount_rub",key:"amount_rub",align:"right",render:e=>{var t=kr(e),n=t>0;return(0,je.jsxs)(li,{style:{fontSize:13,fontWeight:500,color:n?"#16A34A":"#1A1A1A"},children:[n?"+":"",t.toLocaleString("ru-RU",{minimumFractionDigits:2,maximumFractionDigits:2})," ","₽"]})}},{title:"Баланс после",dataIndex:"balance_after_rub",key:"balance_after_rub",align:"right",responsive:["md"],render:e=>(0,je.jsxs)(li,{type:"secondary",style:{fontSize:13},children:[kr(e).toLocaleString("ru-RU",{minimumFractionDigits:2,maximumFractionDigits:2})," ","₽"]})}],b=null!==(e=null==p?void 0:p.transactions)&&void 0!==e?e:[];return(0,je.jsxs)("div",{children:[(0,je.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:8,alignItems:"center",padding:"4px 4px 16px"},children:[(0,je.jsx)(Ht.A,{allowClear:!0,placeholder:"Ассистент",style:{minWidth:180},value:r,onChange:i,options:v,size:"middle"}),(0,je.jsx)(Ht.A,{allowClear:!0,placeholder:"Тип операции",style:{minWidth:200},value:l,onChange:a,options:oi,size:"middle"}),(0,je.jsx)(ai,{value:c,onChange:e=>d(e),format:"DD.MM.YYYY",placeholder:["С","По"]}),h&&(0,je.jsx)(g.Ay,{type:"text",onClick:()=>{i(void 0),a(void 0),d(null)},style:{color:"#6B7280"},children:"Сбросить"})]}),f?(0,je.jsx)(m.A,{active:!0,paragraph:{rows:4}}):x?(0,je.jsx)(li,{type:"secondary",children:"Не удалось загрузить историю транзакций."}):0===b.length?(0,je.jsx)(X.A,{image:X.A.PRESENTED_IMAGE_SIMPLE,description:(0,je.jsx)(li,{type:"secondary",children:h?"Нет операций под выбранные фильтры.":"История операций появится после первого пополнения или списания."})}):(0,je.jsx)(Qt.A,{columns:j,dataSource:b,rowKey:"id",size:"middle",pagination:b.length>15&&{pageSize:15,showSizeChanger:!1}})]})}function di(e){return"topup"===e||e.startsWith("topup_")?"green":"paid_expired"===e?"red":e.startsWith("channel_message")||e.endsWith("_ingest")?"default":"admin_adjustment"===e?"blue":"default"}function ui(e){try{return ri()(e).format("DD.MM.YYYY HH:mm")}catch(t){return e}}function hi(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,l,a=[],o=!0,c=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;o=!1}else for(;!(o=(r=s.call(n)).done)&&(a.push(r.value),a.length!==t);o=!0);}catch(e){c=!0,i=e}finally{try{if(!o&&null!=n.return&&(l=n.return(),Object(l)!==l))return}finally{if(c)throw i}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return yi(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?yi(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function yi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{var t,n;return null!==(t=null===(n=e.user)||void 0===n?void 0:n.assistants)&&void 0!==t?t:[]}),t=q(e=>null!==e.user),n=hi((0,d.ok)(),2),r=n[0],i=n[1],s=r.get("payment_intent"),l=hi((0,L.useState)(null),2),a=l[0],o=l[1];return(0,je.jsxs)("div",{children:[(0,je.jsx)(mi,{level:2,style:{marginTop:0,marginBottom:4},children:"Биллинг"}),(0,je.jsx)(pi,{type:"secondary",children:"Баланс ассистентов и история операций. Списание идёт за вопросы в боевых каналах."}),s&&(0,je.jsx)("div",{style:{marginTop:20},children:(0,je.jsx)(ei,{paymentIntentId:s,onResolved:()=>{r.delete("payment_intent"),i(r,{replace:!0})}})}),(0,je.jsx)("div",{style:{marginTop:24},children:(0,je.jsx)($r,{})}),(0,je.jsxs)("div",{style:{marginTop:32},children:[(0,je.jsx)(mi,{level:4,style:{marginBottom:16},children:"Балансы ассистентов"}),t?0===e.length?(0,je.jsx)(y.A,{children:(0,je.jsx)(X.A,{image:X.A.PRESENTED_IMAGE_SIMPLE,description:(0,je.jsx)(pi,{type:"secondary",children:"У вас пока нет ассистентов. Создайте первого — он получит приветственный баланс."})})}):(0,je.jsx)("div",{style:{display:"grid",gap:16,gridTemplateColumns:"repeat(auto-fill, minmax(280px, 1fr))"},children:e.map(e=>{var t=kr(e.balance),n=t<100;return(0,je.jsxs)(y.A,{styles:{body:{padding:20}},children:[(0,je.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:12},children:[(0,je.jsx)(pi,{style:{fontSize:14,fontWeight:500},ellipsis:{tooltip:e.name},children:e.name}),n&&(0,je.jsx)(ve.A,{bordered:!1,color:"warning",style:{fontSize:11,margin:0},children:"Низкий"})]}),(0,je.jsxs)(mi,{level:3,style:{margin:0,marginBottom:16,fontWeight:500,color:n?"#B45309":"#1F2937"},children:[t.toLocaleString("ru-RU",{minimumFractionDigits:2,maximumFractionDigits:2})," ","₽"]}),(0,je.jsx)(g.Ay,{icon:(0,je.jsx)($.A,{}),block:!0,onClick:()=>o({id:e.id,name:e.name}),children:"Пополнить"})]},e.id)})}):(0,je.jsx)(y.A,{children:(0,je.jsx)(m.A,{active:!0,paragraph:{rows:2}})})]}),(0,je.jsxs)("div",{style:{marginTop:32},children:[(0,je.jsx)(mi,{level:4,style:{marginBottom:16},children:"История операций"}),(0,je.jsx)(y.A,{styles:{body:{padding:0}},children:(0,je.jsx)("div",{style:{padding:4},children:(0,je.jsx)(ci,{})})})]}),a&&(0,je.jsx)(Nr,{open:!!a,assistantId:a.id,assistantName:a.name,onClose:()=>o(null)})]})}var fi=n(50329),xi=n(93598);function vi(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function ji(e){var t,n,r=e.channel,s=(t=e.assistantId,n=(0,i.jE)(),(0,P.n)({mutationFn:e=>Yn(e),onSuccess:(e,r)=>{n.removeQueries({queryKey:Jn.stats(r)}),n.invalidateQueries({queryKey:Jn.list(t)})}}));return(0,je.jsx)(g.Ay,{danger:!0,type:"text",icon:(0,je.jsx)(xi.A,{}),onClick:()=>{Be.A.confirm({title:"Отключить канал?",content:(0,je.jsxs)("div",{children:[(0,je.jsxs)("p",{style:{marginTop:0},children:["Бот ",(0,je.jsxs)("b",{children:["@",r.bot_username]})," перестанет отвечать пользователям."]}),(0,je.jsx)("p",{style:{marginBottom:0,fontSize:13,color:"#6B7280"},children:"История диалогов сохраняется в БД, но скрывается из кабинета. Переподключить бот можно — это будет новый канал."})]}),okText:"Отключить",okButtonProps:{danger:!0},cancelText:"Отмена",onOk(){return(e=function*(){try{yield s.mutateAsync(r.id),Ve.Ay.success("Канал отключён")}catch(e){throw Ve.Ay.error(F(e,"Не удалось отключить канал")),e}},function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){vi(s,r,i,l,a,"next",e)}function a(e){vi(s,r,i,l,a,"throw",e)}l(void 0)})})();var e}})},loading:s.isPending,children:"Отключить"})}function bi(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function Ai(e){var t,n,r=e.channel,s=(t=e.assistantId,n=(0,i.jE)(),(0,P.n)({mutationFn:e=>{var t=e.channelId,n=e.payload;return Vn(t,n)},onSuccess:(e,r)=>{var i=r.channelId;n.invalidateQueries({queryKey:Jn.list(t)}),n.invalidateQueries({queryKey:Jn.stats(i)})}})),l="disabled"===r.status,a="active"===r.status,o=function(){var e,t=(e=function*(e){try{yield s.mutateAsync({channelId:r.id,payload:{status:e?"active":"paused"}})}catch(e){Ve.Ay.error(F(e,"Не удалось переключить статус"))}},function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){bi(s,r,i,l,a,"next",e)}function a(e){bi(s,r,i,l,a,"throw",e)}l(void 0)})});return function(e){return t.apply(this,arguments)}}();return(0,je.jsx)(Oe.A,{checked:a,onChange:o,loading:s.isPending,disabled:l,checkedChildren:"Активен",unCheckedChildren:"Пауза"})}var wi=h.A.Text,_i=h.A.Title;function Si(e){var t,n=e.channel,r=e.assistantId,i=tr(n.id),s=i.data,l=i.isLoading;return(0,je.jsx)(y.A,{children:(0,je.jsxs)(Mn.A,{direction:"vertical",style:{width:"100%"},size:16,children:[(0,je.jsxs)("div",{children:[(0,je.jsxs)(Mn.A,{wrap:!0,size:8,children:[(0,je.jsxs)(wi,{strong:!0,style:{fontSize:16},children:["@",n.bot_username]}),(0,je.jsx)(ve.A,{color:Kn[n.platform],children:Un[n.platform]}),(0,je.jsx)(Fi,{status:n.status})]}),n.bot_display_name&&(0,je.jsx)("div",{style:{marginTop:4},children:(0,je.jsx)(wi,{type:"secondary",style:{fontSize:13},children:n.bot_display_name})}),(0,je.jsx)("div",{style:{marginTop:4},children:(0,je.jsxs)(wi,{type:"secondary",style:{fontSize:12},children:["Подключён ",new Date(n.created_at).toLocaleDateString("ru-RU")]})})]}),n.last_error&&(0,je.jsx)(p.A,{type:"warning",showIcon:!0,message:"Последняя ошибка",description:(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)("div",{children:n.last_error}),n.last_error_at&&(0,je.jsx)(wi,{type:"secondary",style:{fontSize:12},children:new Date(n.last_error_at).toLocaleString("ru-RU")})]})}),(0,je.jsxs)("div",{children:[(0,je.jsx)(_i,{level:5,style:{marginTop:0,marginBottom:8},children:"Активность"}),(0,je.jsxs)(Mn.A,{direction:"vertical",size:4,children:[(0,je.jsx)(Ai,{channel:n,assistantId:r}),(0,je.jsx)(wi,{type:"secondary",style:{fontSize:12},children:"На паузе — бот не отвечает на сообщения, но соединение сохраняется. Можно включить обратно в один клик."})]})]}),(0,je.jsxs)("div",{children:[(0,je.jsx)(_i,{level:5,style:{marginTop:0,marginBottom:8},children:"Статистика"}),(0,je.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, 1fr)",gap:12,padding:"14px 16px",background:"#F9FAFB",borderRadius:8},children:[(0,je.jsx)(Ti,{label:"Диалогов",value:null==s?void 0:s.dialogs_count,loading:l}),(0,je.jsx)(Ti,{label:"Сообщений всего",value:null==s?void 0:s.messages_total,loading:l}),(0,je.jsx)(Ti,{label:"Сообщений за 24ч",value:null==s?void 0:s.messages_last_24h,loading:l}),(0,je.jsx)(Ti,{label:"Списано за 24ч",value:s?(t=s.cost_last_24h_rub,"".concat(t.toFixed(2)," ₽")):void 0,loading:l})]})]}),(0,je.jsxs)("div",{children:[(0,je.jsx)(_i,{level:5,style:{marginTop:0,marginBottom:8},children:"Опасная зона"}),(0,je.jsxs)(Mn.A,{direction:"vertical",size:8,children:[(0,je.jsx)(wi,{type:"secondary",style:{fontSize:13},children:"Отключение канала удалит привязку бота. История диалогов остаётся в БД, но скрывается из UI. Переподключить можно — это будет новый канал с нулевой статистикой."}),(0,je.jsx)(ji,{channel:n,assistantId:r})]})]})]})})}function Fi(e){var t=e.status,n="active"===t?"success":"paused"===t?"warning":"error";return(0,je.jsx)(ve.A,{color:n,children:Hn[t]})}function Ti(e){var t=e.label,n=e.value,r=e.loading;return(0,je.jsxs)("div",{children:[(0,je.jsx)(wi,{type:"secondary",style:{fontSize:11},children:t}),(0,je.jsx)("div",{children:r?(0,je.jsx)(wi,{type:"secondary",children:"…"}):(0,je.jsx)(wi,{strong:!0,style:{fontSize:14},children:null!=n?n:"—"})})]})}function Ii(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function ki(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){Ii(s,r,i,l,a,"next",e)}function a(e){Ii(s,r,i,l,a,"throw",e)}l(void 0)})}}var Ci=e=>ki(function*(){return(yield _.get("/widgets/".concat(e,"/config"))).data})(),zi=(e,t)=>ki(function*(){return(yield _.patch("/widgets/".concat(e,"/config"),t)).data})(),Bi=e=>ki(function*(){return(yield _.get("/widgets/".concat(e,"/snippet"))).data})(),Ei={all:["widget-config"],config:e=>[...Ei.all,"config",e],snippet:e=>[...Ei.all,"snippet",e]},Pi=n(11503),Oi=n(39356);function qi(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function Li(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,l,a=[],o=!0,c=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;o=!1}else for(;!(o=(r=s.call(n)).done)&&(a.push(r.value),a.length!==t);o=!0);}catch(e){c=!0,i=e}finally{try{if(!o&&null!=n.return&&(l=n.return(),Object(l)!==l))return}finally{if(c)throw i}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Ri(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ri(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Ri(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);nzi(t,e),onSuccess:e=>{n.setQueryData(Ei.config(t),e)}}));(0,L.useEffect)(()=>{s.setFieldsValue(Ki(r)),o(!1)},[r,s]);var d=function(){var e,t=(e=function*(e){var t=function(e,t){var n={};e.display_name!==t.display_name&&(n.display_name=e.display_name),e.avatar_url!==t.avatar_url&&(n.avatar_url=e.avatar_url),e.greeting!==t.greeting&&(n.greeting=e.greeting),e.brand_color!==t.brand_color&&(n.brand_color=e.brand_color),e.position!==t.position&&(n.position=e.position),e.theme!==t.theme&&(n.theme=e.theme),e.images_enabled!==t.images_enabled&&(n.images_enabled=e.images_enabled),e.proactive_enabled!==t.proactive_enabled&&(n.proactive_enabled=e.proactive_enabled),e.proactive_delay_sec!==t.proactive_delay_sec&&(n.proactive_delay_sec=e.proactive_delay_sec),e.proactive_show_avatar!==t.proactive_show_avatar&&(n.proactive_show_avatar=e.proactive_show_avatar),e.reset_bg_custom?n.reset_bg_custom=!0:e.bg_custom!==t.bg_custom&&(n.bg_custom=e.bg_custom),e.reset_bot_bg_custom?n.reset_bot_bg_custom=!0:e.bot_bg_custom!==t.bot_bg_custom&&(n.bot_bg_custom=e.bot_bg_custom);var r=e.allowed_origins_text.split("\n").map(e=>e.trim()).filter(Boolean);return function(e,t){if(e.length!==t.length)return!1;for(var n=0;n{o(!0)},onFinish:d,disabled:c.isPending,children:[(0,je.jsx)($e.A.Item,{name:"display_name",label:"Имя ассистента в шапке",rules:[{required:!0,message:"Введите имя"},{max:100,message:"Максимум 100 символов"}],extra:"Отображается в шапке окна чата и в проактивном bubble",children:(0,je.jsx)(Ye.A,{placeholder:"Например, Анна"})}),(0,je.jsx)($e.A.Item,{name:"brand_color",label:"Бренд-цвет",rules:[{required:!0}],extra:"Цвет кнопки виджета, bubble юзера и кнопки отправки. Контрастный текст подбирается автоматически.",getValueFromEvent:e=>null!=e&&e.toHexString?e.toHexString().toUpperCase():e,children:(0,je.jsx)(Pi.A,{showText:!0,format:"hex"})}),(0,je.jsx)($e.A.Item,{name:"position",label:"Позиция на странице",rules:[{required:!0}],children:(0,je.jsxs)(gr.Ay.Group,{children:[(0,je.jsx)(gr.Ay.Button,{value:"right",children:"Справа снизу"}),(0,je.jsx)(gr.Ay.Button,{value:"left",children:"Слева снизу"})]})}),(0,je.jsx)($e.A.Item,{name:"theme",label:"Тема",rules:[{required:!0}],children:(0,je.jsxs)(gr.Ay.Group,{children:[(0,je.jsx)(gr.Ay.Button,{value:"auto",children:"Авто"}),(0,je.jsx)(gr.Ay.Button,{value:"light",children:"Светлая"}),(0,je.jsx)(gr.Ay.Button,{value:"dark",children:"Тёмная"})]})}),(0,je.jsx)($e.A.Item,{name:"allowed_origins_text",label:"Разрешённые домены",extra:"По одному домену на строку. Виджет отвечает только если страница, на которой он встроен, имеет один из этих origin'ов. Защита от использования вашего ключа третьими сторонами.",rules:[{required:!0,message:"Добавьте хотя бы один домен"},{validator:(e,t)=>{if(!t||!t.trim())return Promise.reject(new Error("Добавьте хотя бы один домен"));var n=t.split("\n").map(e=>e.trim()).filter(Boolean).find(e=>!function(e){try{var t=new URL(e);return"http:"===t.protocol||"https:"===t.protocol}catch(e){return!1}}(e));return n?Promise.reject(new Error("Не похоже на domain: «".concat(n,"»"))):Promise.resolve()}}],children:(0,je.jsx)(Ye.A.TextArea,{rows:4,placeholder:"https://example.com\nhttps://www.example.com"})}),(0,je.jsx)(Oi.A,{ghost:!0,size:"small",items:[{key:"appearance",label:"Дополнительный внешний вид",children:(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)($e.A.Item,{name:"avatar_url",label:"URL аватара",extra:"Картинка ассистента в шапке. Если не задано — используется фавиконка сайта клиента.",rules:[{type:"url",message:"Должен быть HTTP/HTTPS URL",validateTrigger:"onBlur"}],children:(0,je.jsx)(Ye.A,{placeholder:"https://..."})}),(0,je.jsx)($e.A.Item,{name:"greeting",label:"Приветствие",rules:[{max:500,message:"Максимум 500 символов"}],extra:"Показывается в пустом чате и в проактивном bubble.",children:(0,je.jsx)(Ye.A.TextArea,{rows:2,placeholder:"Здравствуйте! Чем могу помочь?"})}),(0,je.jsx)(Ni,{name:"bg_custom",resetName:"reset_bg_custom",label:"Фон окна чата (опционально)",hint:"Если не задан — берётся из темы (белый/тёмный)",form:s}),(0,je.jsx)(Ni,{name:"bot_bg_custom",resetName:"reset_bot_bg_custom",label:"Фон bubble ассистента (опционально)",hint:"Если не задан — светло-серый/тёмный из темы",form:s})]})},{key:"features",label:"Функции",children:(0,je.jsx)($e.A.Item,{name:"images_enabled",valuePropName:"checked",extra:"Если выключено — картинки скрываются в ответах ассистента (быстрее ответ, меньше байт).",children:(0,je.jsx)(Ui,{label:"Показывать картинки в ответах"})})},{key:"proactive",label:"Проактивный bubble",children:(0,je.jsxs)(je.Fragment,{children:[(0,je.jsx)($e.A.Item,{name:"proactive_enabled",valuePropName:"checked",extra:"Через N секунд над кнопкой виджета всплывёт приветствие. Привлекает внимание, повышает конверсию в открытие чата.",children:(0,je.jsx)(Ui,{label:"Показывать приветствие"})}),(0,je.jsx)($e.A.Item,{name:"proactive_delay_sec",label:"Задержка перед показом, секунд",rules:[{required:!0,type:"number",min:0,max:300}],children:(0,je.jsx)(qr.A,{min:0,max:300,step:1,style:{width:120}})}),(0,je.jsx)($e.A.Item,{name:"proactive_show_avatar",valuePropName:"checked",extra:"С аватаром — компактнее, без — больше места для приветствия.",children:(0,je.jsx)(Ui,{label:"Показывать аватар в bubble"})})]})}]}),c.error&&(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:F(c.error,"Ошибка сохранения"),style:{marginTop:16}}),(0,je.jsxs)(Mn.A,{style:{marginTop:24},children:[(0,je.jsx)(g.Ay,{type:"primary",htmlType:"submit",loading:c.isPending,disabled:!a,children:"Сохранить"}),(0,je.jsx)(g.Ay,{onClick:()=>{s.setFieldsValue(Ki(r)),o(!1)},disabled:!a||c.isPending,children:"Отменить изменения"})]}),!a&&!c.isPending&&(0,je.jsx)(Wi,{type:"secondary",style:{fontSize:12,marginTop:8,marginBottom:0},children:"Изменения применяются сразу после сохранения. Виджет обновляется при следующей загрузке страницы."})]})}function Ui(e){var t=e.label,n=e.value,r=e.onChange;return(0,je.jsxs)(Mn.A,{size:12,children:[(0,je.jsx)(Oe.A,{checked:n,onChange:r}),(0,je.jsx)(Di,{children:t})]})}function Ni(e){var t=e.name,n=e.resetName,r=e.label,i=e.hint,s=e.form,l=$e.A.useWatch(t,s),a=null!=l&&""!==l;return(0,je.jsxs)($e.A.Item,{label:r,extra:i,style:{marginBottom:12},children:[(0,je.jsxs)(Mn.A,{children:[(0,je.jsx)(Pi.A,{value:null!=l?l:"#FFFFFF",onChange:e=>{var r,i="string"==typeof e?e.toUpperCase():null==e||null===(r=e.toHexString)||void 0===r||null===(r=r.call(e))||void 0===r?void 0:r.toUpperCase();s.setFieldValue(t,i),s.setFieldValue(n,!1)},showText:!0,format:"hex",disabledAlpha:!0}),a&&(0,je.jsx)(g.Ay,{size:"small",type:"link",onClick:()=>{s.setFieldValue(t,null),s.setFieldValue(n,!0),s.validateFields([t])},children:"Сбросить"}),!a&&(0,je.jsx)(Di,{type:"secondary",style:{fontSize:12},children:"не задан"})]}),(0,je.jsx)($e.A.Item,{name:n,hidden:!0,initialValue:!1,children:(0,je.jsx)(Ye.A,{type:"hidden"})})]})}function Ki(e){return{display_name:e.display_name,avatar_url:e.avatar_url,greeting:e.greeting,brand_color:e.brand_color,bg_custom:e.bg_custom,reset_bg_custom:!1,bot_bg_custom:e.bot_bg_custom,reset_bot_bg_custom:!1,position:e.position,theme:e.theme,images_enabled:e.images_enabled,proactive_enabled:e.proactive_enabled,proactive_delay_sec:e.proactive_delay_sec,proactive_show_avatar:e.proactive_show_avatar,allowed_origins_text:e.allowed_origins.join("\n")}}var Hi=n(26067),Qi=n(57046);function Xi(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function Zi(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);nBi(r),enabled:!!r,staleTime:1/0})),s=i.data,l=i.isLoading,a=i.error,o=(t=(0,L.useState)(!1),n=2,function(e){if(Array.isArray(e))return e}(t)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,l,a=[],o=!0,c=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;o=!1}else for(;!(o=(r=s.call(n)).done)&&(a.push(r.value),a.length!==t);o=!0);}catch(e){c=!0,i=e}finally{try{if(!o&&null!=n.return&&(l=n.return(),Object(l)!==l))return}finally{if(c)throw i}}return a}}(t,n)||function(e,t){if(e){if("string"==typeof e)return Zi(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Zi(e,t):void 0}}(t,n)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),c=o[0],d=o[1];if(l)return(0,je.jsx)(m.A,{active:!0,paragraph:{rows:2}});if(a)return(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:"Не удалось загрузить сниппет",description:F(a)});if(!s)return null;var u=function(){var e,t=(e=function*(){try{yield navigator.clipboard.writeText(s.snippet),d(!0),Ve.Ay.success("Сниппет скопирован"),setTimeout(()=>d(!1),2e3)}catch(e){Ve.Ay.error("Не удалось скопировать. Выделите и скопируйте вручную.")}},function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){Xi(s,r,i,l,a,"next",e)}function a(e){Xi(s,r,i,l,a,"throw",e)}l(void 0)})});return function(){return t.apply(this,arguments)}}();return(0,je.jsxs)("div",{children:[(0,je.jsxs)(Gi,{type:"secondary",style:{fontSize:13,marginBottom:8},children:["Вставьте этот код в любое место HTML-страницы вашего сайта — лучше перед закрывающим ",(0,je.jsx)("code",{children:""}),". Виджет появится автоматически."]}),(0,je.jsxs)("div",{style:{position:"relative",background:"#F6F6F7",border:"1px solid #EFEFF1",borderRadius:8,padding:"14px 16px",paddingRight:56},children:[(0,je.jsx)("pre",{style:{margin:0,fontFamily:'ui-monospace, "SF Mono", Menlo, Consolas, monospace',fontSize:12,lineHeight:1.6,whiteSpace:"pre-wrap",wordBreak:"break-all",color:"#1F1F1F"},children:s.snippet}),(0,je.jsx)(g.Ay,{type:"text",icon:c?(0,je.jsx)(Hi.A,{}):(0,je.jsx)(Qi.A,{}),onClick:u,style:{position:"absolute",top:8,right:8},"aria-label":c?"Скопировано":"Копировать сниппет"})]}),(0,je.jsxs)(Gi,{type:"secondary",style:{fontSize:12,marginTop:8,marginBottom:0},children:["Ключ: ",(0,je.jsx)($i,{code:!0,children:s.publishable_key}),"."," ","Этот ключ привязан к разрешённым доменам — даже если кто-то скопирует сниппет, виджет не запустится на чужом сайте."]})]})}var Yi=h.A.Title,Ji=h.A.Text;function es(e){var t,n=e.channel,r=e.assistantId,i=(t=n.id,(0,E.I)({queryKey:Ei.config(null!=t?t:""),queryFn:()=>Ci(t),enabled:!!t,staleTime:1e4})),s=i.data,l=i.isLoading,a=i.error;return(0,je.jsxs)(Mn.A,{direction:"vertical",style:{width:"100%"},size:16,children:[(0,je.jsx)(y.A,{children:(0,je.jsxs)(Mn.A,{wrap:!0,size:8,children:[(0,je.jsx)(ve.A,{color:Kn[n.platform],children:Un[n.platform]}),(0,je.jsx)(ts,{status:n.status}),(0,je.jsxs)(Ji,{type:"secondary",style:{fontSize:12},children:["Создан ",new Date(n.created_at).toLocaleDateString("ru-RU")]})]})}),(0,je.jsxs)(y.A,{children:[(0,je.jsx)(Yi,{level:5,style:{marginTop:0,marginBottom:12},children:"Код для вставки на сайт"}),(0,je.jsx)(Vi,{channelId:n.id})]}),(0,je.jsxs)(y.A,{children:[(0,je.jsx)(Yi,{level:5,style:{marginTop:0,marginBottom:12},children:"Настройки виджета"}),l&&(0,je.jsx)(m.A,{active:!0,paragraph:{rows:6}}),a&&(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:"Не удалось загрузить настройки",description:F(a)}),s&&(0,je.jsx)(Mi,{config:s})]}),(0,je.jsxs)(y.A,{children:[(0,je.jsx)(Yi,{level:5,style:{marginTop:0,marginBottom:8},children:"Опасная зона"}),(0,je.jsxs)(Mn.A,{direction:"vertical",size:8,children:[(0,je.jsx)(Ji,{type:"secondary",style:{fontSize:13},children:"Отключение виджета сделает ключ невалидным — виджет перестанет работать на всех сайтах где вставлен сниппет. История переписки с посетителями остаётся в БД, но скрывается из UI."}),(0,je.jsx)(ji,{channel:n,assistantId:r})]})]})]})}function ts(e){var t=e.status,n="active"===t?"success":"paused"===t?"warning":"error";return(0,je.jsx)(ve.A,{color:n,children:Hn[t]})}var ns=h.A.Title,rs=h.A.Text;function is(){var e,t=(0,u.Zp)(),n=(0,u.g)(),r=n.id,i=n.channelId,s=function(e){var t,n=er((0,u.g)().id);if(!e)return{data:void 0,isLoading:!1,error:null};if(n.isLoading)return{data:void 0,isLoading:!0,error:null};if(n.error)return{data:void 0,isLoading:!1,error:n.error};var r=null===(t=n.data)||void 0===t?void 0:t.find(t=>t.id===e);return r?{data:r,isLoading:!1,error:null}:{data:void 0,isLoading:!1,error:new Error("Канал не найден")}}(i),l=s.data,a=s.isLoading,o=s.error;if(!r||!i)return(0,je.jsx)(p.A,{type:"error",message:"Не указан ID в URL"});var c=()=>{t("/assistants/".concat(r,"?tab=channels"))};return a?(0,je.jsx)(y.A,{children:(0,je.jsx)(m.A,{active:!0,paragraph:{rows:6}})}):o?(0,je.jsxs)("div",{style:{maxWidth:720},children:[(0,je.jsx)(g.Ay,{type:"link",icon:(0,je.jsx)(fi.A,{}),onClick:c,style:{paddingLeft:0,marginBottom:8},children:"К каналам"}),(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:"Канал не найден",description:F(o)})]}):l?(0,je.jsxs)("div",{children:[(0,je.jsx)(g.Ay,{type:"link",icon:(0,je.jsx)(fi.A,{}),onClick:c,style:{paddingLeft:0,marginBottom:8},children:"К каналам"}),(0,je.jsx)(ns,{level:3,style:{marginTop:0,marginBottom:4},children:null!==(e=l.bot_display_name)&&void 0!==e?e:l.bot_username}),(0,je.jsxs)(rs,{type:"secondary",style:{fontSize:12},children:["ID: ",l.id]}),(0,je.jsx)("div",{style:{marginTop:24},children:"widget"===l.platform?(0,je.jsx)(es,{channel:l,assistantId:r}):(0,je.jsx)(Si,{channel:l,assistantId:r})})]}):null}function ss(e,t,n,r,i,s,l){try{var a=e[s](l),o=a.value}catch(e){return void n(e)}a.done?t(o):Promise.resolve(o).then(r,i)}function ls(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function l(e){ss(s,r,i,l,a,"next",e)}function a(e){ss(s,r,i,l,a,"throw",e)}l(void 0)})}}function as(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,l,a=[],o=!0,c=!1;try{if(s=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;o=!1}else for(;!(o=(r=s.call(n)).done)&&(a.push(r.value),a.length!==t);o=!0);}catch(e){c=!0,i=e}finally{try{if(!o&&null!=n.return&&(l=n.return(),Object(l)!==l))return}finally{if(c)throw i}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return os(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?os(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function os(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n{e("/assistants/".concat(t,"?tab=channels"))},style:{paddingLeft:0,marginBottom:8},children:"К каналам"}),(0,je.jsx)(cs,{level:3,style:{marginTop:0,marginBottom:4},children:"Подключить новый канал"}),!s&&(0,je.jsx)(ys,{onPick:e=>i({type:e})}),"telegram"===s&&(0,je.jsx)(ms,{platform:"telegram",assistantId:t,onBack:()=>i({})}),"max"===s&&(0,je.jsx)(ms,{platform:"max",assistantId:t,onBack:()=>i({})}),"widget"===s&&(0,je.jsx)(gs,{assistantId:t,onBack:()=>i({})})]}):(0,je.jsx)(p.A,{type:"error",message:"Не указан assistant_id в URL"})}function ys(e){var t=e.onPick;return(0,je.jsxs)(Mn.A,{direction:"vertical",style:{width:"100%"},size:12,children:[(0,je.jsx)(us,{type:"secondary",style:{marginBottom:8},children:"Выберите, где ваш ассистент будет отвечать пользователям."}),["widget","telegram","max"].map(e=>(0,je.jsx)(y.A,{hoverable:!0,onClick:()=>t(e),styles:{body:{padding:16}},children:(0,je.jsxs)(Mn.A,{direction:"vertical",size:2,children:[(0,je.jsx)(ds,{strong:!0,children:Un[e]}),(0,je.jsx)(ds,{type:"secondary",style:{fontSize:13},children:Nn[e]})]})},e))]})}function ms(e){var t=e.platform,n=e.assistantId,r=e.onBack,i=(0,u.Zp)(),s=as($e.A.useForm(),1)[0],l=as((0,L.useState)(null),2),a=l[0],o=l[1],c=nr(n),d=function(){var e=ls(function*(e){o(null);try{var r=yield c.mutateAsync({assistant_id:n,platform:t,bot_token:e.bot_token.trim()});Ve.Ay.success("Канал подключён"),i("/assistants/".concat(n,"/channels/").concat(r.id))}catch(e){o(F(e,"Не удалось подключить бота"))}});return function(t){return e.apply(this,arguments)}}();return(0,je.jsxs)(y.A,{children:[(0,je.jsxs)(Mn.A,{direction:"vertical",style:{width:"100%"},size:4,children:[(0,je.jsx)(ds,{strong:!0,style:{fontSize:15},children:Un[t]}),(0,je.jsx)(us,{type:"secondary",style:{marginBottom:16},children:Nn[t]})]}),(0,je.jsxs)($e.A,{form:s,layout:"vertical",onFinish:d,disabled:c.isPending,children:[(0,je.jsx)($e.A.Item,{name:"bot_token",label:"Токен бота",rules:[{required:!0,message:"Введите токен бота"},{min:10,message:"Токен слишком короткий"},{max:512,message:"Токен слишком длинный"}],extra:(0,je.jsx)(ps,{platform:t}),children:(0,je.jsx)(Ye.A.Password,{placeholder:"telegram"===t?"123456:ABCdef...":"токен из dev.max.ru",autoComplete:"off",visibilityToggle:!0})}),a&&(0,je.jsx)(p.A,{type:"error",showIcon:!0,message:a,style:{marginBottom:16}}),(0,je.jsxs)(Mn.A,{children:[(0,je.jsx)(g.Ay,{type:"primary",htmlType:"submit",loading:c.isPending,children:"Подключить"}),(0,je.jsx)(g.Ay,{onClick:r,disabled:c.isPending,children:"Назад"})]})]})]})}function ps(e){return"telegram"===e.platform?(0,je.jsxs)(ds,{type:"secondary",style:{fontSize:12},children:["Создайте бота у"," ",(0,je.jsx)("a",{href:"https://t.me/BotFather",target:"_blank",rel:"noreferrer noopener",children:"@BotFather"})," ","и скопируйте выданный токен."]}):(0,je.jsxs)(ds,{type:"secondary",style:{fontSize:12},children:["Получите токен в кабинете разработчика на"," ",(0,je.jsx)("a",{href:"https://dev.max.ru",target:"_blank",rel:"noreferrer noopener",children:"dev.max.ru"}),"."]})}function gs(e){var t=e.assistantId,n=e.onBack,r=(0,u.Zp)(),i=as($e.A.useForm(),1)[0],s=as((0,L.useState)(null),2),l=s[0],a=s[1],o=nr(t),c=function(){var e=ls(function*(e){a(null);var n=e.allowed_origins_text.split("\n").map(e=>e.trim()).filter(Boolean);try{var i=yield o.mutateAsync({assistant_id:t,platform:"widget",display_name:e.display_name.trim(),allowed_origins:n});Ve.Ay.success("Виджет создан"),r("/assistants/".concat(t,"/channels/").concat(i.id))}catch(e){a(F(e,"Не удалось создать виджет"))}});return function(t){return e.apply(this,arguments)}}();return(0,je.jsxs)(y.A,{children:[(0,je.jsxs)(Mn.A,{direction:"vertical",style:{width:"100%"},size:4,children:[(0,je.jsx)(ds,{strong:!0,style:{fontSize:15},children:"Виджет на сайт"}),(0,je.jsxs)(us,{type:"secondary",style:{marginBottom:16},children:["Чат-окно встраивается в HTML-страницу вашего сайта через один ",(0,je.jsx)("code",{children:"