import{a as oe,r as i,j as e,A as Kn,T,S as Be,R as Zn,L as J,F as Te,E as xe,u as St,b as en,I as U,c as Ct,B as L,d as wt,e as kt,f as Rt,g as Xe,C as lt,h as Tt,i as G,k as ae,l as Ft,W as Yn,m as tn,n as Qn,D as nn,o as nt,p as Xn,q as Jn,s as es,N as ts,O as ns,t as ot,v as ce,w as Oe,x as ct,y as sn,M as Fe,z as rn,G as Qe,H as me,J as ss,Q as rs,K as Se,P as is,U as Ie,V as De,X as Ee,Y as as,Z as ls,_ as os,$ as an,a0 as ln,a1 as on,a2 as jt,a3 as Pe,a4 as ee,a5 as cn,a6 as dn,a7 as un,a8 as cs,a9 as pn,aa as Lt,ab as ds,ac as st,ad as hn,ae as rt,af as It,ag as us,ah as it,ai as fn,aj as xn,ak as ps,al as hs,am as fs,an as xs,ao as gs}from"./vendor-B2aKg_eA.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const l of a)if(l.type==="childList")for(const d of l.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&r(d)}).observe(document,{childList:!0,subtree:!0});function s(a){const l={};return a.integrity&&(l.integrity=a.integrity),a.referrerPolicy&&(l.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?l.credentials="include":a.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function r(a){if(a.ep)return;a.ep=!0;const l=s(a);fetch(a.href,l)}})();const Je="/api",dt=`${Je}/v2`,Dt=`${dt}/campaign`;function gn(){const t=document.cookie.match(/csrftoken=([^ ;]+)/);if(t)return t[1]}function ie(t,n){return oe.get(`${Je}/${t}`,n)}function ue(t,n,s){const r={"X-CSRFToken":gn(),...(s==null?void 0:s.headers)||{}},a={withCredentials:!0,...s,headers:r};return oe.post(`${Je}/${t}`,n,a)}function ms(t,n){const s={"X-CSRFToken":gn()},r={withCredentials:!0,...n,headers:s};return oe.delete(`${Je}/${t}`,r)}function N(t,n){return ie(`v2/${t}/`,n)}function B(t,n,s){return ue(`v2/${t}/`,n,s)}function ys(t,n){return ms(`v2/${t}/`,n)}function ut(t){var s;const n=(s=t.response)==null?void 0:s.data;return n!=null&&n.detail?n.detail:n!=null&&n.error?n.error:t.message}const g={bluePale:{300:"#80BDFD",500:"#007BFB"},blue:{500:"#0002F3"},cyan:{500:"#00A2E8"},green:{200:"#ADE5D2",500:"#00B774"},primary:{50:"#FFFBF3",200:"#FFE3AB",500:"#F9AB0D"},orange:{500:"#FC8816"},red:{100:"#FFECEC",500:"#FF3F3F"},redPale:{400:"#FD7967"},greyF:{50:"#F7F8FA",100:"#EFF1F5",600:"#9AA0AC",700:"#6E7788"},greyS:{200:"#D1D1D6"},dark:{500:"#383540"}},js={token:{colorPrimary:"#F9AB0D",colorError:"#FF3F3F",colorText:"#383540",colorTextSecondary:"#6E7788",colorTextDisabled:"#C3C3C3",colorBgLayout:"#F7F8FA",borderRadius:6}},vs=[],_s=(t,n)=>{switch(n.type){case"ADD":return[n.payload,...t];case"REMOVE":return t.filter(s=>s.id!==n.payload);default:return t}},mn=i.createContext(vs),W=()=>i.useContext(mn);function bs({children:t}){const[n,s]=i.useReducer(_s,[]),r=(c,p)=>{const h=Math.round(Math.random()*1e9);s({type:"ADD",payload:{id:h,severity:"info",text:c,...p}}),setTimeout(()=>{a(h)},5e3)},a=c=>{s({type:"REMOVE",payload:c})},l=(c,p={})=>{r(c,{...p,severity:"error"})},u={showMessage:r,showError:l,showRequestError:c=>{l(ut(c))}};return e.jsxs(mn.Provider,{value:u,children:[t,e.jsx("div",{style:{position:"fixed",left:0,bottom:0,zIndex:2e3,display:"flex",flexDirection:"column",gap:4,padding:4},children:n.map(c=>e.jsx(Kn,{type:c.severity==="error"?"error":"info",title:c.text,closable:!0,onClose:()=>a(c.id),showIcon:!0},c.id))})]})}const tt="Панель";function Ke({current:t,prev:n}){if(t==null||n==null)return"—";const s=t-n,r=n?(s/n*100).toFixed(1):0,a=s>=0,l=a?g.green[500]:g.red[500],d=a?kt:Rt;return e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2},children:[e.jsx("span",{style:{fontWeight:500},children:t.toLocaleString("ru-RU")}),e.jsxs("span",{style:{fontSize:12,color:l,display:"flex",alignItems:"center",gap:2},children:[e.jsx(d,{style:{fontSize:10}}),Math.abs(s).toLocaleString("ru-RU")," (",a?"+":"",r,"%)"]})]})}function $t({placeholder:t,onSearch:n,options:s,onSelect:r,notFoundText:a}){const[l,d]=i.useState(""),[u,c]=St("",300);i.useEffect(()=>{n(u)},[u]);const p=o=>{d(o),c(o)},h=(o,f)=>{r(o,f),d(""),c("")};return e.jsx(en,{value:l,options:l.length>=2?s:[],onSelect:h,onChange:p,style:{width:"100%"},notFoundContent:l.length<2?null:e.jsx(xe,{image:xe.PRESENTED_IMAGE_SIMPLE,description:a||"Ничего не найдено"}),children:e.jsx(U,{placeholder:t,prefix:e.jsx(Ct,{style:{color:g.greyF[500]}}),allowClear:!0})})}function Ss(t){return[{title:"Предмет",dataIndex:"subject_name",key:"name",render:(n,s)=>e.jsxs("div",{children:[e.jsx("div",{style:{fontWeight:500},children:n}),e.jsx("div",{style:{fontSize:12,color:g.greyF[700]},children:s.category_name})]})},{title:"Продавцы",key:"sellers",align:"right",render:(n,s)=>e.jsx(Ke,{current:s.sellers,prev:s.sellers_prev})},{title:"Карточки",key:"cards",align:"right",render:(n,s)=>e.jsx(Ke,{current:s.cards,prev:s.cards_prev})},{title:"Заказы",key:"orders",align:"right",render:(n,s)=>e.jsx(Ke,{current:s.orders,prev:s.orders_prev})},{title:"",key:"actions",width:40,render:(n,s)=>e.jsx(L,{type:"text",size:"small",icon:e.jsx(wt,{style:{fontSize:10,color:g.greyF[500]}}),onClick:r=>{r.stopPropagation(),t(s.key)}})}]}function Cs(t){return[{title:"Запрос",dataIndex:"text",key:"text",render:n=>e.jsx("span",{style:{fontWeight:500},children:n})},{title:"Вчера",key:"day",align:"right",render:(n,s)=>e.jsx(Ke,{current:s.day,prev:s.day_prev})},{title:"Неделя",key:"week",align:"right",render:(n,s)=>e.jsx(Ke,{current:s.week,prev:s.week_prev})},{title:"",key:"actions",width:40,render:(n,s)=>e.jsx(L,{type:"text",size:"small",icon:e.jsx(wt,{style:{fontSize:10,color:g.greyF[500]}}),onClick:r=>{r.stopPropagation(),t(s.record_id)}})}]}function ws(){const{showRequestError:t}=W(),[n,s]=i.useState(!0),[r,a]=i.useState(!1),[l,d]=i.useState([]),[u,c]=i.useState([]),[p,h]=i.useState([]),[o,f]=i.useState([]),y=i.useRef(null),j=i.useRef(null),[m,v]=i.useState([]),[R,b]=i.useState([]);i.useEffect(()=>{const x=sessionStorage.getItem("wb_key");x&&(sessionStorage.removeItem("wb_key"),B("user/key-check",{key:x}))},[]),i.useEffect(()=>{S()},[]);const w=i.useCallback(x=>{if(x.length<2){v([]);return}ie("wbstat/subjects/search/",{params:{query:x}}).then(_=>{v(_.data||[])})},[]),C=i.useCallback(x=>{if(x.length<2){b([]);return}ie("wbstat/phrases/search/",{params:{query:x}}).then(_=>{b(_.data||[])})},[]);async function S(){var x,_;s(!0);try{const[k,$]=await Promise.all([ie("wbstat/dashboard/phrase-groups/"),ie("wbstat/dashboard/subject-groups/")]),z=(k.data||[]).find(Ge=>Ge.name===tt),P=($.data||[]).find(Ge=>Ge.name===tt);y.current=z||null,j.current=P||null;const[Z,ge]=await Promise.all([z?ie(`wbstat/dashboard/phrase-groups/${z.id}/phrases/`):Promise.resolve({data:{phrases:[]}}),P?ie(`wbstat/dashboard/subject-groups/${P.id}/subjects/`):Promise.resolve({data:{subjects:[]}})]),Re=((x=Z.data)==null?void 0:x.phrases)||[],ze=((_=ge.data)==null?void 0:_.subjects)||[];c(Re),d(ze),await F(ze,Re)}catch(k){t(k)}finally{s(!1)}}async function F(x=l,_=u){var z,P;const k=x.map(Z=>Z.subject_id),$=_.map(Z=>Z.text);if(k.length===0&&$.length===0){h([]),f([]);return}a(!0);try{const Z=await ue("wbstat/dashboard/tables/",{subject_ids:k,queries:$});h(((z=Z.data)==null?void 0:z.subjects)||[]),f(((P=Z.data)==null?void 0:P.queries)||[])}catch(Z){t(Z)}finally{a(!1)}}async function D(){if(y.current)return y.current;const x=await ue("wbstat/dashboard/phrase-groups/",{name:tt,description:"Dashboard panel"});return y.current=x.data,x.data}async function H(){if(j.current)return j.current;const x=await ue("wbstat/dashboard/subject-groups/",{name:tt,description:"Dashboard panel"});return j.current=x.data,x.data}async function V(x){var k;const _=Number(x);if(!(!_||l.some($=>$.subject_id===_)))try{const $=await H(),P=((k=(await ue(`wbstat/dashboard/subject-groups/${$.id}/add/`,{subjects:[_]})).data)==null?void 0:k.subjects)||[];d(P),await F(P,u)}catch($){t($)}}async function A(x){var k;const _=l.find($=>$.subject_id===x);if(_)try{const $=j.current,P=((k=(await ue(`wbstat/dashboard/subject-groups/${$.id}/remove/`,{ids:[_.id]})).data)==null?void 0:k.subjects)||[];d(P),await F(P,u)}catch($){t($)}}async function I(x){var _;if(!(!x||u.some(k=>k.text===x)))try{const k=await D(),z=((_=(await ue(`wbstat/dashboard/phrase-groups/${k.id}/add/`,{phrases:[x]})).data)==null?void 0:_.phrases)||[];c(z),await F(l,z)}catch(k){t(k)}}async function O(x){var _;try{const k=y.current,z=((_=(await ue(`wbstat/dashboard/phrase-groups/${k.id}/remove/`,{ids:[x]})).data)==null?void 0:_.phrases)||[];c(z),await F(l,z)}catch(k){t(k)}}const Y=new Set(l.map(x=>x.subject_id)),ye=m.filter(x=>!Y.has(x.id)).map(x=>{var _;return{value:String(x.id),label:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("span",{children:x.name}),e.jsx(T.Text,{type:"secondary",style:{fontSize:12},children:(_=x.category)==null?void 0:_.name})]})}}),te=new Set(u.map(x=>x.text)),he=R.filter(x=>!te.has(x.text)).map(x=>{var _;return{value:x.text,label:e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("span",{children:x.text}),e.jsxs(T.Text,{type:"secondary",style:{fontSize:12},children:[x.subject&&e.jsxs(e.Fragment,{children:[x.subject," · "]}),(_=x.count)==null?void 0:_.toLocaleString("ru-RU")]})]})}}),M=p.map(x=>({key:x.subject_id,subject_name:x.subject_name,category_name:x.category_name,sellers:x.suppliers_with_sells,sellers_prev:x.suppliers_with_sells_prev,cards:x.cards_with_orders_count,cards_prev:x.cards_with_orders_count_prev,orders:x.orders_qty,orders_prev:x.orders_qty_prev})),K=o.map(x=>{const _=u.find(k=>k.text===x.text);return{key:x.text,record_id:_==null?void 0:_.id,text:x.text,day:x.yesterday_count,day_prev:x.yesterday_prev_count,week:x.week_count,week_prev:x.week_prev_count}}),E=Ss(A),ne=Cs(O);return n?e.jsx("div",{style:{display:"flex",justifyContent:"center",paddingTop:100},children:e.jsx(Be,{indicator:e.jsx(Zn,{style:{fontSize:32},spin:!0})})}):e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:32,maxWidth:720},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:12},children:[e.jsx(T.Title,{level:4,style:{margin:0},children:"Предметы"}),e.jsx(J,{to:"/external-analytics/niche-analysis",style:{textDecoration:"none",color:g.primary[500],fontWeight:600,fontSize:13},children:"Смотреть все"})]}),e.jsx($t,{placeholder:"Найти предмет...",onSearch:w,options:ye,onSelect:V,notFoundText:"Предмет не найден"}),l.length>0?e.jsx(Te,{dataSource:M,columns:E,pagination:!1,size:"small",bordered:!1,loading:r,locale:{emptyText:e.jsx(xe,{description:"Нет данных",image:xe.PRESENTED_IMAGE_SIMPLE})}}):e.jsx(T.Text,{type:"secondary",style:{padding:"8px 0"},children:"Добавьте предметы для отслеживания"})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:12},children:[e.jsx(T.Title,{level:4,style:{margin:0},children:"Запросы"}),e.jsx(J,{to:"/search-queries",style:{textDecoration:"none",color:g.primary[500],fontWeight:600,fontSize:13},children:"Смотреть все"})]}),e.jsx($t,{placeholder:"Найти запрос...",onSearch:C,options:he,onSelect:I,notFoundText:"Запрос не найден"}),u.length>0?e.jsx(Te,{dataSource:K,columns:ne,pagination:!1,size:"small",bordered:!1,loading:r,locale:{emptyText:e.jsx(xe,{description:"Нет данных",image:xe.PRESENTED_IMAGE_SIMPLE})}}):e.jsx(T.Text,{type:"secondary",style:{padding:"8px 0"},children:"Добавьте запросы для отслеживания"})]})]})}const et=[{id:6,name:"Поиск"},{id:5,name:"Карточки"}],ks=[{id:0,name:"Все"},{id:1,name:"Активные"},{id:2,name:"Остановлены"},{id:3,name:"Неактивные"},{id:4,name:"Без биддера"}],yn=[{id:7,name:"Завершена"},{id:9,name:"Активна"},{id:11,name:"Приостановлена"}],Rs=[{id:0,name:"Все"},...yn],Ts=t=>{const n=yn.find(s=>s.id===t);return n?n.name:""},Fs=[{title:"Кампания",dataIndex:"id",key:"id"},{title:"Параметры",key:"name",render:(t,n)=>{var s,r;return n.name||((s=n.bidder)==null?void 0:s.query)||((r=n.bidder)==null?void 0:r.name)}},{title:"Статус",key:"status",render:(t,n)=>Ts(n.status)},{title:"Текущая ставка",key:"bet",align:"right",render:(t,n)=>{var s;return(s=n.bidder)==null?void 0:s.bet}},{title:"Позиция",key:"place",align:"right",render:(t,n)=>{var s;return(s=n.bidder)==null?void 0:s.place}},{title:"Биддер",key:"active",render:(t,n)=>{var s;return e.jsx(lt,{checked:((s=n.bidder)==null?void 0:s.active)||!1})}},{title:"Макс ставка",key:"maxbet",align:"right",render:(t,n)=>{var s;return(s=n.bidder)==null?void 0:s.maxbet}},{title:"Макс позиция",key:"top_place",align:"right",render:(t,n)=>{var s;return(s=n.bidder)==null?void 0:s.top_place}},{title:"Мин позиция",key:"low_place",align:"right",render:(t,n)=>{var s;return(s=n.bidder)==null?void 0:s.low_place}}];function Is({rows:t}){const n=Xe();return e.jsx(Te,{columns:Fs,dataSource:t||[],rowKey:(s,r)=>r,size:"small",pagination:!1,scroll:{x:900},onRow:s=>({onClick:()=>{const r=s.bidder?`/campaigns/${s.bidder.id}/bidder`:`/campaigns/${s.id}`;n(r)},style:{cursor:"pointer"}})})}function Ds({options:t,value:n,onChange:s}){function r(l){return t.findIndex(d=>d.id===l)}const a=t.map((l,d)=>({key:String(d),label:l.name}));return e.jsxs("div",{children:[e.jsx("h4",{children:"Типы кампаний"}),e.jsx(Tt,{tabPosition:"left",activeKey:String(r(n)),onChange:l=>{s&&s(t[parseInt(l)].id)},items:a})]})}function Es({options:t,value:n,onChange:s}){const r=t.map((a,l)=>({key:String(l),label:a.name}));return e.jsxs("div",{children:[e.jsx("h4",{children:"Магазины"}),e.jsx(Tt,{tabPosition:"left",activeKey:String(n),onChange:a=>{s&&s(parseInt(a))},items:r})]})}function je({count:t=4}){return e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[...Array(t)].map((n,s)=>e.jsx(G.Input,{active:!0,block:!0,style:{height:32,width:"100%"}},s))})}function Ls({status:t,bidder:n,onChange:s}){return e.jsxs("div",{style:{display:"flex",gap:8,marginBottom:8},children:[e.jsx(ae,{style:{flex:1},size:"small",value:t||0,onChange:r=>s&&s("status",r),options:Rs.map(r=>({value:r.id,label:r.name})),placeholder:"Статус"}),e.jsx(ae,{style:{flex:1},size:"small",value:n||0,onChange:r=>s&&s("bidder",r),options:ks.map(r=>({value:r.id,label:r.name})),placeholder:"Биддер"})]})}const $s=`${dt}/supplier/`,Ms=(t,n,s)=>{const r=new URLSearchParams({...s,advert_type:t,supplier_id:n});return`${Dt}/?${r.toString()}`};function zs(){const[t,n]=Ft(),[s,r]=i.useState(!0),[a,l]=i.useState([]),[d,u]=i.useState([]),[c,p]=i.useState(void 0),h=parseInt(t.get("type")||6),o=parseInt(t.get("supplier")||0),f=parseInt(t.get("status")||0),y=parseInt(t.get("bidder")||0),j=(m,v)=>{const R=new URLSearchParams(t);R.set(m,v),n(R)};return i.useEffect(()=>(a.length===0&&(r(!0),oe.get($s).then(m=>{l(m.data)}).finally(()=>r(!1))),()=>{}),[]),i.useEffect(()=>{var m;if(a.length>0){const v=Ms(h,(m=a[o])==null?void 0:m.id,{status:f,bidder:y});r(!0),oe.get(v).then(R=>{u(R.data)}).finally(()=>r(!1))}},[a,t]),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(T.Title,{level:4,style:{margin:0},children:"Кампании"}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"240px 1fr",gap:"16px"},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsx(Ds,{options:et,value:h,onChange:m=>j("type",m)}),e.jsx(Es,{options:a,value:o,onChange:m=>j("supplier",m)})]}),e.jsxs("div",{style:{flexGrow:1},children:[e.jsx(Ls,{status:f,bidder:y,onChange:(m,v)=>j(m,v)}),s?e.jsx(je,{count:5}):e.jsx(Is,{rows:d})]})]})]})}const Ps="ooo_mkeeper_web",qe=new Yn({clientId:Ps,redirectUri:`${window.location.protocol}//${window.location.host}/wb-id-sdk/callback`,scope:"openid phone"}),jn="data:image/svg+xml,%3csvg%20width='128'%20height='128'%20viewBox='0%200%20128%20128'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='128'%20height='128'%20rx='64'%20fill='url(%23paint0_linear_0_1)'/%3e%3cpath%20d='M21.8564%2045.3936H27.9404V50.5889C29.3988%2048.7887%2030.7204%2047.4785%2031.9053%2046.6582C33.9333%2045.2682%2036.2347%2044.5732%2038.8096%2044.5732C41.7262%2044.5732%2044.0732%2045.291%2045.8506%2046.7266C46.8532%2047.5469%2047.7646%2048.7546%2048.585%2050.3496C49.9521%2048.39%2051.5586%2046.943%2053.4043%2046.0088C55.25%2045.0518%2057.3236%2044.5732%2059.625%2044.5732C64.5469%2044.5732%2067.8965%2046.3506%2069.6738%2049.9053C70.6309%2051.8193%2071.1094%2054.3942%2071.1094%2057.6299V82H64.7178V56.5703C64.7178%2054.1322%2064.1025%2052.4574%2062.8721%2051.5459C61.6644%2050.6344%2060.1833%2050.1787%2058.4287%2050.1787C56.0133%2050.1787%2053.9284%2050.9876%2052.1738%2052.6055C50.4421%2054.2233%2049.5762%2056.9235%2049.5762%2060.7061V82H43.3213V58.1084C43.3213%2055.6247%2043.0251%2053.8132%2042.4326%2052.6738C41.4984%2050.9648%2039.7552%2050.1104%2037.2031%2050.1104C34.8789%2050.1104%2032.7598%2051.0104%2030.8457%2052.8105C28.9544%2054.6107%2028.0088%2057.8691%2028.0088%2062.5859V82H21.8564V45.3936ZM80.0303%2031.79H85.9434V60.9453L101.734%2045.3936H109.596L95.582%2059.0996L110.382%2082H102.521L91.1045%2063.543L85.9434%2068.2598V82H80.0303V31.79Z'%20fill='black'/%3e%3cdefs%3e%3clinearGradient%20id='paint0_linear_0_1'%20x1='64'%20y1='32'%20x2='64'%20y2='82'%20gradientUnits='userSpaceOnUse'%3e%3cstop%20stop-color='%23F27420'/%3e%3cstop%20offset='1'%20stop-color='%23F9AB0D'/%3e%3c/linearGradient%3e%3c/defs%3e%3c/svg%3e",As="auth_redirect",pt=()=>{const[t,n]=i.useState(!1),s=tn(),r=()=>{var l;const a=(l=s.state)==null?void 0:l.from;a&&a!=="/auth/login"&&localStorage.setItem(As,a),qe.login()};return e.jsx("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"calc(100vh - 200px)"},children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:32},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[e.jsx("img",{src:jn,style:{width:48,height:48,borderRadius:24},alt:"mkeeper"}),e.jsx("span",{style:{fontSize:28,fontFamily:"Tahoma, Verdana, Segoe, sans-serif",color:g.dark[500]},children:"mkeeper"})]}),e.jsxs("button",{type:"button",onClick:()=>{n(!0),r()},disabled:t,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,width:320,height:52,padding:"0 24px",background:"#F6F6F9",border:"none",borderRadius:20,cursor:"pointer",fontSize:16,color:"#242429",transition:"background-color 0.2s"},onMouseEnter:a=>a.currentTarget.style.backgroundColor="#EDEDF0",onMouseLeave:a=>a.currentTarget.style.backgroundColor="#F6F6F9",children:[e.jsx("span",{children:"Войти с"}),e.jsxs("svg",{width:"40",height:"20",viewBox:"0 0 40 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[e.jsx("path",{d:"M9.585 20C7.007 20 5.451 20 3.917 19.214C2.558 18.518 1.474 17.428 0.782 16.062C0 14.519 0 12.954 0 10.362V9.638C0 7.046 0 5.481 0.782 3.938C1.474 2.572 2.558 1.482 3.917 0.786C5.451 0 7.007 0 9.585 0H30.415C32.993 0 34.549 0 36.083 0.786C37.442 1.482 38.526 2.572 39.218 3.938C40 5.481 40 7.046 40 9.638V10.362C40 12.954 40 14.519 39.218 16.062C38.526 17.428 37.442 18.518 36.083 19.214C34.549 20 32.993 20 30.415 20H9.585Z",fill:"#242429"}),e.jsx("path",{d:"M17.271 6.879C16.552 6.879 15.902 7.098 15.348 7.472V4.052H13.815V10.36C13.815 12.279 15.365 13.824 17.261 13.824C19.158 13.824 20.725 12.289 20.725 10.342C20.725 8.396 19.192 6.879 17.27 6.879ZM10.313 10.806L8.91 7.124H7.836L6.425 10.806L5.014 7.124H3.341L5.81 13.598H6.883L8.364 9.742L9.854 13.598H10.927L13.387 7.124H11.724L10.313 10.806ZM17.262 12.28C16.223 12.28 15.348 11.443 15.348 10.352C15.348 9.261 16.171 8.433 17.271 8.433C18.37 8.433 19.193 9.296 19.193 10.352C19.193 11.407 18.318 12.28 17.262 12.28Z",fill:"#F6F6F9"}),e.jsx("path",{d:"M31.068 7.76H30.071V12.242H31.068C32.242 12.242 33.247 11.346 33.247 10.012C33.247 8.649 32.242 7.76 31.068 7.76Z",fill:"#F6F6F9"}),e.jsx("path",{d:"M36.408 5.378C36.023 4.618 35.408 3.999 34.652 3.612C33.792 3.171 32.666 3.171 30.415 3.171H29.648C27.397 3.171 26.272 3.171 25.412 3.612C24.656 3.999 24.041 4.618 23.656 5.378C23.218 6.242 23.218 7.374 23.218 9.637V10.362C23.218 12.625 23.218 13.757 23.656 14.621C24.041 15.382 24.656 16 25.412 16.387C26.272 16.828 27.397 16.828 29.648 16.828H30.415C32.666 16.828 33.792 16.828 34.652 16.387C35.408 16 36.023 15.382 36.408 14.621C36.846 13.757 36.846 12.625 36.846 10.362V9.637C36.846 7.374 36.846 6.242 36.408 5.378ZM27.425 13.713H25.892V6.286H27.425V13.713ZM31.046 13.713H28.54V6.286H31.046C33.308 6.286 34.781 7.917 34.781 10.01C34.781 12.082 33.308 13.713 31.046 13.713Z",fill:"#F6F6F9"})]})]})]})})},vt={},vn=i.createContext(vt);function Ws({children:t}){const[n,s]=i.useState(vt),r=i.useRef(null),a=i.useRef(0),l=i.useRef(new Map),d=i.useCallback(()=>{const o=++a.current;return N("user/profile").then(f=>{o===a.current&&s({...f.data})})},[]),u=()=>{s({...vt,auth:!1})},c=i.useCallback((o,f)=>{l.current.set(o,f)},[]),p=i.useCallback(o=>{l.current.delete(o)},[]);i.useEffect(()=>{d()},[]),i.useEffect(()=>{if(!n.auth)return;const o=new Qn([{transport:"websocket",endpoint:"/api/centrifugo/connection/websocket"}],{getToken:()=>N("user/centrifugo-token").then(f=>f.data.token)});return o.on("publication",f=>{var y;((y=f.data)==null?void 0:y.op)==="getProfile"&&d(),l.current.forEach(j=>j(f))}),o.connect(),r.current=o,()=>{o.disconnect(),r.current=null}},[n.auth,d]);const h={profile:n,getProfile:d,clearProfile:u,addPublicationHandler:c,removePublicationHandler:p};return e.jsx(vn.Provider,{value:h,children:t})}const pe=()=>i.useContext(vn);function Hs(){const t=Xe(),{clearProfile:n,profile:s}=pe(),r=()=>{qe.logout().then(()=>{}).catch(l=>console.log("wb logout error:",l)),ue("user/logout").then(()=>{n(),t("/")}).catch(l=>{})};if(!s.auth)return e.jsx(J,{to:"/auth/login",style:{color:"inherit",textDecoration:"none"},children:e.jsx(L,{type:"text",children:"Войти"})});const a=[{key:"profile",label:e.jsx(J,{to:"/profile",style:{color:"inherit",textDecoration:"none"},children:"Профиль"})},{key:"logout",label:"Выйти",onClick:r}];return e.jsx(nn,{menu:{items:a},trigger:["click"],children:e.jsx(L,{type:"text",icon:e.jsx(nt,{}),style:{fontSize:"20px"}})})}const Ns=[{key:"niche-analysis",label:e.jsx(J,{to:"/external-analytics/niche-analysis",style:{color:"inherit",textDecoration:"none"},children:"Анализ ниш"})},{key:"category-analysis",label:e.jsx(J,{to:"/external-analytics/category-analysis",style:{color:"inherit",textDecoration:"none"},children:"Анализ категорий"})},{key:"category-matrix",label:e.jsx(J,{to:"/external-analytics/category-matrix",style:{color:"inherit",textDecoration:"none"},children:"Матрица категорий"})},{key:"subject-matrix",label:e.jsx(J,{to:"/external-analytics/subject-matrix",style:{color:"inherit",textDecoration:"none"},children:"Матрица предметов"})},{key:"search-queries",label:e.jsx(J,{to:"/search-queries",style:{color:"inherit",textDecoration:"none"},children:"Запросы"})}];function Os(){const{profile:t}=pe(),n=t.auth===!0;return e.jsxs("header",{style:{position:"fixed",top:0,left:0,right:0,zIndex:1001,background:"#fff",boxShadow:"0 2px 8px rgba(0,0,0,0.06)",height:"56px",display:"flex",alignItems:"center",padding:"0 24px",justifyContent:"space-between",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e.jsxs(J,{to:"/",style:{display:"flex",alignItems:"center",fontWeight:700,textDecoration:"none",fontSize:"18px",color:g.dark[500],marginRight:"16px"},children:[e.jsx("span",{style:{marginRight:"8px",height:"32px"},children:e.jsx("img",{src:jn,style:{width:"32px",height:"32px",borderRadius:"16px"}})}),e.jsx("span",{style:{color:g.dark[500],fontWeight:400,fontFamily:"Tahoma, Verdana, Segoe, sans-serif",lineHeight:1},children:"mkeeper"})]}),n&&e.jsx(nn,{menu:{items:Ns},trigger:["hover"],children:e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"6px 12px",borderRadius:"8px",cursor:"pointer",fontSize:"14px",fontWeight:500,color:g.dark[500],background:"#f5f5f5"},children:["Внешняя аналитика",e.jsx("span",{style:{fontSize:"10px",fontWeight:400,lineHeight:1,padding:"2px 5px",borderRadius:"4px",background:g.primary[500],color:g.dark[500],letterSpacing:"0.02em"},children:"BETA"}),e.jsx(Xn,{style:{fontSize:"10px"}})]})})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[n&&e.jsx(J,{to:"/helpdesk",children:e.jsx(L,{type:"text",icon:e.jsx(Jn,{}),style:{fontSize:"20px"}})}),n&&e.jsx(J,{to:"/wishes",children:e.jsx(L,{type:"text",icon:e.jsx(es,{}),style:{fontSize:"20px"}})}),e.jsx(Hs,{})]})]})}function Mt(){return e.jsx("div",{children:e.jsx(Os,{})})}const qs="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='utf-8'?%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20style='margin:%20auto;%20background:%20none;%20display:%20block;%20shape-rendering:%20auto;'%20width='200px'%20height='200px'%20viewBox='0%200%20100%20100'%20preserveAspectRatio='xMidYMid'%3e%3cg%20transform='translate(80,50)'%3e%3cg%20transform='rotate(0)'%3e%3ccircle%20cx='0'%20cy='0'%20r='6'%20fill='%23d8ebf9'%20fill-opacity='1'%3e%3canimateTransform%20attributeName='transform'%20type='scale'%20begin='-0.875s'%20values='1.5%201.5;1%201'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%3e%3c/animateTransform%3e%3canimate%20attributeName='fill-opacity'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%20values='1;0'%20begin='-0.875s'%3e%3c/animate%3e%3c/circle%3e%3c/g%3e%3c/g%3e%3cg%20transform='translate(71.21320343559643,71.21320343559643)'%3e%3cg%20transform='rotate(45)'%3e%3ccircle%20cx='0'%20cy='0'%20r='6'%20fill='%23d8ebf9'%20fill-opacity='0.875'%3e%3canimateTransform%20attributeName='transform'%20type='scale'%20begin='-0.75s'%20values='1.5%201.5;1%201'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%3e%3c/animateTransform%3e%3canimate%20attributeName='fill-opacity'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%20values='1;0'%20begin='-0.75s'%3e%3c/animate%3e%3c/circle%3e%3c/g%3e%3c/g%3e%3cg%20transform='translate(50,80)'%3e%3cg%20transform='rotate(90)'%3e%3ccircle%20cx='0'%20cy='0'%20r='6'%20fill='%23d8ebf9'%20fill-opacity='0.75'%3e%3canimateTransform%20attributeName='transform'%20type='scale'%20begin='-0.625s'%20values='1.5%201.5;1%201'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%3e%3c/animateTransform%3e%3canimate%20attributeName='fill-opacity'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%20values='1;0'%20begin='-0.625s'%3e%3c/animate%3e%3c/circle%3e%3c/g%3e%3c/g%3e%3cg%20transform='translate(28.786796564403577,71.21320343559643)'%3e%3cg%20transform='rotate(135)'%3e%3ccircle%20cx='0'%20cy='0'%20r='6'%20fill='%23d8ebf9'%20fill-opacity='0.625'%3e%3canimateTransform%20attributeName='transform'%20type='scale'%20begin='-0.5s'%20values='1.5%201.5;1%201'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%3e%3c/animateTransform%3e%3canimate%20attributeName='fill-opacity'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%20values='1;0'%20begin='-0.5s'%3e%3c/animate%3e%3c/circle%3e%3c/g%3e%3c/g%3e%3cg%20transform='translate(20,50.00000000000001)'%3e%3cg%20transform='rotate(180)'%3e%3ccircle%20cx='0'%20cy='0'%20r='6'%20fill='%23d8ebf9'%20fill-opacity='0.5'%3e%3canimateTransform%20attributeName='transform'%20type='scale'%20begin='-0.375s'%20values='1.5%201.5;1%201'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%3e%3c/animateTransform%3e%3canimate%20attributeName='fill-opacity'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%20values='1;0'%20begin='-0.375s'%3e%3c/animate%3e%3c/circle%3e%3c/g%3e%3c/g%3e%3cg%20transform='translate(28.78679656440357,28.786796564403577)'%3e%3cg%20transform='rotate(225)'%3e%3ccircle%20cx='0'%20cy='0'%20r='6'%20fill='%23d8ebf9'%20fill-opacity='0.375'%3e%3canimateTransform%20attributeName='transform'%20type='scale'%20begin='-0.25s'%20values='1.5%201.5;1%201'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%3e%3c/animateTransform%3e%3canimate%20attributeName='fill-opacity'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%20values='1;0'%20begin='-0.25s'%3e%3c/animate%3e%3c/circle%3e%3c/g%3e%3c/g%3e%3cg%20transform='translate(49.99999999999999,20)'%3e%3cg%20transform='rotate(270)'%3e%3ccircle%20cx='0'%20cy='0'%20r='6'%20fill='%23d8ebf9'%20fill-opacity='0.25'%3e%3canimateTransform%20attributeName='transform'%20type='scale'%20begin='-0.125s'%20values='1.5%201.5;1%201'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%3e%3c/animateTransform%3e%3canimate%20attributeName='fill-opacity'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%20values='1;0'%20begin='-0.125s'%3e%3c/animate%3e%3c/circle%3e%3c/g%3e%3c/g%3e%3cg%20transform='translate(71.21320343559643,28.78679656440357)'%3e%3cg%20transform='rotate(315)'%3e%3ccircle%20cx='0'%20cy='0'%20r='6'%20fill='%23d8ebf9'%20fill-opacity='0.125'%3e%3canimateTransform%20attributeName='transform'%20type='scale'%20begin='0s'%20values='1.5%201.5;1%201'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%3e%3c/animateTransform%3e%3canimate%20attributeName='fill-opacity'%20keyTimes='0;1'%20dur='1s'%20repeatCount='indefinite'%20values='1;0'%20begin='0s'%3e%3c/animate%3e%3c/circle%3e%3c/g%3e%3c/g%3e%3c!--%20[ldio]%20generated%20by%20https://loading.io/%20--%3e%3c/svg%3e";function Le(){const[t,n]=i.useState(0);return i.useEffect(()=>(n(1),()=>{n(0)}),[]),e.jsx("div",{className:"spinner-wrapper",children:e.jsx("img",{src:qs,className:"spinner-img",style:{opacity:t}})})}const zt="cookie_banner_dismissed";function Bs(){const[t,n]=i.useState(()=>!localStorage.getItem(zt));if(!t)return null;const s=()=>{localStorage.setItem(zt,"1"),n(!1)};return e.jsxs("div",{style:{position:"fixed",bottom:24,right:24,zIndex:2e3,background:"#fff",boxShadow:"0 4px 16px rgba(0,0,0,0.12)",borderRadius:12,padding:"14px 18px",maxWidth:320,display:"flex",flexDirection:"column",gap:10,fontSize:13,color:g.dark[500]},children:[e.jsx("span",{children:"Мы используем файлы куки для корректной работы сервиса и аналитики. Продолжая использовать сайт, вы соглашаетесь с их использованием."}),e.jsx("button",{onClick:s,style:{alignSelf:"flex-end",background:g.primary[500],border:"none",borderRadius:8,padding:"6px 16px",fontSize:13,fontWeight:600,color:"#fff",cursor:"pointer"},children:"Закрыть"})]})}const Gs=["/auth/login","/auth/logout","/auth/ext-auth","/wb-id-sdk/callback","/auth/wblogin"];function Us(){const{profile:t}=pe(),n=tn(),s=Gs.includes(n.pathname);return t.auth===void 0?e.jsxs("div",{style:{display:"flex"},children:[e.jsx(Mt,{}),e.jsxs("main",{style:{flexGrow:1,minWidth:0,overflowX:"hidden",padding:"0 24px 24px 24px"},children:[e.jsx("div",{style:{height:"72px"}}),e.jsx(Le,{})]})]}):t.auth===!1&&!s?e.jsx(ts,{to:"/auth/login",replace:!0,state:{from:n.pathname+n.search+n.hash}}):e.jsxs("div",{style:{display:"flex"},children:[e.jsx(Mt,{}),e.jsxs("main",{style:{flexGrow:1,minWidth:0,overflowX:"hidden",padding:"0 24px 24px 24px"},children:[e.jsx("div",{style:{height:"72px"}}),e.jsx(ns,{})]}),e.jsx(Bs,{})]})}const _n=({label:t,headers:n,rows:s})=>e.jsxs("div",{children:[t&&e.jsx(T.Title,{level:4,style:{padding:"16px"},children:t}),e.jsx(Te,{columns:n,dataSource:s||[],rowKey:(r,a)=>a,size:"small",pagination:!1,scroll:{x:900},locale:{emptyText:"Empty..."}})]}),Vs=()=>{let{subjectId:t}=ot();const[n,s]=i.useState(!0),[r,a]=i.useState([]),l="Запросы по категории",d=[{title:"ПОИСКОВЫЙ ЗАПРОС",key:"text",dataIndex:"text"},{title:"ПРИОРИТЕТ",key:"priority",dataIndex:"priority",align:"right"},{title:"ПОКАЗОВ В МЕСЯЦ",key:"requestCount",dataIndex:"requestCount",align:"right"}];return i.useEffect(()=>{s(!0),N("wbstat/priority-subjects",{params:{id:t}}).then(c=>{var p;a(((p=c.data)==null?void 0:p.results)||[])}).finally(()=>s(!1))},[]),n?e.jsx(Be,{}):e.jsx("div",{children:e.jsx(_n,{label:l,headers:d,rows:r})})},Ks=()=>e.jsxs("div",{style:{background:"#fff",borderRadius:4,padding:16,marginBottom:8,boxShadow:"0 1px 2px rgba(0,0,0,0.06)"},children:[e.jsxs(ce.Group,{style:{marginBottom:8},children:[e.jsx(ce,{value:"isByWord",children:"По словам"}),e.jsx(ce,{value:"isBySearch",children:"История запросов"}),e.jsx(ce,{value:"isByCategory",children:"По категории"})]}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx(U,{placeholder:"Поисковый запрос",size:"small",style:{flex:1}}),e.jsx(L,{type:"primary",style:{padding:"0 25px",fontSize:12,fontWeight:700},children:"Подобрать"})]})]}),Zs=()=>{const t=[{title:"СТАТИСТИКА ПО СЛОВАМ",align:"left"},{title:"ПОКАЗОВ В МЕСЯЦ",align:"left"}];return e.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.jsx(Ks,{}),e.jsx(_n,{headers:t})]})};function Ys({options:t,onChange:n,value:s}){return e.jsx(Oe,{dataSource:t||[],renderItem:(r,a)=>{var l;return e.jsx(Oe.Item,{onClick:()=>{n(r)},style:{cursor:"pointer",background:(r==null?void 0:r.id)===(s==null?void 0:s.id)?"#FFFBF3":"transparent",padding:"8px 16px"},children:e.jsx(Oe.Item.Meta,{title:r.name,description:(l=r.category)==null?void 0:l.name})},a)}})}function de(t){return t.toLocaleString()}const Qs=[{title:"Фраза",dataIndex:"text",key:"text"},{title:"Приоритет",dataIndex:"priority",key:"priority"},{title:"Запросов за неделю",key:"weekRequestCount",render:(t,n)=>de(n.weekRequestCount)},{title:"Запросов за месяц",key:"monthRequestCount",render:(t,n)=>de(n.monthRequestCount)},{title:"Запросов за 3 месяца",key:"quarterRequestCount",render:(t,n)=>de(n.quarterRequestCount)}];function bn({rows:t}){return t!=null&&t.length?e.jsx(Te,{columns:Qs,dataSource:t||[],rowKey:(n,s)=>s,size:"small",pagination:!1,scroll:{x:900}}):null}function Xs(){const[t,n]=i.useState(!1),[s,r]=i.useState([]),[a,l]=i.useState(""),[d,u]=i.useState([]),[c,p]=i.useState([]),[h,o]=i.useState(void 0),[f,y]=St("",300);i.useEffect(()=>{h&&(n(!0),N(`wbstat/subjects/phrases/${h.id}`).then(v=>{var R,b;u(((R=v.data)==null?void 0:R.results)||[]),p(((b=v.data)==null?void 0:b.count)||0)}).finally(()=>n(!1)))},[h]),i.useEffect(()=>{if(a.length<3){r([]);return}N("wbstat/subjects/search",{params:{query:a}}).then(R=>{var b;r(((b=R.data)==null?void 0:b.results)||[])}).finally(()=>n(!1))},[f]);const j=v=>{l(v),y(v)},m=()=>{window.location.href=`/api/wbstat/subjects/phrases/${h.id}/xlsx/${h.name}.xlsx`};return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(T.Title,{level:4,style:{margin:0},children:"Фразы по категориям"}),e.jsx("div",{children:e.jsx(U,{onChange:v=>{j(v.target.value)},value:a,placeholder:"Введите текст для поиска категории",size:"large"})}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"240px 1fr",gap:"20px"},children:[e.jsx("div",{children:e.jsx(Ys,{options:s,onChange:o,value:h})}),e.jsxs("div",{style:{flexGrow:1},children:[t?e.jsx(je,{count:1}):e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:!!(d!=null&&d.length)&&e.jsxs(L,{onClick:m,icon:e.jsx(ct,{}),children:["Скачать ",c," фраз в xlsx"]})}),t?e.jsx(je,{count:5}):e.jsx(bn,{rows:d})]})]})]})}function Js(){const{subjectId:t}=ot(),[n,s]=i.useState(!1),[r,a]=i.useState([]),[l,d]=i.useState(0),[u,c]=i.useState(void 0);i.useEffect(()=>{N("wbstat/subjects/search",{params:{id:t}}).then(o=>{var f,y,j;c(((y=(f=o.data)==null?void 0:f.results)==null?void 0:y.length)>0?(j=o.data)==null?void 0:j.results[0]:void 0)}).finally(()=>s(!1))},[]),i.useEffect(()=>{u&&(s(!0),N(`wbstat/subjects/phrases/${t}`).then(h=>{var o,f;a(((o=h.data)==null?void 0:o.results)||[]),d(((f=h.data)==null?void 0:f.count)||0)}).finally(()=>s(!1)))},[u]);const p=()=>{window.location.href=`/api/wbstat/subjects/phrases/${t}/xlsx/${u.name}.xlsx`};return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsxs(T.Title,{level:4,style:{margin:0},children:["Приоритетные фразы по категории ",u==null?void 0:u.name]}),e.jsxs("div",{style:{flexGrow:1},children:[n?e.jsx(je,{count:1}):e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsxs(L,{onClick:p,icon:e.jsx(ct,{}),children:["Скачать ",l," фраз в xlsx"]})}),n?e.jsx(je,{count:5}):e.jsx(bn,{rows:r})]})]})}const er=t=>`/campaigns/${t}`,tr=t=>`/campaigns/${t}/bidder`;function nr({instance:t,campaignId:n}){var s,r,a;return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{style:{display:"flex",columnGap:8,alignItems:"center",justifyContent:"space-between"},children:["Актуальная ставка: 0",e.jsx("a",{href:er(n),children:e.jsx(L,{type:"link",children:"Изменить параметры"})})]}),e.jsx(T.Title,{level:5,style:{margin:0},children:"Параметры биддера"}),e.jsx(U,{id:"max-cpm",placeholder:"Максимальная ставка",value:((s=t.bidder)==null?void 0:s.maxbet)??"",size:"small"}),e.jsx(U,{id:"top-place",placeholder:"Верхняя позиция",value:((r=t.bidder)==null?void 0:r.top_place)??"",size:"small"}),e.jsx(U,{id:"low-place",placeholder:"Нижняя позиция",value:((a=t.bidder)==null?void 0:a.low_place)??"",size:"small"}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx(L,{type:"primary",children:"Сохранить изменения"}),e.jsx(L,{children:"Запустить биддер"})]})]})}const sr=[{title:"Позиция",dataIndex:"place",key:"place"},{title:"Бренд",key:"brand",render:(t,n)=>`${n.brand} (${n.advert_id})`},{title:"Ставка",dataIndex:"cpm",key:"cpm",align:"right"}];function Sn({data:t,place:n,campaignId:s}){const r=t==null?void 0:t.filter(a=>!n&&a.place<=20||a.place<4||a.place>t.length-3||0<=n-a.place&&n-a.place<10||0<=a.place-n&&a.place-n<5);return e.jsx(Te,{columns:sr,dataSource:r||[],rowKey:"place",size:"small",pagination:!1,rowClassName:a=>a.advert_id===s?"ant-table-row-bold":""})}function rr({instance:t}){const n=t.updated_at?new Date(t.updated_at):void 0,s=[{label:"Статус",value:t.active?"Активна":"Не активна"},{label:"Актуальная ставка",value:t.bet},{label:"Ожидаемое место",value:t.place},{label:"Обновлено",value:n==null?void 0:n.toLocaleString()}];return e.jsxs("div",{children:[e.jsx(T.Title,{level:5,style:{margin:0},children:"Состояние"}),e.jsx(Oe,{dataSource:s,renderItem:r=>e.jsx(Oe.Item,{children:e.jsx(Oe.Item.Meta,{title:r.value,description:r.label})})})]})}const ir=(t,n)=>(et.find(s=>s.id===t),`${Dt}/${n}`),ar=t=>`${dt}/auction/${t}/`;function lr(){var p,h;const{campaignId:t}=ot(),[n,s]=i.useState(!0),[r,a]=i.useState([]),[l,d]=i.useState([]),[u,c]=i.useState(void 0);return i.useEffect(()=>{s(!0),oe.get(ir(6,t)).then(o=>{a(o.data)}).finally(()=>s(!1)),oe.get(ar(t)).then(o=>{var f,y;(y=(f=o.data)==null?void 0:f.data)==null||y.forEach((j,m)=>{j.place=m+1}),d(o.data)})},[t]),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsx(sn,{items:[{title:e.jsx("a",{href:"/campaigns",children:"Мои кампании"})},{title:t}]}),e.jsxs(T.Title,{level:5,style:{margin:0},children:[(p=et.find(o=>o.id===r.advert_type))==null?void 0:p.name,": ",r.name]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"20px"},children:[e.jsx(nr,{instance:r,campaignId:t}),e.jsx("div",{children:e.jsx(rr,{instance:r.bidder||{}})}),e.jsx("div",{children:e.jsx(Sn,{...l,campaignId:t,place:(h=r.bidder)==null?void 0:h.place})})]})]})}function or({supplierId:t}){const[n,s]=i.useState(!1),r=()=>{s(!0)},a=()=>{s(!1)},l=()=>"Ключ API";return e.jsxs(e.Fragment,{children:[e.jsx(L,{onClick:r,type:"link",children:"Добавить"}),e.jsxs(Fe,{open:n,onCancel:a,title:`Добавить ${l()} API`,onOk:a,okText:"Сохранить",cancelText:"Отмена",children:[e.jsx("p",{children:"Добавьте ключ API в кабинете поставщика и вставьте его сюда"}),e.jsx(U,{autoFocus:!0,id:"api_key",placeholder:l()})]})]})}function cr({item:t}){return e.jsxs("div",{style:{border:"solid thin #ccc",borderRadius:"8px",padding:4},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between"},children:[e.jsx(T.Title,{level:5,style:{margin:0},children:t.name}),e.jsx(L,{type:"text",children:"Удалить"})]}),e.jsxs("div",{children:["Ключ API: ",t!=null&&t.api_key?"Есть":e.jsx(or,{supplierId:t.id,keyType:"uni"})]})]})}function dr(){const[t,n]=i.useState(!1),s=()=>{n(!0)},r=()=>{n(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(L,{onClick:s,type:"primary",children:"Добавить поставщика"}),e.jsxs(Fe,{open:t,onCancel:r,title:"Добавить поставщика",onOk:r,okText:"Сохранить",cancelText:"Отмена",children:[e.jsx("p",{children:"Добавьте ключ API в кабинете поставщика и вставьте его сюда"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsx(U,{autoFocus:!0,id:"name",placeholder:"Наименование"}),e.jsx(U,{id:"api_key",placeholder:"Ключ API"})]})]})]})}const be=({children:t,...n})=>{const{variant:s,color:r,sx:a,size:l,type:d,disabled:u,onClick:c,component:p,href:h,target:o,...f}=n;let y="default",j=!1;s==="contained"?y="primary":s==="outlined"&&(y="default"),r==="error"&&(j=!0);const m={fontSize:"16px",lineHeight:"26px",fontWeight:500,padding:"8px 20px",height:"auto",...a||{}};return p==="a"||h?e.jsx("a",{href:h,target:o,style:{textDecoration:"none"},children:e.jsx(L,{type:y,danger:j,disabled:u,onClick:c,style:m,htmlType:d,children:t})}):e.jsx(L,{type:y,danger:j,disabled:u,onClick:c,style:m,htmlType:d,children:t})},Cn=()=>e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",children:[e.jsx("rect",{width:"24",height:"24",rx:"12",fill:"#F7F8FA"}),e.jsx("path",{d:"M7 6.99988L17 16.9999",stroke:"#6E7788","stroke-width":"1.3","stroke-linecap":"square","stroke-linejoin":"round"}),e.jsx("path",{d:"M17 6.99988L7 16.9999",stroke:"#6E7788","stroke-width":"1.3","stroke-linecap":"square","stroke-linejoin":"round"})]}),ur=[{label:"1 месяц (30 дней)",value:1},{label:"3 месяца (90 дней)",value:3},{label:"6 месяцев (180 дней)",value:6},{label:"1 год (365 дней)",value:12}],pr=[{value:"russia",label:"Российская Федерация",icon:"🇷🇺"},{value:"foreign",label:"Иностранная карта",icon:"🌐"}];function hr({method:t,selected:n,onClick:s}){return e.jsxs("div",{onClick:s,style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:8,padding:"16px 12px",border:`1px solid ${n?g.primary[500]:g.greyS[200]}`,borderRadius:8,background:n?g.primary[50]:"#fff",cursor:"pointer",transition:"border-color 0.2s, background 0.2s"},children:[e.jsx("span",{style:{fontSize:32,lineHeight:1},children:t.icon}),e.jsx(T.Text,{style:{fontSize:13,textAlign:"center"},children:t.label})]})}function Ze({children:t,disabled:n,variant:s="contained",licenseKey:r}){const[a,l]=rn.useState(!1),[d,u]=i.useState([]),[c,p]=i.useState(!0),[h,o]=i.useState(!1),[f,y]=i.useState(null),[j,m]=i.useState(1),[v,R]=i.useState("russia"),[b,w]=i.useState(!1),[C,S]=i.useState(null),{showRequestError:F}=W(),D=()=>{p(!0),Promise.all([N("user/tariff"),N("user/tariff/current").catch(()=>null)]).then(([x,_])=>{const k=x.data??[],$=_==null?void 0:_.data,z=$?[$,...k.filter(P=>P.id!==$.id)]:k;z.length&&(u(z),y(z[0].id))}).catch(x=>{F(x)}).finally(()=>p(!1))};i.useEffect(()=>{a&&D()},[a]);const H=()=>{o(!0);const x=v!=="foreign"&&b?"cloudpayments2":"cloudpayments";ue("billing/get_payment_link",{tariff:f,months:j,payment_method:v,source:"site",subscription:v==="russia"?b:!1,...x?{agent:x}:{},...r?{key:r}:{},...(I==null?void 0:I.devices)>0?{devices:C}:{}}).then(_=>{_.data.url?(window.open(_.data.url,"_blank").focus(),A()):F("Ошибка при создании платежа")}).catch(_=>{F(`Ошибка при создании платежа: ${ut(_)}`)}).finally(()=>o(!1))},V=()=>l(!0),A=()=>l(!1),I=d.find(x=>x.id===f);i.useEffect(()=>{(I==null?void 0:I.devices)>0?S(x=>x===null||x_===3?x.price3??0:_===6?x.price6??0:_===12?x.price12??0:x.price??0,Y=(x,_)=>_===3?x.device_price3??0:_===6?x.device_price6??0:_===12?x.device_price12??0:x.device_price??0,ye=(x,_,k=0)=>{if(!x||_===1)return null;const $=(x.price??0)+k*(x.device_price??0);if(!$)return null;const z=O(x,_)+k*Y(x,_),P=_*$,Z=Math.floor((1-z/P)*100);return Z>0?Z:null},te=(I==null?void 0:I.devices)>0&&C>I.devices?C-I.devices:0,he=I?Y(I,j):0,M=I?O(I,j):null,K=M!==null?M+te*he:null,E=ye(I,j,te),ne=ur.map(x=>{if(x.value===1||!I)return x;const _=ye(I,x.value);return _?{...x,label:`${x.label} — скидка ${_}%`}:x});return e.jsxs(e.Fragment,{children:[e.jsx(be,{disabled:n,variant:s,onClick:V,color:"primary",children:t}),e.jsx(Fe,{open:!!a,onCancel:A,title:"Покупка тарифа",footer:null,closeIcon:e.jsx(Cn,{}),width:500,children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16,paddingTop:8},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx(T.Text,{style:{color:g.greyF[700]},children:"Тариф:"}),e.jsx(ae,{style:{width:"100%"},loading:c,value:f,onChange:y,options:d.map(x=>({label:x.name,value:x.id}))})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx(T.Text,{style:{color:g.greyF[700]},children:"Срок оплаты:"}),e.jsx(ae,{style:{width:"100%"},value:j,onChange:m,options:ne})]}),(I==null?void 0:I.devices)>0&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx(T.Text,{style:{color:g.greyF[700]},children:"Количество устройств:"}),e.jsx(Qe,{style:{width:"100%"},min:I.devices,value:C,onChange:x=>S(x)}),te>0&&e.jsxs(T.Text,{style:{fontSize:12,color:g.greyF[700]},children:["+",te," доп. ",te===1?"устройство":te<5?"устройства":"устройств"," × ",he.toLocaleString("ru-RU")," ₽"]})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx(T.Text,{style:{color:g.greyF[700]},children:"Способ оплаты:"}),e.jsx("div",{style:{display:"flex",gap:8},children:pr.map(x=>e.jsx(hr,{method:x,selected:v===x.value,onClick:()=>R(x.value)},x.value))})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[e.jsx(lt,{checked:b&&v==="russia",onChange:x=>w(x.target.checked),disabled:v==="foreign",className:"checkbox-large",style:{fontSize:16,fontWeight:500},children:"Подключить автоплатёж"}),b&&v==="russia"&&e.jsxs(T.Text,{style:{fontSize:12,color:g.greyF[700],paddingLeft:24},children:["Условия автоплатежа",e.jsx("br",{}),"Автоматическое списание будет производиться каждые 30 дней"]}),v==="foreign"&&e.jsx(T.Text,{style:{fontSize:12,color:g.greyF[700]},children:"При оплате методом «Иностранная карта» нет возможности подключить автоплатёж."})]}),e.jsx(me,{style:{margin:0}}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",background:g.primary[50],border:`1px solid ${g.primary[200]}`,borderRadius:8,padding:"12px 16px"},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.jsx(T.Text,{style:{color:g.greyF[700],fontSize:13},children:"Итого:"}),e.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8},children:[e.jsx(T.Text,{strong:!0,style:{fontSize:22},children:K!==null?`${K.toLocaleString("ru-RU")} ₽`:"—"}),E&&K!==null&&I&&e.jsxs(T.Text,{style:{fontSize:14,color:g.greyF[400],textDecoration:"line-through"},children:[(j*((I.price??0)+te*(I.device_price??0))).toLocaleString("ru-RU")," ₽"]})]})]}),e.jsx(be,{variant:"contained",color:"primary",onClick:H,disabled:!f||h,loading:h,children:"Оплатить"})]}),e.jsxs(T.Text,{style:{textAlign:"center",color:g.greyF[700],fontSize:13},children:["По вопросам с оплатой — ",e.jsx(T.Link,{href:"https://t.me/adm_mkeeper",target:"_blank",children:"@adm_mkeeper"})]})]})})]})}function fr(){var h;const[t,n]=i.useState(!1),[s,r]=i.useState(void 0),{showRequestError:a,showError:l}=W();i.useEffect(()=>{n(!0),N("user/license").then(o=>{r(o.data)}).catch(o=>a(o)).finally(()=>n(!1))},[]);const d=()=>{ue("billing/get_payment_link",{}).then(o=>{o.data.url?window.open(o.data.url,"_blank").focus():l("Ошибка при создании платежа")}).catch(o=>{a(`Ошибка при создании платежа: ${ut(o)}`)})};if(t)return e.jsx(je,{count:3});let u=!1;if(!(s!=null&&s.length))u=!0;else{const o=s[0];new Date(o.action_date).getFullYear()<2020&&(u=!0)}if(u)return e.jsxs("div",{style:{display:"flex",columnGap:12,alignItems:"center"},children:[e.jsx(T.Text,{children:"Отстутствует лицензия"}),e.jsx(Ze,{children:"Активировать подписку"})]});const c=s[0],p=new Date(c.action_date);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsxs(T.Text,{style:{lineHeight:1.4},children:["Номер лицензии: ",c.key]}),e.jsxs(T.Text,{style:{lineHeight:1.4},children:["Тариф ",(h=c.tariff)==null?void 0:h.name]}),c.is_active?e.jsxs(T.Text,{style:{lineHeight:1.4},children:["Подписка активна до ",p.toLocaleDateString()]}):e.jsxs(T.Text,{style:{lineHeight:1.4},children:["Подписка закончилась ",p.toLocaleDateString()]})]}),e.jsx("div",{style:{marginTop:8,display:"flex",gap:8},children:c.tariff===void 0?e.jsx(Ze,{children:"Выбрать тариф"}):e.jsx(e.Fragment,{children:e.jsx(be,{variant:"contained",onClick:d,children:"Продлить подписку"})})})]})}const xr="user/suppliers";function gr(){const[t,n]=i.useState(!0),[s,r]=i.useState([]);return i.useEffect(()=>{n(!0),N(xr).then(a=>{r(a.data)}).finally(()=>n(!1))},[]),t?e.jsx("div",{children:"Загрузка..."}):e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{style:{display:"flex",columnGap:12,alignItems:"center"},children:[e.jsx(dr,{}),e.jsx(fr,{}),e.jsx(J,{to:"/devices",children:e.jsx(L,{children:"Расширение Chrome"})})]}),s.map((a,l)=>e.jsx(cr,{item:a},l))]})}const mr=`${Je}/cabinet/supplier_full/`;function yr(){const[t,n]=i.useState([]),[s,r]=i.useState(!0);return i.useEffect(()=>{t.length===0&&(r(!0),oe.get(mr).then(a=>{n(a.data)}).finally(()=>r(!1)))},[]),e.jsxs("div",{children:[e.jsx("h1",{children:"Поставщики и ключи API"}),e.jsx(gr,{suppliers:t})]})}function jr({instance:t,campaignId:n}){return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsx(U,{id:"name",placeholder:"Наименование кампании",value:t.name??"",size:"small"}),e.jsx(U,{id:"cpm",placeholder:"Ставка",value:t.bet??"",size:"small",type:"number"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",columnGap:8},children:[e.jsx(L,{type:"primary",children:"Сохранить изменения"}),e.jsx("a",{href:tr(n),children:e.jsx(L,{type:"link",children:"Запустить биддер"})})]})]})}const vr=(t,n)=>(et.find(s=>s.id===t),`${Dt}/${n}`),_r=t=>`${dt}/auction/${t}/`;function br(){var p;const{campaignId:t}=ot(),[n,s]=i.useState(!0),[r,a]=i.useState([]),[l,d]=i.useState([]),[u,c]=i.useState(void 0);return i.useEffect(()=>{s(!0),oe.get(vr(6,t)).then(h=>{a(h.data)}).finally(()=>s(!1)),oe.get(_r(t)).then(h=>{var o,f;(f=(o=h.data)==null?void 0:o.data)==null||f.forEach((y,j)=>{y.place=j+1}),d(h.data)})},[t]),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsx(sn,{items:[{title:e.jsx("a",{href:"/campaigns",children:"Мои кампании"})},{title:t}]}),e.jsxs(T.Title,{level:5,style:{margin:0},children:["Изменение: ",(p=et.find(h=>h.id===r.advert_type))==null?void 0:p.name,": ",r.name]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"20px"},children:[n?e.jsx("div",{style:{width:"100%"},children:e.jsx(je,{})}):e.jsx(jr,{instance:r,campaignId:t}),e.jsx("div",{}),e.jsx(Sn,{...l,campaignId:t})]})]})}const Sr="&appType=1&curr=rub&dest=-1257786®ions=80,38,83,4,64,33,68,70,30,40,86,75,69,22,1,31,66,110,48,71,114&spp=0",Cr=async t=>{let{data:n}=await oe.get(`https://catalog-ads.wildberries.ru/api/v5/search?keyword=${t}`);if(!n.adverts)return null;const s=[];n.adverts.forEach(u=>s.push(u.id));let r=localStorage.getItem("geoData")||Sr;const{data:a}=await oe.get(`/api/wp/clist/?${r}&nm=${s.join(";")}`);if(!a)return null;const l=a.data.products.map(u=>(u.deliveryHours=u.time1+u.time2,u.nmId=u.id,u));return{advData:n,advGoods:l}};async function wr(t){const{data:n}=await oe.get("https://static-basket-01.wb.ru/vol0/data/subject-base.json");let s=[];const r=(a,l)=>{a.forEach(d=>{if(d.id==l){const u={id:d.id,subj_name:d.name};s.push(u)}else d.childs&&r(d.childs,l)})};return t.forEach(a=>r(n,a)),s}const kr=function(t,n,s){const{advData:r}=t;r.pages.sort((l,d)=>l.page-d.page);const a={};return s=Tr(s,r),r.pages.forEach(l=>{let d=s.splice(0,l.positions.length);d.forEach((u,c)=>{const p=r.adverts.find(h=>h.id===u.nmId);Rr(u,p,l.positions[c],l.page)}),l.page===1&&(d=n.concat(d)),d.sort((u,c)=>u.advStatFields.position-c.advStatFields.position),a[l.page]=d}),a},Rr=function(t,n,s,r=1){var a,l,d,u;t.advStatFields={advertId:n.advertId,position:s,cpm:(a=(l=t.advStatFields)===null||l===void 0?void 0:l.cpm)!==null&&a!==void 0?a:n.cpm,subjectId:t.subjectId,brandId:t.brandCod,kindId:t.kindId,page:r,mk_cpmweight:(d=(u=t.advStatFields)===null||u===void 0?void 0:u.mk_cpmweight)!==null&&d!==void 0?d:0,mk_deliveryweight:(d=(u=t.advStatFields)===null||u===void 0?void 0:u.mk_deliveryweight)!==null&&d!==void 0?d:0,totalWeight:(d=(u=t.advStatFields)===null||u===void 0?void 0:u.totalWeight)!==null&&d!==void 0?d:0,cpmRatio:t.advStatFields.cpmRatio,deliveryRatio:t.advStatFields.deliveryRatio}},Tr=function(t,n){var s,r;if((s=n.adverts)===null||s===void 0||!s.length||t==null||!t.length)return[];const a=n.adverts.reduce((d,u)=>d.set(u.id,u),new Map);if((r=n.prioritySubjects)!==null&&r!==void 0&&r.length)return Fr(t,n,a);const l=wn(t,n.adverts.length);return kn(l,n,a)},wn=function(t,n){return{advertsCount:n??0,products:t??[]}},Fr=function(t,n,s){const r=t.reduce((d,u)=>d.set(u.nmId,u),new Map),a=n.adverts.reduce((d,u)=>{var c;const p=u.subject,h=r.get(u.id),o=(c=d.get(p))!==null&&c!==void 0?c:wn();return o.advertsCount++,h&&o.products.push(h),d.set(p,o)},new Map),l=[];for(let d=0;dc.advStatFields.totalWeight==p.advStatFields.totalWeight&&p.advStatFields.cpm!=c.advStatFields.cpm?p.advStatFields.cpm-c.advStatFields.cpm:p.advStatFields.totalWeight-c.advStatFields.totalWeight),r},Ir=function(t,n,s){const{cpms:r,deliveries:a}=t.reduce((c,p)=>{if(!p)return;const h=n.get(p.nmId);return c.deliveries.add(p.deliveryHours),c.cpms.add(h.cpm),c},{cpms:new Set,deliveries:new Set}),l=1/s.advertsCount;function d(c){let p=1;return c.reduce((h,o)=>h.has(o)?h:(h.size>0&&(p-=l),h.set(o,p)),new Map)}function u(c,p){const h=Array.from(c);return h.sort(p),h}return{weightMapCpm:d(u(r,(c,p)=>p-c)),weightMapDelivery:d(u(a,(c,p)=>c-p))}},Dr=function(t){var n,s;let r=.6666666666666666,a=1/3;if(t!=null&&(n=t.sortWeights)!==null&&n!==void 0&&n.cpm&&t!=null&&(s=t.sortWeights)!==null&&s!==void 0&&s.delivery){const l=t.sortWeights.cpm+t.sortWeights.delivery;l&&(r=t.sortWeights.cpm/l,a=t.sortWeights.delivery/l)}return{cpmRatio:r,deliveryRatio:a}};function Er(t,n){const s=new Map;t.advData.adverts.forEach(p=>{s.has(p.id)||s.set(p.id,p)});const r=kr(t,[],t.advGoods),a=[];let l=0,d=0,u=0;Object.entries(r).forEach((p,h)=>{p[1].forEach(o=>{const f=++l;let y;n&&(y=n.find(m=>m.id===o.advStatFields.subjectId)),d||(d=o.advStatFields.cpmRatio),u||(u=o.advStatFields.deliveryRatio);const j={brand:o.brand,deliveryHours:o.deliveryHours,id:o.cod1S||o.id,n:f,page:o.advStatFields.page,pl:l,position:o.advStatFields.position,subj_name:y?y.subj_name:"",cpm:o.advStatFields.cpm,cpmWeight:o.advStatFields.mk_cpmweight.toFixed(3),deliveryWeight:o.advStatFields.mk_deliveryweight.toFixed(3),totalWeight:o.advStatFields.totalWeight.toFixed(3),subject:"",name:o.name};a.push(j)})});const c={cpm:"",delivery:"",cpmPercentages:null,deliveryPercentages:null};return t.advData.sortWeights&&(c.cpm=`${t.advData.sortWeights.cpm}/${t.advData.sortWeights.cpm+t.advData.sortWeights.delivery}`,c.delivery=`${t.advData.sortWeights.delivery}/${t.advData.sortWeights.cpm+t.advData.sortWeights.delivery}`),c.cpmPercentages=d*100,c.deliveryPercentages=u*100,{data:a,ratio:c}}async function Lr(t){const n=await Cr(t);if(n===null)return new Promise((a,l)=>a([]));const s=await wr(n.advData.prioritySubjects),r=Er(n,s);return new Promise((a,l)=>a(r.data))}var _e=(t=>(t[t.Small=360]="Small",t[t.Mobile=414]="Mobile",t[t.Tablet=768]="Tablet",t[t.Medium=1280]="Medium",t[t.Laptop=1366]="Laptop",t[t.Large=1920]="Large",t))(_e||{});const ht=i.createContext({resolution:1920}),Pt=()=>document.body.clientWidth<=360?360:document.body.clientWidth<=414?414:document.body.clientWidth<=768?768:document.body.clientWidth<=1280?1280:document.body.clientWidth<=1366?1366:1920;function $r({children:t}){const[n,s]=i.useState(document.body.clientWidth);return i.useEffect(()=>{window.addEventListener("resize",()=>s(Pt())),s(Pt())},[]),e.jsx(ht.Provider,{value:{resolution:n},children:t})}function Rn(t,n=246,s=328){return`//basket-${Mr(Math.floor(t/1e5))}.wb.ru/vol${Math.floor(t/1e5)}/part${Math.floor(t/1e3)}/${t}/images/c${n}x${s}/1.jpg`}function Mr(t){return t>=0&&t<=143?"01":t>=144&&t<=287?"02":t>=288&&t<=431?"03":t>=432&&t<=719?"04":t>=720&&t<=1007?"05":t>=1008&&t<=1061?"06":t>=1062&&t<=1115?"07":t>=1116&&t<=1169?"08":t>=1170&&t<=1313?"09":t>=1314&&t<=1601?"10":t>=1602&&t<=1655?"11":"12"}function zr({rows:t,skeleton:n}){return n?e.jsx("div",{children:[...Array(5)].map((s,r)=>e.jsxs("div",{style:{border:"1px solid #d5d5d5",padding:"8px",borderRadius:"10px",marginTop:r>0?"15px":0},children:[e.jsx(G.Input,{active:!0,block:!0,style:{height:15,width:"100%"}}),e.jsxs("div",{style:{display:"flex",marginTop:"4px",width:"100%"},children:[e.jsx(G.Image,{active:!0,style:{height:80,width:60,marginRight:"4px"}}),e.jsxs("div",{style:{width:"100%"},children:[e.jsx(G.Input,{active:!0,block:!0,style:{height:15,width:"100%"}}),e.jsx(G.Input,{active:!0,block:!0,style:{height:15,width:"100%",marginTop:"4px"}}),e.jsx(G.Input,{active:!0,block:!0,style:{height:15,width:"100%",marginTop:"4px"}})]})]})]},r))}):t.length?e.jsx("div",{children:t.map(s=>e.jsxs("div",{style:{border:"1px solid #d5d5d5",padding:"8px",borderRadius:"10px",marginTop:"15px"},children:[e.jsxs("div",{style:{display:"flex"},children:[e.jsx("span",{style:{marginRight:"5px",fontSize:"12px"},children:s.n}),e.jsx("span",{style:{fontSize:"12px"},children:s.name})]}),e.jsxs("div",{style:{display:"flex",width:"100%",marginTop:"4px"},children:[e.jsx("a",{href:`https://www.wildberries.ru/catalog/${s.id}/detail.aspx`,target:"_blank",style:{height:"80px",marginRight:"5px"},children:e.jsx("img",{height:"80px",src:`${Rn(s.id)}`,style:{borderRadius:"5px"}})}),e.jsxs("div",{style:{marginRight:"16px",flexGrow:1},children:[e.jsxs("div",{style:{fontSize:"12px"},children:["Артикул: ",s.id]}),e.jsxs("div",{style:{fontSize:"12px"},children:["Бренд: ",s.brand]}),e.jsxs("div",{style:{fontSize:"12px"},children:["Категория: ",s.subj_name]})]}),e.jsxs("div",{style:{minWidth:"90px"},children:[e.jsxs("div",{style:{fontSize:"12px"},children:["Ставка: ",s.cpm," ₽"]}),e.jsxs("div",{style:{fontSize:"12px"},children:["Доставка: ",s.deliveryHours," ч."]})]})]})]},s.id))}):e.jsx("div",{style:{width:"100%",textAlign:"center"},children:"Пусто..."})}const Pr=[{title:"№",dataIndex:"n",key:"n",align:"center",render:t=>de(t)},{title:"",key:"img",align:"center",render:(t,n)=>e.jsx("a",{href:`https://www.wildberries.ru/catalog/${n.id}/detail.aspx`,target:"_blank",children:e.jsx("img",{height:"22px",src:`${Rn(n.id)}`})})},{title:"Артикул",key:"id",align:"center",render:(t,n)=>e.jsx("a",{href:`https://www.wildberries.ru/catalog/${n.id}/detail.aspx`,target:"_blank",children:n.id})},{title:"Бренд",dataIndex:"brand",key:"brand",align:"center"},{title:"Категория",dataIndex:"subj_name",key:"subj_name",align:"center"},{title:"Ставка",key:"cpm",align:"center",render:(t,n)=>`${de(n.cpm)} ₽`},{title:"Вес ставки",key:"cpmWeight",align:"center",render:(t,n)=>de(n.cpmWeight)},{title:"Доставка",key:"deliveryHours",align:"center",render:(t,n)=>`${de(n.deliveryHours)} ч.`},{title:"Вес доставки",key:"deliveryWeight",align:"center",render:(t,n)=>de(n.deliveryWeight)},{title:"Общий вес",key:"totalWeight",align:"center",render:(t,n)=>de(n.totalWeight)},{title:"Место",key:"pl",align:"center",render:(t,n)=>de(n.pl)},{title:"Страница",key:"page",align:"center",render:(t,n)=>de(n.page)},{title:"Позиция",key:"position",align:"center",render:(t,n)=>de(n.position)}];function Ar({rows:t,skeleton:n}){return n?e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[...Array(8)].map((s,r)=>e.jsx(G.Input,{active:!0,block:!0,style:{height:32,width:"100%"}},r))}):e.jsx(Te,{columns:Pr,dataSource:t||[],rowKey:"id",size:"small",pagination:!1,locale:{emptyText:"Пусто..."}})}function Wr({rows:t,skeleton:n}){const{resolution:s}=i.useContext(ht);return e.jsx(e.Fragment,{children:s<=_e.Mobile?e.jsx(zr,{skeleton:n,rows:t}):e.jsx(Ar,{skeleton:n,rows:t})})}const Hr=async t=>{const{data:n}=await oe.get(`https://search.wb.ru/suggests/api/v3/hint?query=${t}&gender=common&locale=ru&lang=ru`);let s=[];return n.forEach(r=>{r.type==="suggest"&&s.push({label:r.name})}),new Promise((r,a)=>r(s))};function Nr(){const[t,n]=i.useState(""),[s,r]=i.useState(!1),[a,l]=St("",300),[d,u]=i.useState([]),[c,p]=i.useState([]),h=f=>{n(f),f&&(l(f),r(!0))};i.useEffect(()=>{if(!t){u([]),p([]),r(!1);return}Lr(t).then(f=>{u(f),r(!1)}),Hr(t).then(f=>{Array.isArray(f)&&p(f)})},[a]);const o=c.map(f=>({value:f.label,label:f.label}));return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(T.Title,{level:4,style:{margin:0},children:"Аукцион поиска"}),e.jsx("div",{children:e.jsx(en,{style:{width:"100%"},options:o,value:t,onSelect:f=>h(f),onSearch:f=>h(f),children:e.jsx(U.Search,{placeholder:"Введите текст для поиска",size:"large"})})}),e.jsx("div",{children:e.jsx(Wr,{rows:d,skeleton:s})})]})}const Or="mkeeper_direct_bot";function qr(){const{profile:t}=pe(),[n,s]=i.useState(null),[r,a]=i.useState(!1);if(i.useEffect(()=>{t.tg_id||(a(!0),B("user/tg-link-code").then(d=>{s(d.data.code)}).finally(()=>{a(!1)}))},[t.tg_id]),r||!n)return e.jsx(Le,{});const l=`https://t.me/${Or}?start=tg_mk_${n}`;return e.jsxs("div",{children:[e.jsx(T.Text,{type:"secondary",style:{display:"block",marginBottom:16},children:"Отсканируйте QR-код или перейдите по ссылке для привязки аккаунта"}),e.jsxs(ss,{align:"center",gap:24,wrap:"wrap",children:[e.jsx(rs,{value:l,size:160,fgColor:g.text,level:"M"}),e.jsx(T.Link,{href:l,target:"_blank",children:l})]})]})}function Br({onConfirm:t,title:n,button:s,children:r}){const[a,l]=i.useState(!1),d=()=>{l(!0)},u=()=>{l(!1)},c=()=>{t&&t(),l(!1)};return e.jsxs(e.Fragment,{children:[e.jsx("div",{onClick:d,className:"hoverable-icon",children:s}),e.jsxs(Fe,{open:a,onCancel:u,title:n,footer:null,closeIcon:e.jsx(Cn,{}),width:455,styles:{body:{padding:"16px 16px 0"}},children:[r&&e.jsx("div",{style:{marginBottom:16},children:r}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx(be,{onClick:c,variant:"outlined",color:"error",sx:{width:"100%"},children:"Подтвердить"}),e.jsx(be,{onClick:u,variant:"outlined",color:"secondary",sx:{width:"100%"},children:"Отмена"})]})]})]})}const Gr=30,$e=44,Ur=30,Me=40,Vr="_textCell_j8spt_1",At={textCell:Vr},le=({value:t,textAlignment:n="left",link:s,routerLink:r,afterIcon:a})=>{let l=t;return r?l=e.jsx(J,{to:r,children:t}):s&&(l=e.jsx("a",{href:s,target:"_blank",children:t})),e.jsxs("div",{className:At.textCell,style:{textAlign:n},children:[e.jsx("span",{className:At.text,style:{fontSize:"16px",lineHeight:1.4,color:"#383540"},children:l}),a||""]})},Kr="_headerContainer_1o3pk_1",Zr="_customHeaderLabel_1o3pk_19",Wt={headerContainer:Kr,customHeaderLabel:Zr},Yr=({size:t=16,color:n,direction:s="right"})=>{const r={up:"0deg",right:"90deg",down:"180deg"},a=n||g.dark[500];return e.jsx("svg",{style:{transform:`rotate(${r[s]})`},xmlns:"http://www.w3.org/2000/svg",width:t,height:t,viewBox:"0 0 16 16",fill:"none",children:e.jsx("path",{d:"M8.61193 13.5L7.39003 13.5L7.40317 5.84127L7.16667 6.06614L4.36813 8.89683L3.50098 8.05026L7.99441 3.5L12.501 8.03704L11.6338 8.89682L8.59879 5.82804L8.61193 13.5Z",fill:a})})},Ce=t=>{const[n,s]=i.useState(!1),[r,a]=i.useState(!1),l=()=>{const u=t.column.getSort();s(u==="asc"),a(u==="desc")},d=u=>{const c=n?"desc":"asc";t.setSort(c,u.shiftKey)};return i.useEffect(()=>{t.column.addEventListener("sortChanged",l),l()},[]),e.jsxs("div",{className:Wt.headerContainer,onClick:d,onTouchEnd:d,style:t.enableSorting?{cursor:"pointer"}:{},children:[e.jsx("span",{className:Wt.customHeaderLabel,style:{fontSize:"16px",lineHeight:1.4,color:g.greyF[700],...t.wrapText?{whiteSpace:"normal"}:{}},children:t.displayName}),t.enableSorting?e.jsx("span",{style:{minWidth:"16px",maxWidth:"16px",minHeight:"16px",maxHeight:"16px"},children:e.jsx(Yr,{direction:r?"down":"up",color:n||r?g.blue[500]:g.greyF[700]})}):""]})},Qr=()=>e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",children:[e.jsxs("g",{clipPath:"url(#clip0_7578_23038)",children:[e.jsx("mask",{id:"mask0_7578_23038",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:"0",y:"0",width:"24",height:"24",children:e.jsx("rect",{width:"24",height:"24",fill:"#D9D9D9"})}),e.jsx("g",{mask:"url(#mask0_7578_23038)",children:e.jsx("path",{d:"M7 21C6.45 21 5.97917 20.8042 5.5875 20.4125C5.19583 20.0208 5 19.55 5 19V6H4V4H9V3H15V4H20V6H19V19C19 19.55 18.8042 20.0208 18.4125 20.4125C18.0208 20.8042 17.55 21 17 21H7ZM9 17H11V8H9V17ZM13 17H15V8H13V17Z",fill:g.redPale[400]})})]}),e.jsx("defs",{children:e.jsx("clipPath",{id:"clip0_7578_23038",children:e.jsx("rect",{width:"24",height:"24",fill:"white"})})})]}),we=({message:t})=>e.jsx("div",{style:{padding:"20px",color:"#666666",fontSize:"16px",pointerEvents:"all",lineHeight:"1.5",display:"block"},children:e.jsx("span",{children:t||"Нет данных"})}),Ht="user/device";function Xr(){const[t,n]=i.useState(!0),[s,r]=i.useState([]),{showRequestError:a}=W(),l=()=>{n(!0),N(Ht).then(p=>{r(p.data)}).catch(p=>{a(p)}).finally(()=>n(!1))};i.useEffect(()=>{l()},[]);const d=p=>p?new Date(p).toLocaleString("ru-RU",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"—",u=p=>{ys(`${Ht}/${p}`).then(h=>{l()})};if(t)return e.jsx(je,{count:2});const c=[{headerName:"Ключ активации",field:"key",cellRenderer:p=>e.jsx(le,{value:p.value})},{headerName:"User Agent",field:"user_agent",cellRenderer:p=>e.jsx(le,{value:p.value})},{headerName:"Дата использования",field:"last_check",cellRenderer:p=>e.jsx(le,{value:d(p.value)})},{headerName:"Дата активации",field:"activation_date",cellRenderer:p=>e.jsx(le,{value:d(p.value),afterIcon:e.jsx("div",{style:{height:"24px",marginLeft:"auto"},children:e.jsx(Br,{button:e.jsx(Qr,{}),title:"Деактивировать устройство?",onConfirm:()=>u(p.data.dev_num)})})})}];return e.jsx(e.Fragment,{children:e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:e.jsx("div",{style:{width:"100%"},children:e.jsx(Se,{domLayout:"autoHeight",rowHeight:Ur,headerHeight:Gr,rowData:s,columnDefs:c,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!1,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:Ce},onFirstDataRendered:p=>p.api.sizeColumnsToFit(),noRowsOverlayComponent:we})})})})}function Tn(){const{profile:t}=pe();return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:24},children:[e.jsx(T.Title,{level:5,style:{margin:0},children:"Устройства"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:16},children:e.jsx(Xr,{})})]})}function Fn({hidden:t}){const n=Xe(),{profile:s}=pe(),{showRequestError:r,showError:a}=W(),[l,d]=i.useState("");return i.useEffect(()=>{s.auth?B("user/device/new").then(u=>{var c;(c=u.data)!=null&&c.key?d(u.data.key):(a("Нет свободных активаций. Отвяжите одно устройство или повысьте тариф"),n("/"))}).catch(u=>{}):n("/auth/login")},[]),e.jsxs("div",{children:[!t&&e.jsx(Le,{}),e.jsx("input",{type:"hidden",id:"new-device-key",value:l})]})}function ve({label:t,value:n}){return e.jsxs("div",{style:{display:"flex",gap:16,paddingBlock:10},children:[e.jsx(T.Text,{style:{minWidth:180,color:"#888"},children:t}),e.jsx(T.Text,{children:n})]})}function xt({children:t}){return e.jsx(T.Title,{level:5,style:{margin:0},children:t})}function Jr({onDevicesClick:t}){var j;const{profile:n}=pe(),[s,r]=i.useState(void 0),[a,l]=i.useState(!0),[d,u]=i.useState(!1),{showRequestError:c,showError:p,showMessage:h}=W();if(i.useEffect(()=>{n.tg_id&&u(!1)},[n.tg_id]),i.useEffect(()=>{l(!0),N("user/license").then(m=>{r(m.data)}).catch(m=>c(m)).finally(()=>l(!1))},[]),a)return e.jsx(je,{count:4});const o=s==null?void 0:s[0],f=o&&new Date(o.action_date).getFullYear()>=2020,y=f?new Date(o.action_date).toLocaleDateString("ru-RU"):null;return e.jsxs("div",{style:{display:"flex",flexDirection:"column",maxWidth:560},children:[e.jsx(xt,{children:"Общая информация"}),e.jsx(me,{style:{marginTop:8,marginBottom:0}}),n.wb_id&&e.jsx(ve,{label:"WB ID:",value:n.wb_id}),e.jsx(ve,{label:"Telegram:",value:n.tg_id?e.jsx(T.Text,{children:n.tg_username?`${n.tg_username} (${n.tg_id})`:n.tg_id}):e.jsx(T.Link,{onClick:()=>u(!0),children:"Привязать"})}),e.jsx(Fe,{open:d,onCancel:()=>u(!1),title:"Привязка Telegram",footer:null,width:480,children:e.jsx("div",{style:{paddingTop:8},children:e.jsx(qr,{})})}),e.jsxs("div",{style:{marginTop:24},children:[e.jsx(xt,{children:"Информация о тарифе"}),e.jsx(me,{style:{marginTop:8,marginBottom:0}}),f?e.jsxs(e.Fragment,{children:[e.jsx(ve,{label:"Тариф:",value:((j=o.tariff)==null?void 0:j.name)??"—"}),e.jsx(ve,{label:"Лицензионный ключ:",value:o.key}),e.jsx(ve,{label:"Действует до:",value:e.jsx(T.Text,{style:new Date(o.action_date)0&&e.jsx(ve,{label:"Подключено устройств:",value:e.jsxs(T.Link,{onClick:t,children:[o.devices_used??0," из ",o.devices]})}),e.jsxs("div",{style:{marginTop:16,display:"flex",gap:8},children:[e.jsx(Ze,{variant:"contained",licenseKey:o.key,children:"Продлить тариф"}),e.jsx(Ze,{disabled:!0,variant:"outlined",licenseKey:o.key,children:"Сменить тариф"}),e.jsx(be,{disabled:!0,variant:"outlined",children:"История оплат"})]})]}):e.jsx("div",{style:{paddingTop:12},children:e.jsx(Ze,{children:"Активировать подписку"})})]}),f&&o.autopay&&e.jsxs("div",{style:{marginTop:24},children:[e.jsx(xt,{children:"Автоплатёж"}),e.jsx(me,{style:{marginTop:8,marginBottom:0}}),o.next_pay_at&&e.jsx(ve,{label:"Следующее списание:",value:new Date(o.next_pay_at).toLocaleDateString("ru-RU")}),o.next_pay_amount!=null&&e.jsx(ve,{label:"Сумма списания:",value:`${o.next_pay_amount.toLocaleString("ru-RU")} ₽`}),o.autopay&&e.jsxs("div",{style:{paddingTop:10},children:[e.jsx(T.Text,{children:"Автоплатёж подключён. Вы можете "}),e.jsx(is,{title:"Отключить автоплатёж?",description:"Автоплатёж будет отключён. Текущий период останется активным.",okText:"Отключить",cancelText:"Назад",okButtonProps:{danger:!0},onConfirm:()=>{B("user/cancel-payment",{}).then(m=>{var v;(v=m.data)!=null&&v.message&&h(m.data.message),r(R=>R.map((b,w)=>w===0?{...b,autopay:!1,next_pay_at:null}:b))}).catch(m=>{var v,R;p(((R=(v=m.response)==null?void 0:v.data)==null?void 0:R.error)??ut(m))})},children:e.jsx(T.Link,{children:"Отключить автоплатёж"})})]})]})]})}function ei(){const{profile:t}=pe(),[n]=Ft(),[s,r]=i.useState("general"),a=n.get("auth")==="success";if(t.auth===void 0)return e.jsx(Le,{});if(t.auth===!1)return e.jsx(pt,{});const l=[{key:"general",label:"Общее",children:e.jsx(Jr,{onDevicesClick:()=>r("devices")})},{key:"devices",label:"Устройства",children:e.jsx(Tn,{})},{key:"shops",label:"Магазины",children:null},{key:"employees",label:"Сотрудники",children:null},{key:"referral",label:"Партнёрская программа",children:null}];return e.jsxs("div",{style:{maxWidth:900},children:[e.jsx(T.Title,{level:4,style:{margin:0,marginBottom:24},children:"Профиль"}),e.jsx(Tt,{items:l,activeKey:s,onChange:r}),a&&e.jsx(Fn,{hidden:!0})]})}const ti=()=>{const{clearProfile:t}=pe(),n=Xe(),s=()=>{qe.logout().then(()=>{}).catch(r=>console.log("wb logout error:",r)),ue("user/logout").then(()=>{t(),n("/")}).catch(r=>{})};return i.useEffect(()=>{s()},[s]),e.jsx("div",{className:"auth-page",children:"Выход..."})},ni="_numberCell_1xqpf_1",si="_number_1xqpf_1",ri="_tag_1xqpf_17",Ae={numberCell:ni,number:si,tag:ri},q=({value:t,digits:n,cellStyle:s,textAlignment:r="end",tag:a=!1,icon:l=!1,prefix:d=!1,suffix:u=!1})=>{const c=p=>isNaN(p)||!isFinite(p)?"--":n!==void 0?p.toLocaleString("ru-RU",{minimumFractionDigits:n,maximumFractionDigits:n}):p.toLocaleString("ru-RU");return e.jsxs("div",{className:Ae.numberCell,style:{...s,justifyContent:r},children:[a&&e.jsx("div",{className:Ae.tag,children:a}),l&&e.jsx("div",{className:Ae.icon,children:l}),e.jsxs("span",{className:Ae.number,style:{fontSize:"16px",lineHeight:1.4,color:"#383540"},children:[d&&t!=null&&e.jsx("div",{className:Ae.prefix,children:d}),c(Number(t)),u&&t!=null&&e.jsx("div",{className:Ae.suffix,children:u})]})]})},ii="_container_10jp5_1",ai="_input_10jp5_10",gt={container:ii,input:ai},li=500,ke=i.forwardRef((t,n)=>{const[s,r]=i.useState(""),[a,l]=i.useState(""),d=i.useRef(null);i.useImperativeHandle(n,()=>({onParentModelChanged(o){o||(r(""),l(""))}}));const u=(o,f)=>{const y=o?Number(o):null,j=f?Number(f):null;y!=null&&j!=null?t.onModelChange({type:"inRange",filter:y,filterTo:j}):y!=null?t.onModelChange({type:"greaterThanOrEqual",filter:y}):j!=null?t.onModelChange({type:"lessThanOrEqual",filter:j}):t.onModelChange(null)},c=(o,f)=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{u(o,f)},li)},p=o=>{const f=o.target.value;r(f),c(f,a)},h=o=>{const f=o.target.value;l(f),c(s,f)};return e.jsxs("div",{className:gt.container,children:[e.jsx("input",{className:gt.input,type:"number",placeholder:"От",value:s,onChange:p}),e.jsx("input",{className:gt.input,type:"number",placeholder:"До",value:a,onChange:h})]})});ke.displayName="RangeFloatingFilter";Ie.setLicenseKey("key");De.registerModules([Ee]);const oi=64,ci=10,di=()=>e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",width:"100%",height:"100%"},children:e.jsx(G.Input,{active:!0,size:"small",block:!0,style:{height:20,minWidth:0}})}),Ye=t=>n=>{var s;return(s=n.context)!=null&&s.loading?e.jsx(di,{}):t(n)},ui={category_name:{text:"category"},subject_name:{text:"subject_name"},revenue:{min:"revenue_min",max:"revenue_max"},revenue_change_pc:{min:"revenue_change_pc_min",max:"revenue_change_pc_max"},cards_count:{min:"cards_count_min",max:"cards_count_max"},cards_count_change_pc:{min:"cards_count_change_pc_min",max:"cards_count_change_pc_max"},cards_with_orders_count:{min:"cards_with_orders_count_min",max:"cards_with_orders_count_max"},cards_with_orders_count_change_pc:{min:"cards_with_orders_count_change_pc_min",max:"cards_with_orders_count_change_pc_max"},suppliers:{min:"suppliers_min",max:"suppliers_max"},suppliers_change_pc:{min:"suppliers_change_pc_min",max:"suppliers_change_pc_max"},suppliers_with_sells:{min:"suppliers_with_sells_min",max:"suppliers_with_sells_max"},suppliers_with_sells_change_pc:{min:"suppliers_with_sells_change_pc_min",max:"suppliers_with_sells_change_pc_max"},redemption_pc:{min:"redemption_pc_min",max:"redemption_pc_max"},redemption_pc_change_pc:{min:"redemption_pc_change_pc_min",max:"redemption_pc_change_pc_max"},buyouts_qty:{min:"buyouts_qty_min",max:"buyouts_qty_max"},buyouts_qty_change_pc:{min:"buyouts_qty_change_pc_min",max:"buyouts_qty_change_pc_max"},orders_qty:{min:"orders_qty_min",max:"orders_qty_max"},orders_qty_change_pc:{min:"orders_qty_change_pc_min",max:"orders_qty_change_pc_max"},orders_rub:{min:"orders_rub_min",max:"orders_rub_max"},orders_rub_change_pc:{min:"orders_rub_change_pc_min",max:"orders_rub_change_pc_max"},buyouts_rub:{min:"buyouts_rub_min",max:"buyouts_rub_max"},buyouts_rub_change_pc:{min:"buyouts_rub_change_pc_min",max:"buyouts_rub_change_pc_max"},avg_check:{min:"avg_check_min",max:"avg_check_max"},avg_check_change_pc:{min:"avg_check_change_pc_min",max:"avg_check_change_pc_max"},weekly_turnover_days:{min:"weekly_turnover_days_min",max:"weekly_turnover_days_max"},weekly_turnover_days_change_pc:{min:"weekly_turnover_days_change_pc_min",max:"weekly_turnover_days_change_pc_max"},monopolization_pc:{min:"monopolization_pc_min",max:"monopolization_pc_max"},monopolization_pc_change_pc:{min:"monopolization_pc_change_pc_min",max:"monopolization_pc_change_pc_max"},remaining_count:{min:"remaining_count_min",max:"remaining_count_max"},remaining_count_change_pc:{min:"remaining_count_change_pc_min",max:"remaining_count_change_pc_max"},avg_rating:{min:"avg_rating_min",max:"avg_rating_max"},avg_rating_change_pc:{min:"avg_rating_change_pc_min",max:"avg_rating_change_pc_max"}};function pi(t){const n={};for(const[s,r]of Object.entries(t)){const a=ui[s];a&&("text"in a?r.filter&&(n[a.text]=r.filter):r.type==="inRange"?(r.filter!=null&&(n[a.min]=String(r.filter)),r.filterTo!=null&&(n[a.max]=String(r.filterTo))):r.type==="greaterThanOrEqual"?r.filter!=null&&(n[a.min]=String(r.filter)):r.type==="lessThanOrEqual"&&r.filter!=null&&(n[a.max]=String(r.filter)))}return n}const re=(t,n,s={})=>({headerName:t,field:n,filter:"agNumberColumnFilter",floatingFilter:!0,floatingFilterComponent:ke,minWidth:130,cellRenderer:Ye(r=>e.jsx(q,{value:r.value,...s}))}),hi=t=>t==null||isNaN(t)||!isFinite(t)?"--":t.toLocaleString("ru-RU"),se=(t,n)=>({headerName:t,field:n,filter:"agNumberColumnFilter",floatingFilter:!0,floatingFilterComponent:ke,minWidth:170,cellRenderer:Ye(s=>{const r=s.value;if(r==null)return e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",width:"100%",height:"100%"},children:"--"});const a=r>=0,l=a?g.green[500]:g.red[500],d=a?kt:Rt;return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:4,width:"100%",height:"100%",color:l,fontSize:16,lineHeight:1.4,whiteSpace:"nowrap"},children:[e.jsx(d,{style:{fontSize:10}}),hi(r),"%"]})})}),_t=[{headerName:"Категория",field:"category_name",filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:200,cellRenderer:Ye(t=>e.jsx(le,{value:t.value}))},{headerName:"Предмет",field:"subject_name",filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:150,cellRenderer:Ye(t=>e.jsx(le,{value:t.value,routerLink:`/external-analytics/niche-analysis/${t.data.subject}`}))},re("Выручка","revenue",{suffix:" ₽"}),se("Δ Выручка, %","revenue_change_pc"),re("Карточек товаров","cards_count"),se("Δ Карточек товаров, %","cards_count_change_pc"),{...re("Карточек с заказами","cards_with_orders_count"),minWidth:140},{...se("Δ Карточек с заказами, %","cards_with_orders_count_change_pc"),minWidth:160},{...re("Продавцы","suppliers"),minWidth:110},se("Δ Продавцы, %","suppliers_change_pc"),{...re("Продавцы с заказами","suppliers_with_sells"),minWidth:140},{...se("Δ Продавцы с заказами, %","suppliers_with_sells_change_pc"),minWidth:160},{...re("% выкупа","redemption_pc",{suffix:"%"}),minWidth:110},se("Δ % выкупа, %","redemption_pc_change_pc"),re("Заказы, шт","orders_qty"),se("Δ Заказы шт, %","orders_qty_change_pc"),re("Заказы, ₽","orders_rub",{suffix:" ₽"}),se("Δ Заказы ₽, %","orders_rub_change_pc"),re("Выкупы, шт","buyouts_qty"),se("Δ Выкупы шт, %","buyouts_qty_change_pc"),re("Выкупы, ₽","buyouts_rub",{suffix:" ₽"}),se("Δ Выкупы ₽, %","buyouts_rub_change_pc"),{...re("Средний чек","avg_check",{suffix:" ₽"}),minWidth:120},se("Δ Средний чек, %","avg_check_change_pc"),re("Оборачиваемость","weekly_turnover_days"),se("Δ Оборачиваемость, %","weekly_turnover_days_change_pc"),re("Монополизация","monopolization_pc"),se("Δ Монополизация, %","monopolization_pc_change_pc"),{...re("Среднее кол-во остатков","remaining_count"),minWidth:160},{...se("Δ Среднее кол-во остатков, %","remaining_count_change_pc"),minWidth:180},{headerName:"Средний рейтинг",field:"avg_rating",filter:"agNumberColumnFilter",floatingFilter:!0,floatingFilterComponent:ke,minWidth:130,cellRenderer:Ye(t=>e.jsx(q,{value:t.value,digits:1,icon:e.jsx(as,{style:{color:g.primary[500],fontSize:14}})}))},se("Δ Средний рейтинг, %","avg_rating_change_pc")],Nt=_t.map(t=>({field:t.field,headerName:t.headerName})),fi=t=>Array.from({length:t},(n,s)=>({_id:s}));function xi({rowData:t,loading:n,onFilterChanged:s,onSortChanged:r,hiddenColumns:a=[]}){const l=i.useRef(ci);!n&&t.length&&(l.current=t.length);const d=i.useMemo(()=>n?fi(l.current):t,[n,t]),u=i.useMemo(()=>({loading:n}),[n]),c=i.useMemo(()=>a.length?_t.filter(o=>!a.includes(o.field)):_t,[a]),p=i.useCallback(o=>{if(!s)return;const f=o.api.getFilterModel(),y=pi(f);s(y)},[s]),h=i.useCallback(o=>{if(!r)return;const f=o.api.getColumnState().filter(y=>y.sort).map(y=>y.sort==="desc"?`-${y.colId}`:y.colId);r(f.length?f.join(","):null)},[r]);return e.jsx("div",{style:{width:"100%"},children:e.jsx(Se,{domLayout:"autoHeight",rowHeight:Me,headerHeight:$e,floatingFiltersHeight:oi,rowData:d,columnDefs:c,context:u,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!0,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:Ce,headerComponentParams:{enableSorting:!0,wrapText:!0}},onGridReady:o=>{o.api.sizeColumnsToFit()},onGridSizeChanged:o=>{o.api.sizeColumnsToFit()},onFilterChanged:p,onSortChanged:h,noRowsOverlayComponent:we})})}function In(t,n){const[s,r]=i.useState(()=>{try{const h=localStorage.getItem(t);return h?JSON.parse(h):[]}catch{return[]}}),[a,l]=i.useState(!1),d=i.useCallback(()=>l(!0),[]),u=i.useCallback(()=>l(!1),[]),c=i.useCallback((h,o)=>{r(f=>{const y=o?f.filter(j=>j!==h):[...f,h];return localStorage.setItem(t,JSON.stringify(y)),y})},[t]),p=i.useMemo(()=>new Set(n.map(h=>h.field).filter(h=>!s.includes(h))),[n,s]);return{hiddenColumns:s,visibleColumns:p,open:a,openModal:d,closeModal:u,toggleColumn:c}}function Dn({columns:t,hiddenColumns:n,open:s,onClose:r,onToggle:a}){return e.jsx(Fe,{open:s,onCancel:r,title:"Настройка колонок",footer:null,width:420,children:e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8,maxHeight:480,overflowY:"auto"},children:t.map(l=>e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"4px 0"},children:[e.jsx("span",{style:{fontSize:14},children:l.headerName}),e.jsx(ls,{size:"small",checked:!n.includes(l.field),onChange:d=>a(l.field,d)})]},l.field))})})}function En({onClick:t}){return e.jsx(L,{icon:e.jsx(os,{}),onClick:t,children:"Настроить колонки"})}const{Title:gi}=T,mi="wbstat/external_analytics",yi=[{label:"Неделя",value:"week"},{label:"Месяц",value:"month"},{label:"Квартал",value:"quarter"}];function ji(){const[t,n]=i.useState([]),[s,r]=i.useState(!0),[a,l]=i.useState({}),[d,u]=i.useState(null),[c,p]=i.useState("month"),{showRequestError:h}=W(),o=In("niche_analysis_columns",Nt),f=i.useCallback(m=>{r(!0),ie(`${mi}/`,{params:m}).then(v=>{n(v.data.results)}).catch(v=>{h(v)}).finally(()=>{r(!1)})},[h]);i.useEffect(()=>{const m={...a,period:c,page_size:100};d&&(m.ordering=d),f(m)},[a,d,c]);const y=i.useCallback(m=>{l(m)},[]),j=i.useCallback(m=>{u(m)},[]);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(gi,{level:3,style:{margin:0},children:"Анализ ниш"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap",justifyContent:"space-between"},children:[e.jsx(ce.Group,{options:yi,value:c,onChange:m=>p(m.target.value),optionType:"button",buttonStyle:"solid"}),e.jsx(En,{onClick:o.openModal})]}),e.jsx(Dn,{columns:Nt,hiddenColumns:o.hiddenColumns,open:o.open,onClose:o.closeModal,onToggle:o.toggleColumn}),e.jsx(xi,{rowData:t,loading:s,onFilterChanged:y,onSortChanged:j,hiddenColumns:o.hiddenColumns})]})}const Ot=[{key:"orders_qty",name:"Заказы (шт)",color:g.bluePale[500]},{key:"buyouts_qty",name:"Выкупы (шт)",color:g.green[500]},{key:"orders_rub",name:"Заказы (₽)",color:g.orange[500]},{key:"buyouts_rub",name:"Выкупы (₽)",color:g.cyan[500]},{key:"sellers_with_orders",name:"Продавцы с заказами",color:g.primary[500]},{key:"sellers_with_buyouts",name:"Продавцы с выкупами",color:g.red[500]},{key:"cards_with_orders",name:"Карточки с заказами",color:g.bluePale[300]},{key:"cards_with_buyouts",name:"Карточки с выкупами",color:g.green[200]}],vi=["orders_qty","buyouts_qty","orders_rub","buyouts_rub"];function _i(t){if(t==null)return"";const n=Math.abs(t);return n>=1e9?(t/1e9).toFixed(1).replace(/\.0$/,"")+" млрд":n>=1e6?(t/1e6).toFixed(1).replace(/\.0$/,"")+" млн":n>=1e3?(t/1e3).toFixed(1).replace(/\.0$/,"")+" тыс":String(t)}function bi(t){return t?new Date(t).toLocaleDateString("ru-RU",{day:"2-digit",month:"2-digit"}):""}function Si({data:t}){const[n,s]=i.useState(vi),r=i.useMemo(()=>[...t].sort((c,p)=>new Date(c.period_start)-new Date(p.period_start)),[t]),a=i.useMemo(()=>r.map(c=>bi(c.period_start)),[r]),l=i.useCallback((c,p)=>{s(h=>p?[...h,c]:h.filter(o=>o!==c))},[]),d=i.useMemo(()=>Ot.filter(c=>n.includes(c.key)),[n]),u=i.useMemo(()=>{const c=d.map((h,o)=>({type:"log",name:h.name,nameTextStyle:{color:h.color,fontSize:11},position:o%2===0?"left":"right",offset:Math.floor(o/2)*70,axisLine:{show:!0,lineStyle:{color:h.color}},axisLabel:{fontSize:11,color:h.color,formatter:_i},splitLine:{show:o===0}})),p=d.map((h,o)=>({name:h.name,type:"line",yAxisIndex:o,data:r.map(f=>f[h.key]),smooth:!0,symbol:"none",lineStyle:{width:2,color:h.color},itemStyle:{color:h.color}}));return{tooltip:{trigger:"axis",axisPointer:{type:"cross"}},grid:{left:20+Math.floor(d.filter((h,o)=>o%2===0).length/1)*35,right:20+Math.floor(d.filter((h,o)=>o%2!==0).length/1)*35,top:40,bottom:30,containLabel:!0},xAxis:{type:"category",data:a,axisLabel:{fontSize:11}},yAxis:c.length>0?c:[{type:"log"}],series:p}},[d,r,a]);return e.jsxs("div",{style:{background:"#fff",borderRadius:8,padding:16,border:"1px solid #EFF1F5"},children:[e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:12,marginBottom:12},children:Ot.map(c=>e.jsx(lt,{checked:n.includes(c.key),onChange:p=>l(c.key,p.target.checked),style:{color:c.color,fontWeight:500},children:e.jsx("span",{style:{color:c.color},children:c.name})},c.key))}),e.jsx(an,{option:u,style:{height:400},notMerge:!0})]})}Ie.setLicenseKey("key");De.registerModules([Ee]);const Ci=10,wi=()=>e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",width:"100%",height:"100%"},children:e.jsx(G.Input,{active:!0,size:"small",block:!0,style:{height:20,minWidth:0}})}),fe=t=>n=>{var s;return(s=n.context)!=null&&s.loading?e.jsx(wi,{}):t(n)};function ki(t){return t?new Date(t).toLocaleDateString("ru-RU"):""}const Ri=[{headerName:"Период",field:"period_start",minWidth:120,cellRenderer:fe(t=>e.jsx(le,{value:ki(t.value)}))},{headerName:"Брендов с выкупами",field:"brands_with_buyouts",minWidth:140,cellRenderer:fe(t=>e.jsx(q,{value:t.value}))},{headerName:"Брендов с заказами",field:"brands_with_orders",minWidth:140,cellRenderer:fe(t=>e.jsx(q,{value:t.value}))},{headerName:"Продавцов с заказами",field:"sellers_with_orders",minWidth:150,cellRenderer:fe(t=>e.jsx(q,{value:t.value}))},{headerName:"Продавцов с выкупами",field:"sellers_with_buyouts",minWidth:150,cellRenderer:fe(t=>e.jsx(q,{value:t.value}))},{headerName:"Карточек с выкупами",field:"cards_with_buyouts",minWidth:150,cellRenderer:fe(t=>e.jsx(q,{value:t.value}))},{headerName:"Карточек с заказами",field:"cards_with_orders",minWidth:150,cellRenderer:fe(t=>e.jsx(q,{value:t.value}))},{headerName:"Заказы (шт)",field:"orders_qty",minWidth:120,cellRenderer:fe(t=>e.jsx(q,{value:t.value}))},{headerName:"Заказы (₽)",field:"orders_rub",minWidth:130,cellRenderer:fe(t=>e.jsx(q,{value:t.value,suffix:" ₽"}))},{headerName:"Выкупы (шт)",field:"buyouts_qty",minWidth:120,cellRenderer:fe(t=>e.jsx(q,{value:t.value}))},{headerName:"Выкупы (₽)",field:"buyouts_rub",minWidth:130,cellRenderer:fe(t=>e.jsx(q,{value:t.value,suffix:" ₽"}))}],Ti=t=>Array.from({length:t},(n,s)=>({_id:s}));function Fi({rowData:t,loading:n}){const s=i.useRef(Ci);!n&&t.length&&(s.current=t.length);const r=i.useMemo(()=>n?Ti(s.current):t,[n,t]),a=i.useMemo(()=>({loading:n}),[n]);return e.jsx("div",{style:{width:"100%"},children:e.jsx(Se,{domLayout:"autoHeight",rowHeight:Me,headerHeight:$e,rowData:r,columnDefs:Ri,context:a,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!1,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:Ce},onGridReady:l=>{l.api.sizeColumnsToFit()},onGridSizeChanged:l=>{l.api.sizeColumnsToFit()},noRowsOverlayComponent:we})})}const{Title:Ii}=T,Di="sales/subject-dynamic",Ei=[{label:"День",value:"day"},{label:"Неделя",value:"week"},{label:"Месяц",value:"month"}];async function Li(t,n){let s=1,r=[];for(;;){const a=await ie(`${Di}/`,{params:{subject_id:t,period:n,page:s}}),{results:l,next:d}=a.data;if(r=r.concat(l),!d)break;s++}return r}function $i(){const{subjectId:t}=ln(),[n,s]=i.useState([]),[r,a]=i.useState(!0),[l,d]=i.useState("month"),{showRequestError:u}=W(),c=i.useCallback(()=>{a(!0),Li(t,l).then(h=>s(h)).catch(h=>u(h)).finally(()=>a(!1))},[t,l,u]);i.useEffect(()=>{c()},[c]);const p=n.length>0?n[0].subject_name:"";return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[e.jsx(J,{to:"/external-analytics/niche-analysis",children:e.jsx(on,{style:{fontSize:20,color:"#383540"}})}),e.jsx(Ii,{level:3,style:{margin:0},children:r&&!p?e.jsx(Be,{size:"small"}):`Динамика ниши: ${p}`})]}),e.jsx(ce.Group,{options:Ei,value:l,onChange:h=>d(h.target.value),optionType:"button",buttonStyle:"solid"}),!r&&n.length>0&&e.jsx(Si,{data:n}),e.jsx(Fi,{rowData:n,loading:r})]})}Ie.setLicenseKey("key");De.registerModules([Ee]);const Mi=64,zi=10,Pi=()=>e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",width:"100%",height:"100%"},children:e.jsx(G.Input,{active:!0,size:"small",block:!0,style:{height:20,minWidth:0}})}),Et=t=>n=>{var s;return(s=n.context)!=null&&s.loading?e.jsx(Pi,{}):t(n)},Ai={category__name:{text:"category"},orders_rub:{min:"orders_rub_min",max:"orders_rub_max"},orders_rub_change_pc:{min:"orders_rub_change_pc_min",max:"orders_rub_change_pc_max"},orders_qty:{min:"orders_qty_min",max:"orders_qty_max"},orders_qty_change_pc:{min:"orders_qty_change_pc_min",max:"orders_qty_change_pc_max"},buyouts_rub:{min:"buyouts_rub_min",max:"buyouts_rub_max"},buyouts_rub_change_pc:{min:"buyouts_rub_change_pc_min",max:"buyouts_rub_change_pc_max"},buyouts_qty:{min:"buyouts_qty_min",max:"buyouts_qty_max"},buyouts_qty_change_pc:{min:"buyouts_qty_change_pc_min",max:"buyouts_qty_change_pc_max"},cards_count:{min:"cards_count_min",max:"cards_count_max"},cards_count_change_pc:{min:"cards_count_change_pc_min",max:"cards_count_change_pc_max"},cards_with_orders_count:{min:"cards_with_orders_count_min",max:"cards_with_orders_count_max"},cards_with_orders_count_change_pc:{min:"cards_with_orders_count_change_pc_min",max:"cards_with_orders_count_change_pc_max"}};function Wi(t){const n={};for(const[s,r]of Object.entries(t)){const a=Ai[s];a&&("text"in a?r.filter&&(n[a.text]=r.filter):r.type==="inRange"?(r.filter!=null&&(n[a.min]=String(r.filter)),r.filterTo!=null&&(n[a.max]=String(r.filterTo))):r.type==="greaterThanOrEqual"?r.filter!=null&&(n[a.min]=String(r.filter)):r.type==="lessThanOrEqual"&&r.filter!=null&&(n[a.max]=String(r.filter)))}return n}const We=(t,n,s={})=>({headerName:t,field:n,filter:"agNumberColumnFilter",floatingFilter:!0,floatingFilterComponent:ke,minWidth:130,cellRenderer:Et(r=>e.jsx(q,{value:r.value,...s}))}),Hi=t=>t==null||isNaN(t)||!isFinite(t)?"--":t.toLocaleString("ru-RU"),He=(t,n)=>({headerName:t,field:n,filter:"agNumberColumnFilter",floatingFilter:!0,floatingFilterComponent:ke,minWidth:170,cellRenderer:Et(s=>{const r=s.value;if(r==null)return e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",width:"100%",height:"100%"},children:"--"});const a=r>=0,l=a?g.green[500]:g.red[500],d=a?kt:Rt;return e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:4,width:"100%",height:"100%",color:l,fontSize:16,lineHeight:1.4,whiteSpace:"nowrap"},children:[e.jsx(d,{style:{fontSize:10}}),Hi(r),"%"]})})}),bt=[{headerName:"Категория",field:"category_name",filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:200,cellRenderer:Et(t=>e.jsx(le,{value:t.value}))},We("Заказы, ₽","orders_rub",{suffix:" ₽"}),He("Δ Заказы ₽, %","orders_rub_change_pc"),We("Заказы, шт","orders_qty"),He("Δ Заказы шт, %","orders_qty_change_pc"),We("Выкупы, ₽","buyouts_rub",{suffix:" ₽"}),He("Δ Выкупы ₽, %","buyouts_rub_change_pc"),We("Выкупы, шт","buyouts_qty"),He("Δ Выкупы шт, %","buyouts_qty_change_pc"),We("Карточек товаров","cards_count"),He("Δ Карточек товаров, %","cards_count_change_pc"),{...We("Карточек с заказами","cards_with_orders_count"),minWidth:140},{...He("Δ Карточек с заказами, %","cards_with_orders_count_change_pc"),minWidth:160}],qt=bt.map(t=>({field:t.field,headerName:t.headerName})),Ni=t=>Array.from({length:t},(n,s)=>({_id:s}));function Oi({rowData:t,loading:n,onFilterChanged:s,onSortChanged:r,hiddenColumns:a=[]}){const l=i.useRef(zi);!n&&t.length&&(l.current=t.length);const d=i.useMemo(()=>n?Ni(l.current):t,[n,t]),u=i.useMemo(()=>({loading:n}),[n]),c=i.useMemo(()=>a.length?bt.filter(o=>!a.includes(o.field)):bt,[a]),p=i.useCallback(o=>{if(!s)return;const f=o.api.getFilterModel(),y=Wi(f);s(y)},[s]),h=i.useCallback(o=>{if(!r)return;const f=o.api.getColumnState().filter(y=>y.sort).map(y=>y.sort==="desc"?`-${y.colId}`:y.colId);r(f.length?f.join(","):null)},[r]);return e.jsx("div",{style:{width:"100%"},children:e.jsx(Se,{domLayout:"autoHeight",rowHeight:Me,headerHeight:$e,floatingFiltersHeight:Mi,rowData:d,columnDefs:c,context:u,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!0,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:Ce,headerComponentParams:{enableSorting:!0,wrapText:!0}},onGridReady:o=>{o.api.sizeColumnsToFit()},onGridSizeChanged:o=>{o.api.sizeColumnsToFit()},onFilterChanged:p,onSortChanged:h,noRowsOverlayComponent:we})})}const{Title:qi}=T,Bi="wbstat/external_analytics_category",Gi=[{label:"Неделя",value:"week"},{label:"Месяц",value:"month"},{label:"Квартал",value:"quarter"}];function Ui(){const[t,n]=i.useState([]),[s,r]=i.useState(!0),[a,l]=i.useState({}),[d,u]=i.useState(null),[c,p]=i.useState("month"),{showRequestError:h}=W(),o=In("category_analysis_columns",qt),f=i.useCallback(m=>{r(!0),ie(`${Bi}/`,{params:m}).then(v=>{n(v.data.results)}).catch(v=>{h(v)}).finally(()=>{r(!1)})},[h]);i.useEffect(()=>{const m={...a,period:c,page_size:100};d&&(m.ordering=d),f(m)},[a,d,c]);const y=i.useCallback(m=>{l(m)},[]),j=i.useCallback(m=>{u(m)},[]);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(qi,{level:3,style:{margin:0},children:"Анализ категорий"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap",justifyContent:"space-between"},children:[e.jsx(ce.Group,{options:Gi,value:c,onChange:m=>p(m.target.value),optionType:"button",buttonStyle:"solid"}),e.jsx(En,{onClick:o.openModal})]}),e.jsx(Dn,{columns:qt,hiddenColumns:o.hiddenColumns,open:o.open,onClose:o.closeModal,onToggle:o.toggleColumn}),e.jsx(Oi,{rowData:t,loading:s,onFilterChanged:y,onSortChanged:j,hiddenColumns:o.hiddenColumns})]})}function at(t,n,s,r,a){if(n===s)return;let l;if(r==="log"){const u=Math.log1p(n),c=Math.log1p(s);l=(Math.log1p(t)-u)/(c-u)}else if(r==="quantile"){if(!a||a.length<2)return;let u=0,c=a.length-1;for(;u>1;a[p]n.date_from.slice(0,7))}function $n(t){const[n,s]=t.split("-"),a=new Date(Number(n),Number(s)-1,1).toLocaleDateString("ru-RU",{month:"long",year:"numeric"});return a.charAt(0).toUpperCase()+a.slice(1)}function Mn(t,n){let s=1/0,r=-1/0;for(const a of t)for(const l of n){const d=a[l];d!=null&&isFinite(d)&&(dr&&(r=d))}return isFinite(s)?{min:s,max:r}:{min:0,max:0}}function zn(t,n){const s=[];for(const r of t)for(const a of n){const l=r[a];l!=null&&isFinite(l)&&s.push(l)}return s.sort((r,a)=>r-a),s}function Pn(t,n){let s=1/0;for(const r of n){const a=t[r];a!=null&&isFinite(a)&&a>0&&aArray.from({length:t},(n,s)=>({_id:s}));Ie.setLicenseKey("key");De.registerModules([Ee]);const Vi=10,Ki=()=>e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",width:"100%",height:"100%"},children:e.jsx(G.Input,{active:!0,size:"small",block:!0,style:{height:20,minWidth:0}})}),Bt=t=>n=>{var s;return(s=n.context)!=null&&s.loading?e.jsx(Ki,{}):t(n)};function Zi(t){return!t||!t.length?[]:t.map(n=>{const s={category_name:n.category_name};return n.values&&n.values.forEach(r=>{const a=r.date_from.slice(0,7);s[a]=r.value}),s})}const Yi={category_name:{text:"category"}};function Qi(t){const n={};for(const[s,r]of Object.entries(t)){const a=Yi[s];a&&"text"in a&&r.filter&&(n[a.text]=r.filter)}return n}function Xi({rowData:t,loading:n,onFilterChanged:s,onSortChanged:r}){const a=i.useRef(null),l=i.useRef(Vi),[d,u]=i.useState("linear"),c=i.useMemo(()=>Ln(t),[t]),p=i.useMemo(()=>Zi(t),[t]),{min:h,max:o}=i.useMemo(()=>Mn(p,c),[p,c]),f=i.useMemo(()=>zn(p,c),[p,c]);!n&&p.length&&(l.current=p.length);const y=i.useMemo(()=>n?Wn(l.current):p,[n,p]),j=i.useMemo(()=>({loading:n}),[n]),m=i.useMemo(()=>{const w=[{headerName:"Категория",field:"category_name",filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:200,pinned:"left",cellRenderer:Bt(C=>e.jsx(le,{value:C.value}))}];return c.forEach(C=>{w.push({headerName:$n(C),field:C,filter:"agNumberColumnFilter",minWidth:140,cellRenderer:Bt(S=>e.jsx(q,{value:S.value})),cellStyle:S=>{if(S.value==null||!isFinite(S.value))return;let F;if(d==="dynamics"){const D=Pn(S.data,c);F=at(S.value,D,D*3,"linear")}else F=at(S.value,h,o,d,f);return F?{backgroundColor:F}:void 0}})}),w},[c,h,o,d,f]),v=i.useCallback(w=>{if(!s)return;const C=w.api.getFilterModel(),S=Qi(C);s(S)},[s]),R=i.useCallback(w=>{if(!r)return;const C=w.api.getColumnState().filter(S=>S.sort).map(S=>S.sort==="desc"?`-${S.colId}`:S.colId);r(C.length?C.join(","):null)},[r]),b=i.useCallback(()=>{var w;(w=a.current)!=null&&w.api&&a.current.api.exportDataAsCsv()},[]);return e.jsxs("div",{style:{width:"100%",height:"calc(100vh - 200px)",display:"flex",flexDirection:"column"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:12,marginBottom:8},children:[e.jsx(ce.Group,{options:An,value:d,onChange:w=>u(w.target.value),optionType:"button",size:"small"}),e.jsx(L,{icon:e.jsx(ct,{}),onClick:b,children:"Скачать"})]}),e.jsx(Se,{ref:a,rowHeight:Me,headerHeight:$e,rowData:y,columnDefs:m,context:j,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!0,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:Ce,headerComponentParams:{enableSorting:!0,wrapText:!0}},onGridReady:()=>{},onGridSizeChanged:()=>{},onFilterChanged:v,onSortChanged:R,noRowsOverlayComponent:we})]})}const{Title:Ji}=T,ea="wbstat/category_matrix",ta=[{label:"Заказы, ₽",value:"orders_rub"},{label:"Заказы, шт",value:"orders_qty"},{label:"Выкупы, ₽",value:"buyouts_rub"},{label:"Выкупы, шт",value:"buyouts_qty"},{label:"Карточек товаров",value:"cards_count"},{label:"Карточек с заказами",value:"cards_with_orders_count"}];function na(){const[t,n]=i.useState([]),[s,r]=i.useState(!0),[a,l]=i.useState({}),[d,u]=i.useState(null),[c,p]=i.useState("orders_qty"),[h,o]=i.useState(null),[f,y]=i.useState(null),{showRequestError:j}=W(),m=i.useCallback(b=>{r(!0),ie(`${ea}/`,{params:b}).then(w=>{n(w.data.results)}).catch(w=>{j(w)}).finally(()=>{r(!1)})},[j]);i.useEffect(()=>{const b={...a,indicator:c,page_size:100};d&&(b.ordering=d),h!=null&&(b.value_min=h),f!=null&&(b.value_max=f),m(b)},[a,d,c,h,f]);const v=i.useCallback(b=>{l(b)},[]),R=i.useCallback(b=>{u(b)},[]);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(Ji,{level:3,style:{margin:0},children:"Матрица категорий"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[e.jsx(ae,{options:ta,value:c,onChange:p,style:{width:260}}),e.jsx(Qe,{placeholder:"От",value:h,onChange:o,style:{width:140}}),e.jsx(Qe,{placeholder:"До",value:f,onChange:y,style:{width:140}})]}),e.jsx(Xi,{rowData:t,loading:s,onFilterChanged:v,onSortChanged:R})]})}Ie.setLicenseKey("key");De.registerModules([Ee]);const sa=10,ra=()=>e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",width:"100%",height:"100%"},children:e.jsx(G.Input,{active:!0,size:"small",block:!0,style:{height:20,minWidth:0}})}),mt=t=>n=>{var s;return(s=n.context)!=null&&s.loading?e.jsx(ra,{}):t(n)};function ia(t){return!t||!t.length?[]:t.map(n=>{const s={category_name:n.category_name,subject_name:n.subject_name};return n.values&&n.values.forEach(r=>{const a=r.date_from.slice(0,7);s[a]=r.value}),s})}const aa={category_name:{text:"category"},subject_name:{text:"subject_name"}};function la(t){const n={};for(const[s,r]of Object.entries(t)){const a=aa[s];a&&"text"in a&&r.filter&&(n[a.text]=r.filter)}return n}function oa({rowData:t,loading:n,onFilterChanged:s,onSortChanged:r}){const a=i.useRef(null),l=i.useRef(sa),[d,u]=i.useState("linear"),c=i.useMemo(()=>Ln(t),[t]),p=i.useMemo(()=>ia(t),[t]),{min:h,max:o}=i.useMemo(()=>Mn(p,c),[p,c]),f=i.useMemo(()=>zn(p,c),[p,c]);!n&&p.length&&(l.current=p.length);const y=i.useMemo(()=>n?Wn(l.current):p,[n,p]),j=i.useMemo(()=>({loading:n}),[n]),m=i.useMemo(()=>{const w=[{headerName:"Категория",field:"category_name",filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:200,pinned:"left",cellRenderer:mt(C=>e.jsx(le,{value:C.value}))},{headerName:"Предмет",field:"subject_name",filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:180,pinned:"left",cellRenderer:mt(C=>e.jsx(le,{value:C.value}))}];return c.forEach(C=>{w.push({headerName:$n(C),field:C,filter:"agNumberColumnFilter",minWidth:140,cellRenderer:mt(S=>e.jsx(q,{value:S.value})),cellStyle:S=>{if(S.value==null||!isFinite(S.value))return;let F;if(d==="dynamics"){const D=Pn(S.data,c);F=at(S.value,D,D*3,"linear")}else F=at(S.value,h,o,d,f);return F?{backgroundColor:F}:void 0}})}),w},[c,h,o,d,f]),v=i.useCallback(w=>{if(!s)return;const C=w.api.getFilterModel(),S=la(C);s(S)},[s]),R=i.useCallback(w=>{if(!r)return;const C=w.api.getColumnState().filter(S=>S.sort).map(S=>S.sort==="desc"?`-${S.colId}`:S.colId);r(C.length?C.join(","):null)},[r]),b=i.useCallback(()=>{var w;(w=a.current)!=null&&w.api&&a.current.api.exportDataAsCsv()},[]);return e.jsxs("div",{style:{width:"100%",height:"calc(100vh - 200px)",display:"flex",flexDirection:"column"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:12,marginBottom:8},children:[e.jsx(ce.Group,{options:An,value:d,onChange:w=>u(w.target.value),optionType:"button",size:"small"}),e.jsx(L,{icon:e.jsx(ct,{}),onClick:b,children:"Скачать"})]}),e.jsx(Se,{ref:a,rowHeight:Me,headerHeight:$e,rowData:y,columnDefs:m,context:j,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!0,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:Ce,headerComponentParams:{enableSorting:!0,wrapText:!0}},onGridReady:()=>{},onGridSizeChanged:()=>{},onFilterChanged:v,onSortChanged:R,noRowsOverlayComponent:we})]})}const{Title:ca}=T,da="wbstat/subject_matrix",ua=[{label:"Заказы, шт",value:"orders_qty"},{label:"Заказы, ₽",value:"orders_rub"},{label:"Выкупы, шт",value:"buyouts_qty"},{label:"Выкупы, ₽",value:"buyouts_rub"},{label:"Выручка",value:"revenue"},{label:"Средний чек",value:"avg_check"},{label:"Карточек товаров",value:"cards_count"},{label:"Карточек с заказами",value:"cards_with_orders_count"},{label:"Продавцы",value:"suppliers"},{label:"Продавцы с продажами",value:"suppliers_with_sells"},{label:"Монополизация, %",value:"monopolization_pc"},{label:"Оборачиваемость, дн",value:"weekly_turnover_days"},{label:"Остатки",value:"remaining_count"},{label:"% выкупа",value:"redemption_pc"},{label:"Средний рейтинг",value:"avg_rating"},{label:"Наличие",value:"availability"}];function pa(){const[t,n]=i.useState([]),[s,r]=i.useState(!0),[a,l]=i.useState({}),[d,u]=i.useState(null),[c,p]=i.useState("orders_qty"),[h,o]=i.useState(null),[f,y]=i.useState(null),{showRequestError:j}=W(),m=i.useCallback(b=>{r(!0),ie(`${da}/`,{params:b}).then(w=>{n(w.data.results)}).catch(w=>{j(w)}).finally(()=>{r(!1)})},[j]);i.useEffect(()=>{const b={...a,indicator:c,page_size:100};d&&(b.ordering=d),h!=null&&(b.value_min=h),f!=null&&(b.value_max=f),m(b)},[a,d,c,h,f]);const v=i.useCallback(b=>{l(b)},[]),R=i.useCallback(b=>{u(b)},[]);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(ca,{level:3,style:{margin:0},children:"Матрица предметов"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[e.jsx(ae,{options:ua,value:c,onChange:p,style:{width:260}}),e.jsx(Qe,{placeholder:"От",value:h,onChange:o,style:{width:140}}),e.jsx(Qe,{placeholder:"До",value:f,onChange:y,style:{width:140}})]}),e.jsx(oa,{rowData:t,loading:s,onFilterChanged:v,onSortChanged:R})]})}Ie.setLicenseKey("key");De.registerModules([Ee]);const ha=64,fa=10,xa=()=>e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",width:"100%",height:"100%"},children:e.jsx(G.Input,{active:!0,size:"small",block:!0,style:{height:20,minWidth:0}})}),ft=t=>n=>{var s;return(s=n.context)!=null&&s.loading?e.jsx(xa,{}):t(n)},ga={text:{text:"text"},subject:{text:"subject"},count:{min:"count_min",max:"count_max"},prev_count:{min:"prev_count_min",max:"prev_count_max"},views:{min:"views_min",max:"views_max"},added:{min:"added_min",max:"added_max"},added_conv:{min:"added_conv_min",max:"added_conv_max"},orders:{min:"orders_min",max:"orders_max"},orders_conv:{min:"orders_conv_min",max:"orders_conv_max"},subjects:{min:"subjects_min",max:"subjects_max"}};function ma(t){const n={};for(const[s,r]of Object.entries(t)){const a=ga[s];a&&("text"in a?r.filter&&(n[a.text]=r.filter):r.type==="inRange"?(r.filter!=null&&(n[a.min]=String(r.filter)),r.filterTo!=null&&(n[a.max]=String(r.filterTo))):r.type==="greaterThanOrEqual"?r.filter!=null&&(n[a.min]=String(r.filter)):r.type==="lessThanOrEqual"&&r.filter!=null&&(n[a.max]=String(r.filter)))}return n}const ya=(t,n,s={})=>({headerName:t,field:n,filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:200,cellRenderer:ft(r=>e.jsx(le,{value:r.value})),...s}),Ne=(t,n,s={})=>({headerName:t,field:n,filter:"agNumberColumnFilter",floatingFilter:!0,floatingFilterComponent:ke,minWidth:130,cellRenderer:ft(r=>e.jsx(q,{value:r.value,...s}))}),Gt=(t,n)=>({headerName:t,field:n,filter:"agNumberColumnFilter",floatingFilter:!0,floatingFilterComponent:ke,minWidth:130,cellRenderer:ft(s=>s.value==null?null:e.jsx(q,{value:s.value,suffix:"%"}))}),ja=[{headerName:"Запрос",field:"text",filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:250,cellRenderer:ft(t=>e.jsx(le,{value:t.value,routerLink:`/search-queries/${encodeURIComponent(t.value)}`}))},Ne("Частота","count"),Ne("Пред. частота","prev_count"),ya("Предмет","subject",{minWidth:160}),Ne("Просмотры","views"),Ne("В корзину","added"),Gt("В корзину, %","added_conv"),Ne("Заказы","orders"),Gt("Заказы, %","orders_conv"),Ne("Предметов","subjects")],va=t=>Array.from({length:t},(n,s)=>({_id:s}));function _a({rowData:t,loading:n,onFilterChanged:s,onSortChanged:r}){const a=i.useRef(fa);!n&&t.length&&(a.current=t.length);const l=i.useMemo(()=>n?va(a.current):t,[n,t]),d=i.useMemo(()=>({loading:n}),[n]),u=i.useCallback(p=>{if(!s)return;const h=p.api.getFilterModel(),o=ma(h);s(o)},[s]),c=i.useCallback(p=>{if(!r)return;const h=p.api.getColumnState().filter(o=>o.sort).map(o=>o.sort==="desc"?`-${o.colId}`:o.colId);r(h.length?h.join(","):null)},[r]);return e.jsx("div",{style:{width:"100%"},children:e.jsx(Se,{domLayout:"autoHeight",rowHeight:Me,headerHeight:$e,floatingFiltersHeight:ha,rowData:l,columnDefs:ja,context:d,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!0,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:Ce,headerComponentParams:{enableSorting:!0,wrapText:!0}},onGridReady:p=>{p.api.sizeColumnsToFit()},onGridSizeChanged:p=>{p.api.sizeColumnsToFit()},onFilterChanged:u,onSortChanged:c,noRowsOverlayComponent:we})})}const{Title:ba}=T,Sa="wbstat/queries",Ca=[50,100,200],wa=[{label:"День",value:"yesterday"},{label:"Неделя",value:"week"},{label:"Месяц",value:"month"}];function ka(){const[t,n]=i.useState([]),[s,r]=i.useState(!0),[a,l]=i.useState("week"),[d,u]=i.useState({}),[c,p]=i.useState(null),[h,o]=i.useState(1),[f,y]=i.useState(100),[j,m]=i.useState(0),{showRequestError:v}=W(),R=i.useCallback(D=>{r(!0),ie(`${Sa}/`,{params:D}).then(H=>{n(H.data.results),m(H.data.count)}).catch(H=>{v(H)}).finally(()=>{r(!1)})},[v]);i.useEffect(()=>{const D={...d,period:a,page:h,page_size:f};c&&(D.ordering=c),R(D)},[d,a,c,h,f]);const b=i.useCallback(D=>{l(D.target.value),o(1)},[]),w=i.useCallback(D=>{u(D),o(1)},[]),C=i.useCallback(D=>{p(D),o(1)},[]),S=i.useCallback(D=>{o(D)},[]),F=i.useCallback(D=>{y(D),o(1)},[]);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(ba,{level:3,style:{margin:0},children:"Поисковые запросы"}),e.jsx(ce.Group,{options:wa,value:a,onChange:b,optionType:"button",buttonStyle:"solid"}),e.jsx(_a,{rowData:t,loading:s,onFilterChanged:w,onSortChanged:C}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:12},children:[e.jsx(jt,{current:h,total:j,pageSize:f,onChange:S,showSizeChanger:!1,showTotal:D=>`Всего ${D}`}),e.jsx(ae,{value:f,onChange:F,options:Ca.map(D=>({value:D,label:`${D} / стр`})),style:{width:110}})]})]})}const Ut=[{key:"queries_week",name:"Запросы (неделя)",color:g.bluePale[500]},{key:"queries_month",name:"Запросы (месяц)",color:g.green[500]},{key:"items_count",name:"Товаров в выдаче",color:g.cyan[500]},{key:"yesterday_count",name:"Запросов вчера",color:g.red[500]}],Ra=["queries_week","queries_month"];function Ta(t){if(t==null)return"";const n=Math.abs(t);return n>=1e9?(t/1e9).toFixed(1).replace(/\.0$/,"")+" млрд":n>=1e6?(t/1e6).toFixed(1).replace(/\.0$/,"")+" млн":n>=1e3?(t/1e3).toFixed(1).replace(/\.0$/,"")+" тыс":String(t)}function Fa(t){return t?new Date(t).toLocaleDateString("ru-RU",{day:"2-digit",month:"2-digit"}):""}function Ia({data:t}){const[n,s]=i.useState(Ra),r=i.useMemo(()=>[...t].sort((c,p)=>new Date(c.period_start)-new Date(p.period_start)),[t]),a=i.useMemo(()=>r.map(c=>Fa(c.period_start)),[r]),l=i.useCallback((c,p)=>{s(h=>p?[...h,c]:h.filter(o=>o!==c))},[]),d=i.useMemo(()=>Ut.filter(c=>n.includes(c.key)),[n]),u=i.useMemo(()=>{const c=d.map((h,o)=>({type:"log",name:h.name,nameTextStyle:{color:h.color,fontSize:11},position:o%2===0?"left":"right",offset:Math.floor(o/2)*70,axisLine:{show:!0,lineStyle:{color:h.color}},axisLabel:{fontSize:11,color:h.color,formatter:Ta},splitLine:{show:o===0}})),p=d.map((h,o)=>({name:h.name,type:"line",yAxisIndex:o,data:r.map(f=>f[h.key]||null),smooth:!0,symbol:"none",lineStyle:{width:2,color:h.color},itemStyle:{color:h.color}}));return{tooltip:{trigger:"axis",axisPointer:{type:"cross"}},grid:{left:20+Math.floor(d.filter((h,o)=>o%2===0).length/1)*35,right:20+Math.floor(d.filter((h,o)=>o%2!==0).length/1)*35,top:40,bottom:30,containLabel:!0},xAxis:{type:"category",data:a,axisLabel:{fontSize:11}},yAxis:c.length>0?c:[{type:"log"}],series:p}},[d,r,a]);return e.jsxs("div",{style:{background:"#fff",borderRadius:8,padding:16,border:"1px solid #EFF1F5"},children:[e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:12,marginBottom:12},children:Ut.map(c=>e.jsx(lt,{checked:n.includes(c.key),onChange:p=>l(c.key,p.target.checked),style:{color:c.color,fontWeight:500},children:e.jsx("span",{style:{color:c.color},children:c.name})},c.key))}),e.jsx(an,{option:u,style:{height:400},notMerge:!0})]})}Ie.setLicenseKey("key");De.registerModules([Ee]);const Da=10,Ea=()=>e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",width:"100%",height:"100%"},children:e.jsx(G.Input,{active:!0,size:"small",block:!0,style:{height:20,minWidth:0}})}),Ue=t=>n=>{var s;return(s=n.context)!=null&&s.loading?e.jsx(Ea,{}):t(n)};function La(t){return t?new Date(t).toLocaleDateString("ru-RU"):""}const $a=[{headerName:"Период",field:"period_start",minWidth:120,cellRenderer:Ue(t=>e.jsx(le,{value:La(t.value)}))},{headerName:"Запросы (неделя)",field:"queries_week",minWidth:140,cellRenderer:Ue(t=>e.jsx(q,{value:t.value}))},{headerName:"Запросы (месяц)",field:"queries_month",minWidth:140,cellRenderer:Ue(t=>e.jsx(q,{value:t.value}))},{headerName:"Товаров в выдаче",field:"items_count",minWidth:140,cellRenderer:Ue(t=>e.jsx(q,{value:t.value}))},{headerName:"Запросов вчера",field:"yesterday_count",minWidth:140,cellRenderer:Ue(t=>e.jsx(q,{value:t.value}))}],Ma=t=>Array.from({length:t},(n,s)=>({_id:s}));function za({rowData:t,loading:n}){const s=i.useRef(Da);!n&&t.length&&(s.current=t.length);const r=i.useMemo(()=>n?Ma(s.current):t,[n,t]),a=i.useMemo(()=>({loading:n}),[n]);return e.jsx("div",{style:{width:"100%"},children:e.jsx(Se,{domLayout:"autoHeight",rowHeight:Me,headerHeight:$e,rowData:r,columnDefs:$a,context:a,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!1,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:Ce},onGridReady:l=>{l.api.sizeColumnsToFit()},onGridSizeChanged:l=>{l.api.sizeColumnsToFit()},noRowsOverlayComponent:we})})}const{Title:Pa}=T,Aa="wbstat/phrase_analysis",Wa=[{label:"День",value:"day"},{label:"Неделя",value:"week"},{label:"Месяц",value:"month"}];async function Ha(t,n){let s=1,r=[],a=null;for(;;){const l=await ie(`${Aa}/`,{params:{query:t,period:n,page:s,page_size:20}}),{results:d,next:u,cluster_summary:c}=l.data;if(r=r.concat(d),c&&(a=c),!u)break;s++}return{results:r,clusterSummary:a}}function Na(){var o,f;const{query:t}=ln(),[n,s]=i.useState([]),[r,a]=i.useState(null),[l,d]=i.useState(!0),[u,c]=i.useState("week"),{showRequestError:p}=W(),h=i.useCallback(()=>{d(!0),Ha(t,u).then(({results:y,clusterSummary:j})=>{s(y),a(j)}).catch(y=>p(y)).finally(()=>d(!1))},[t,u]);return i.useEffect(()=>{h()},[h]),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[e.jsx(J,{to:"/search-queries",children:e.jsx(on,{style:{fontSize:20,color:"#383540"}})}),e.jsx(Pa,{level:3,style:{margin:0},children:l&&!n.length?e.jsx(Be,{size:"small"}):`Анализ фразы: ${t}`})]}),e.jsx(ce.Group,{options:Wa,value:u,onChange:y=>c(y.target.value),optionType:"button",buttonStyle:"solid"}),r&&!l&&e.jsx("div",{style:{background:"#fff",borderRadius:8,padding:16,border:"1px solid #EFF1F5"},children:e.jsxs(Pe,{title:"Кластер",size:"small",column:{xs:1,sm:2,md:3},children:[e.jsx(Pe.Item,{label:"Фраза",children:r.text}),e.jsx(Pe.Item,{label:"Норм. фраза",children:r.norm_text}),e.jsx(Pe.Item,{label:"Запросы (неделя)",children:(o=r.cluster_week_count)==null?void 0:o.toLocaleString("ru-RU")}),e.jsx(Pe.Item,{label:"Запросы (месяц)",children:(f=r.cluster_month_count)==null?void 0:f.toLocaleString("ru-RU")}),e.jsx(Pe.Item,{label:"Обновлено",children:r.updated_at})]})}),!l&&n.length>0&&e.jsx(Ia,{data:n}),e.jsx(za,{rowData:n,loading:l})]})}function Oa(){const t=Xe(),{getProfile:n}=pe(),{showRequestError:s}=W();return i.useEffect(()=>{qe.handleCallback().then(()=>{const r=qe.accessToken;return B("user/wb-login",{access_token:r})}).then(r=>{var a;((a=r.data)==null?void 0:a.is_new)===!0&&ym(107086743,"reachGoal","ym-register")}).then(()=>n()).then(()=>{const r=sessionStorage.getItem("wb_key");if(r)return sessionStorage.removeItem("wb_key"),B("user/key-check",{key:r}).then(()=>n()).catch(()=>{})}).then(()=>{const r=localStorage.getItem("auth_redirect");r?(localStorage.removeItem("auth_redirect"),t(r,{replace:!0})):t("/profile")}).catch(r=>{console.error("WB ID callback error:",r),s(r),t("/auth/login")})},[]),e.jsx(Le,{})}const qa=()=>{const[t]=Ft();return i.useEffect(()=>{const n=t.get("key");n&&sessionStorage.setItem("wb_key",n),qe.login()},[]),e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",minHeight:"calc(100vh - 200px)"},children:e.jsx(Be,{size:"large"})})};function Ba(t){return t?new Date(t).toLocaleDateString("ru-RU",{day:"numeric",month:"short",year:"numeric"}):""}function Ga(t){return!!(t!=null&&t.official_response)}function Vt({wishId:t,open:n,onVote:s,onLoad:r,variant:a="sidebar"}){const[l,d]=i.useState(null),[u,c]=i.useState(!1),{showRequestError:p}=W(),{resolution:h}=i.useContext(ht);i.useEffect(()=>{n&&t?(c(!0),N(`wishes/${t}`).then(R=>{d(R.data),r==null||r(R.data)}).catch(R=>{p(R)}).finally(()=>{c(!1)})):n||d(null)},[n,t]);const o=()=>{l!=null&&l.has_voted||s(t).then(R=>{R!=null&&R.has_voted&&d(b=>b&&{...b,votes_count:R.votes_count,has_voted:!0})}).catch(()=>{})},f=l?Ba(l.created_at):"",y=l?l.votes_count>0||l.has_voted:!1,j=a==="sheet",m=a==="sidebar"&&h>_e.Tablet;if(!n)return null;const v={display:"flex",flexDirection:"column",gap:16,...j?{}:m?{maxHeight:"calc(100vh - 96px)",overflowY:"auto",position:"sticky",top:72}:{}};return e.jsx("div",{style:v,children:u?e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",minHeight:220},children:e.jsx(Be,{})}):l?e.jsxs(e.Fragment,{children:[e.jsx("h2",{style:{fontSize:j?24:28,fontWeight:400,lineHeight:1.2,margin:0},children:l.title}),e.jsx(ee,{color:g.greyF[700],style:{margin:0,borderRadius:4,alignSelf:"flex-start"},children:l.status}),e.jsx(me,{style:{margin:0}}),e.jsx("p",{style:{fontSize:14,lineHeight:1.45,margin:0,color:g.dark[500]},children:l.description}),e.jsxs("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8,color:g.dark[500]},children:[e.jsx(L,{size:"small",icon:e.jsx(cn,{}),disabled:l.has_voted,onClick:o,style:{background:l.has_voted?g.primary[50]:g.greyF[100],borderColor:l.has_voted?g.primary[500]:"transparent",color:l.has_voted?g.dark[500]:g.greyF[700]},children:y?l.votes_count:null}),Ga(l)?e.jsxs(e.Fragment,{children:[e.jsx(me,{type:"vertical",style:{margin:0}}),e.jsxs("span",{style:{alignItems:"center",color:g.dark[500],display:"inline-flex",fontSize:14,gap:4,lineHeight:1.2},children:[e.jsx(dn,{style:{fontSize:14,color:g.greyF[700]}}),"Есть ответ"]})]}):null,e.jsx(me,{type:"vertical",style:{margin:0}}),e.jsx("span",{style:{fontSize:14,lineHeight:1.2},children:f})]}),l.official_response&&e.jsxs("div",{style:{borderLeft:`2px solid ${g.primary[500]}`,display:"flex",flexDirection:"column",gap:12,paddingLeft:12},children:[e.jsx("p",{style:{fontSize:14,fontWeight:500,lineHeight:1.2,margin:0},children:"Официальный ответ"}),e.jsx("p",{style:{fontSize:14,lineHeight:1.45,margin:0,color:g.dark[500]},children:l.official_response})]})]}):null})}const{TextArea:Ua}=U,Va=50,Ka=500;function Kt({onClose:t,onSubmit:n,variant:s="inline"}){const[r,a]=i.useState(""),[l,d]=i.useState(""),[u,c]=i.useState(!1),p=()=>{!r.trim()||!l.trim()||u||(c(!0),n({title:r.trim(),description:l.trim()}).then(()=>{a(""),d(""),t()}).catch(()=>{}).finally(()=>{c(!1)}))},h=()=>{u||(a(""),d(""),t())},o=r.trim().length>0&&l.trim().length>0,f=s==="sheet";return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,...f?{flex:1,minHeight:0}:{}},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsx("span",{style:{fontSize:14,fontWeight:500},children:"Заголовок"}),e.jsx(U,{placeholder:"Кратко опишите идею",value:r,onChange:y=>a(y.target.value),maxLength:Va,showCount:!0,disabled:u})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsx("span",{style:{fontSize:14,fontWeight:500},children:"Описание"}),e.jsx(Ua,{placeholder:"Подробно опишите вашу идею",value:l,onChange:y=>d(y.target.value),maxLength:Ka,showCount:!0,rows:5,disabled:u,style:{resize:"none"}})]})]}),e.jsxs("div",{style:{display:"flex",gap:10,marginTop:f?"auto":4,paddingBottom:f?20:0},children:[e.jsxs(be,{variant:"contained",onClick:p,disabled:!o||u,sx:{flex:f?1:void 0,minWidth:f?void 0:226,height:40,fontSize:14,padding:"0 20px"},children:[e.jsx(un,{}),u?"Отправка...":"Предложить"]}),e.jsx(L,{onClick:h,disabled:u,icon:e.jsx(wt,{}),style:{width:56,height:40},"aria-label":f?"Закрыть форму":"Закрыть форму создания"})]})]})}const{Title:Zt}=T,Yt=[{label:"Все",value:"all"},{label:"Новые",value:"Новое"},{label:"Запланировано",value:"Запланировано"},{label:"Сделано",value:"Сделано"}],Za=[{label:"Все теги",value:"all"},{label:"Новые",value:"Новое"},{label:"Запланировано",value:"Запланировано"},{label:"Сделано",value:"Сделано"}],Qt=[{label:"Больше голосов",value:"most_votes"},{label:"Меньше голосов",value:"least_votes"},{label:"Сначала новые",value:"newest"},{label:"Сначала старые",value:"oldest"}],Ve=20;function Ya(t){return t?new Date(t).toLocaleDateString("ru-RU",{day:"numeric",month:"short",year:"numeric"}):""}function Qa(t){return!!(t!=null&&t.official_response)}function yt(t,n){return n!=null&&n.id?t.map(s=>s.id===n.id?{...s,...n}:s):t}function Xa(){const[t,n]=i.useState([]),[s,r]=i.useState(!0),[a,l]=i.useState("all"),[d,u]=i.useState("most_votes"),[c,p]=i.useState(1),[h,o]=i.useState(0),[f,y]=i.useState(null),[j,m]=i.useState(!1),{showMessage:v,showRequestError:R}=W(),{resolution:b}=i.useContext(ht),w=b<=_e.Tablet,C=i.useRef(new Map),S=i.useRef(new Set),F=x=>(x!=null&&x.id&&C.current.set(x.id,x),x),D=x=>{const _=C.current.get(x.id);return _?{...x,..._}:x};i.useEffect(()=>{let x=!0;r(!0);const _={ordering:d,page:c,limit:Ve};return a!=="all"&&(_.status=a),N("wishes",{params:_}).then(k=>{if(!x)return;const $=k.data.results.map(D);n($),o(k.data.count);const z=$.filter(P=>!P.description&&!S.current.has(P.id));z.length!==0&&(z.forEach(P=>{S.current.add(P.id)}),Promise.allSettled(z.map(P=>N(`wishes/${P.id}`))).then(P=>{if(!x)return;const Z=P.reduce((ge,Re,ze)=>{const Ge=z[ze].id;return S.current.delete(Ge),Re.status==="fulfilled"&&ge.push(F(Re.value.data)),ge},[]);Z.length>0&&n(ge=>Z.reduce((Re,ze)=>yt(Re,ze),ge))}))}).catch(k=>{x&&R(k)}).finally(()=>{x&&r(!1)}),()=>{x=!1}},[a,d,c]),i.useEffect(()=>{if(!f)return;t.some(_=>_.id===f)||y(null)},[f,t]),i.useEffect(()=>{if(w&&(j||f))return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[w,j,f]);const H=x=>{l(x),p(1)},V=x=>{u(x),p(1)},A=x=>{m(!1),y(_=>_===x.id?null:x.id)},I=x=>B("wishes",x).then(()=>{m(!1),v("Идея отправлена на модерацию")}).catch(_=>{throw R(_),_}),O=x=>{const _=t.find(k=>k.id===x);return _!=null&&_.has_voted?Promise.resolve({has_voted:!0,votes_count:_.votes_count}):B(`wishes/${x}/vote`).then(k=>(n($=>$.map(z=>z.id===x?{...z,votes_count:k.data.votes_count,has_voted:!0}:z)),v("Ваш голос учтён!"),{has_voted:!0,votes_count:k.data.votes_count})).catch(k=>{var $,z,P;if((($=k.response)==null?void 0:$.status)===400&&((P=(z=k.response)==null?void 0:z.data)!=null&&P.detail)){if(v(k.response.data.detail),k.response.data.has_voted)return n(Z=>Z.map(ge=>ge.id===x?{...ge,votes_count:k.response.data.votes_count,has_voted:!0}:ge)),{has_voted:!0,votes_count:k.response.data.votes_count}}else R(k);throw k})},Y=!!f&&!j&&!w,ye=b<=_e.Tablet,te=i.useRef(null),[he,M]=i.useState(!1),K=i.useCallback(x=>{if(te.current=x,!x)return;const _=new ResizeObserver(([k])=>{M(k.contentRect.width<600)});return _.observe(x),()=>_.disconnect()},[]),E=Y?{display:"grid",gap:16,gridTemplateColumns:b>=_e.Large?"693px minmax(0, 687px)":b>_e.Tablet?"minmax(0, 1fr) minmax(0, 1fr)":"minmax(0, 1fr)",alignItems:"stretch",padding:"16px 20px 24px",height:"calc(100vh - 112px)"}:{maxWidth:693,padding:"16px 20px 24px"},ne={alignItems:"flex-start",display:"flex",gap:10,justifyContent:"space-between",...b<=_e.Tablet?{flexDirection:"column",alignItems:"stretch"}:{}};return e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{background:"#fff",color:g.dark[500],fontFamily:"'IBM Plex Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",margin:"0 -24px -24px",minHeight:"calc(100vh - 72px)"},children:w?e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{borderBottom:`1px solid ${g.greyF[100]}`,display:"flex",flexDirection:"column",gap:12,padding:"8px 20px 12px"},children:[e.jsx(Zt,{level:3,style:{margin:0},children:"Пожелания"}),e.jsxs("div",{style:{display:"flex",gap:8,width:"100%"},children:[e.jsx(ae,{options:Za,value:a,onChange:H,variant:"filled",style:{flex:"0 0 146px"}}),e.jsx(ae,{options:Qt,value:d,onChange:V,variant:"filled",style:{flex:"1 1 0",minWidth:0}})]})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"12px 20px 108px"},children:[e.jsx(Xt,{loading:s,onVote:O,onWishClick:A,selectedWishId:f,wishes:t}),h>Ve?e.jsx("div",{style:{display:"flex",justifyContent:"center",marginTop:4},children:e.jsx(jt,{current:c,total:h,pageSize:Ve,onChange:p,showSizeChanger:!1})}):null]}),e.jsx(cs,{type:"primary",icon:e.jsx(pn,{style:{fontSize:24}}),onClick:()=>{y(null),m(!0)},"aria-label":"Предложить идею",style:{width:64,height:64}})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{padding:"12px 20px 0"},children:e.jsx(Zt,{level:3,style:{margin:0},children:"Пожелания"})}),e.jsxs("div",{style:E,children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16,minWidth:0,overflowY:"auto"},children:[e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:j?e.jsx(Kt,{onClose:()=>m(!1),onSubmit:I}):e.jsxs(be,{variant:"outlined",onClick:()=>{y(null),m(!0)},sx:{height:36,fontSize:13,padding:"0 16px",alignSelf:"flex-start"},children:[e.jsx(un,{}),"Предложить идею"]})}),e.jsx(me,{style:{margin:0}}),e.jsxs("div",{ref:K,style:ne,children:[he?e.jsx(ae,{options:Yt,value:a,onChange:H,variant:"filled",style:{flex:"0 0 146px"}}):e.jsx(ce.Group,{options:Yt,value:a,onChange:x=>H(x.target.value),optionType:"button",buttonStyle:"solid"}),e.jsx(ae,{options:Qt,value:d,onChange:V,variant:"filled",style:{minWidth:180}})]}),e.jsx(Xt,{loading:s,onVote:O,onWishClick:A,selectedWishId:f,wishes:t}),h>Ve?e.jsx("div",{style:{display:"flex",justifyContent:"center",marginTop:4},children:e.jsx(jt,{current:c,total:h,pageSize:Ve,onChange:p,showSizeChanger:!1})}):null]}),Y?e.jsx("div",{style:{alignSelf:"stretch",minWidth:0,overflowY:"auto",...ye?{borderTop:`1px solid ${g.greyF[100]}`,paddingTop:16}:{borderLeft:`1px solid ${g.greyF[100]}`,paddingLeft:16}},children:e.jsx(Vt,{wishId:f,open:Y,onLoad:x=>{F(x),n(_=>yt(_,x))},onVote:O,variant:"sidebar"})}):null]})]})}),e.jsxs("div",{style:{position:"fixed",inset:0,zIndex:1e3,pointerEvents:"none"},children:[e.jsx(Lt,{open:w&&j,onClose:()=>m(!1),placement:"bottom",height:"75%",closable:!1,getContainer:!1,rootStyle:{pointerEvents:j?"auto":"none"},styles:{wrapper:{borderRadius:"20px 20px 0 0",overflow:"hidden"},body:{padding:"16px 20px 20px",display:"flex",flexDirection:"column",height:"100%"}},children:e.jsx(Kt,{onClose:()=>m(!1),onSubmit:I,variant:"sheet"})}),e.jsx(Lt,{open:w&&!!f,onClose:()=>y(null),placement:"bottom",height:"75%",closable:!1,getContainer:!1,rootStyle:{pointerEvents:f?"auto":"none"},styles:{wrapper:{borderRadius:"20px 20px 0 0",overflow:"hidden"},body:{padding:"16px 20px 20px"}},children:e.jsx(Vt,{wishId:f,open:!!f,onLoad:x=>{F(x),n(_=>yt(_,x))},onVote:O,variant:"sheet"})})]})]})}function Xt({wishes:t,loading:n,selectedWishId:s,onWishClick:r,onVote:a}){return n?e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:Array.from({length:5}).map((l,d)=>e.jsx(G,{active:!0,paragraph:{rows:2}},`wish-skeleton-${d}`))}):t.length===0?e.jsx(xe,{description:"Нет идей для отображения"}):e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:t.map(l=>e.jsx(Ja,{onClick:()=>r(l),onVote:a,selected:l.id===s,wish:l},l.id))})}function Ja({wish:t,selected:n,onClick:s,onVote:r}){const a=Ya(t.created_at),l=t.votes_count>0||t.has_voted,d=Qa(t);return e.jsxs(ds,{hoverable:!0,role:"button",tabIndex:0,onClick:s,onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),s())},style:{borderColor:n?g.bluePale[500]:void 0,boxShadow:n?"0 8px 20px rgba(0, 123, 251, 0.08)":void 0},styles:{body:{padding:8,display:"flex",flexDirection:"column",gap:12}},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8,minWidth:0},children:[e.jsx("h3",{style:{flex:"1 1 220px",fontSize:16,fontWeight:500,lineHeight:1.2,margin:0,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.title}),e.jsx(ee,{color:g.greyF[700],style:{margin:0,borderRadius:4},children:t.status})]}),e.jsx("p",{style:{color:g.dark[500],display:"-webkit-box",fontSize:14,lineHeight:1.2,margin:0,overflow:"hidden",WebkitBoxOrient:"vertical",WebkitLineClamp:1},children:t.description}),e.jsxs("div",{style:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:8,color:g.greyF[700]},children:[e.jsx(L,{size:"small",icon:e.jsx(cn,{}),disabled:t.has_voted,onClick:u=>{u.stopPropagation(),r(t.id)},style:{background:t.has_voted?g.primary[50]:g.greyF[100],borderColor:t.has_voted?g.primary[500]:"transparent",color:t.has_voted?g.dark[500]:g.greyF[700]},children:l?t.votes_count:null}),d?e.jsxs(e.Fragment,{children:[e.jsx(me,{type:"vertical",style:{margin:0}}),e.jsxs("span",{style:{alignItems:"center",color:g.dark[500],display:"inline-flex",fontSize:14,gap:4,lineHeight:1.2},children:[e.jsx(dn,{style:{fontSize:14,color:g.greyF[700]}}),"Есть ответ"]})]}):null,e.jsx(me,{type:"vertical",style:{margin:0}}),e.jsx("span",{style:{fontSize:14,lineHeight:1.2},children:a})]})]})}const Jt=new Audio("/sounds/notification.mp3");function Hn(){const t=i.useRef(document.title),[n,s]=i.useState(0),r=i.useRef(document.hidden);return i.useEffect(()=>{const l=()=>{r.current=document.hidden,document.hidden||s(0)};return document.addEventListener("visibilitychange",l),()=>document.removeEventListener("visibilitychange",l)},[]),i.useEffect(()=>{const l=t.current;document.title=n>0?`(${n}) ${l}`:l},[n]),i.useEffect(()=>{const l=t.current;return()=>{document.title=l}},[]),{notifyIncoming:i.useCallback(()=>{Jt.currentTime=0,Jt.play().catch(()=>{}),r.current&&s(l=>l+1)},[])}}const{Title:Nn,Text:Q}=T,{TextArea:On}=U,el=30,tl=50,nl=[{label:"Активные",value:"open"},{label:"Непрочитанные",value:"unread"},{label:"Все",value:"all"},{label:"Архив",value:"archived"}];function qn(t){if(!t)return"";const n=new Date(t),s=new Date;return n.toDateString()===s.toDateString()?n.toLocaleTimeString("ru-RU",{hour:"2-digit",minute:"2-digit"}):n.toLocaleDateString("ru-RU",{day:"numeric",month:"short"})}function Bn(t){return t==="open"?e.jsx(ee,{color:"green",style:{margin:0},children:"Открыт"}):e.jsx(ee,{color:"default",style:{margin:0},children:"Закрыт"})}function sl(t){const n={page:1,limit:el};return t==="open"?n.status="open":t==="unread"?n.only_unread=!0:t==="archived"&&(n.archived=!0),n}function rl({chat:t,selected:n,onClick:s}){var l;const r=((l=t.last_message)==null?void 0:l.text)||"",a=r.length>60?r.slice(0,60)+"…":r;return e.jsxs("div",{role:"button",tabIndex:0,onClick:s,onKeyDown:d=>(d.key==="Enter"||d.key===" ")&&s(),style:{padding:"10px 12px",borderRadius:6,cursor:"pointer",background:n?g.primary[50]:"transparent",borderLeft:n?`3px solid ${g.primary[500]}`:"3px solid transparent",transition:"background 0.15s"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:2},children:[t.has_unread&&e.jsx(st,{dot:!0,style:{marginTop:2}}),e.jsx(Q,{strong:!0,style:{flex:1,fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:t.has_unread?700:500},children:t.subject}),e.jsx(Q,{style:{fontSize:11,color:g.greyF[600],flexShrink:0},children:qn(t.updated_at)})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[t.category&&e.jsx(ee,{style:{margin:0,fontSize:11},children:t.category.name}),Bn(t.status),t.unread_count>0&&e.jsx(st,{count:t.unread_count,size:"small",style:{marginLeft:"auto"}})]}),a?e.jsx(Q,{style:{fontSize:12,color:g.greyF[700],display:"block",marginTop:4},children:a}):null,t.assigned_to&&e.jsxs(Q,{style:{fontSize:11,color:g.greyF[600],display:"block",marginTop:2},children:["Поддержка: ",t.assigned_to.first_name||t.assigned_to.email]})]})}function il({read:t}){const n=t?"rgba(255,255,255,0.95)":"rgba(255,255,255,0.55)";return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",color:n,flexShrink:0},children:[e.jsx("span",{style:{fontSize:11,lineHeight:1},children:"✓"}),t&&e.jsx("span",{style:{fontSize:11,lineHeight:1,marginLeft:-4},children:"✓"})]})}function al({msg:t,read:n}){var r;if(t.kind==="system")return e.jsx("div",{style:{textAlign:"center",margin:"8px 0"},children:e.jsx(Q,{style:{fontSize:12,color:g.greyF[600],background:g.greyF[100],padding:"3px 10px",borderRadius:12},children:t.text})});const s=t.kind==="user";return e.jsx("div",{style:{display:"flex",justifyContent:s?"flex-end":"flex-start",margin:"4px 0"},children:e.jsxs("div",{style:{maxWidth:"70%",background:s?g.primary[500]:g.greyF[100],color:s?"#fff":g.dark[500],borderRadius:s?"12px 12px 2px 12px":"12px 12px 12px 2px",padding:"8px 12px",fontSize:14},children:[!s&&t.author&&e.jsx(Q,{style:{fontSize:11,color:g.greyF[600],display:"block",marginBottom:2},children:t.author.first_name||t.author.email}),e.jsx("div",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:t.text}),((r=t.attachments)==null?void 0:r.length)>0&&e.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:3},children:t.attachments.map(a=>e.jsxs("a",{href:a.file_url,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:4,fontSize:12,color:s?"rgba(255,255,255,0.85)":g.bluePale[500]},children:[e.jsx(xn,{}),a.original_name]},a.id))}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:3,marginTop:4},children:[e.jsx(Q,{style:{fontSize:10,color:s?"rgba(255,255,255,0.7)":g.greyF[600]},children:qn(t.created_at)}),s&&e.jsx(il,{read:n})]})]})})}function ll({chatId:t,refreshKey:n,showDividerAfterMsgId:s,onMessagesLoaded:r,lastSupportReadMsgId:a}){const[l,d]=i.useState([]),[u,c]=i.useState(!0),{showRequestError:p}=W(),h=i.useRef(null),o=i.useRef(r),f=i.useRef(!0);if(i.useEffect(()=>{o.current=r},[r]),i.useEffect(()=>{f.current=!0,d([])},[t]),i.useEffect(()=>{if(!t)return;let m=!0;return f.current&&(c(!0),f.current=!1),N(`helpdesk/chats/${t}/messages`,{params:{limit:tl}}).then(v=>{var C;if(!m)return;const b=[...v.data.results??v.data].reverse();d(b);const w=b.reduce((S,F)=>F.id>S?F.id:S,0);(C=o.current)==null||C.call(o,w)}).catch(v=>m&&p(v)).finally(()=>m&&c(!1)),()=>{m=!1}},[t,n]),i.useEffect(()=>{var m;(m=h.current)==null||m.scrollIntoView({behavior:"instant"})},[l]),u)return e.jsx("div",{style:{padding:16,display:"flex",flexDirection:"column",gap:8},children:Array.from({length:4}).map((m,v)=>e.jsx(G,{active:!0,paragraph:{rows:1}},v))});if(l.length===0)return e.jsx(xe,{description:"Нет сообщений",style:{marginTop:40}});const y=l.filter(m=>m.kind!=="user").reduce((m,v)=>v.id>m?v.id:m,0),j=[];return l.forEach(m=>{const v=m.kind==="user"&&(a>0?m.id<=a:y>0&&m.id{if(!r.trim()&&l.length===0)return;c(!0),s==null||s();let o;if(l.length>0){const f=new FormData;f.append("text",r.trim()),l.forEach(y=>f.append("attachments",y.originFileObj)),o=B(`helpdesk/chats/${t}/messages`,f,{headers:{"Content-Type":"multipart/form-data"}})}else o=B(`helpdesk/chats/${t}/messages`,{text:r.trim()});o.then(()=>{a(""),d([]),n()}).catch(f=>p(f)).finally(()=>c(!1))};return e.jsxs("div",{style:{padding:"10px 16px",borderTop:`1px solid ${g.greyF[100]}`},children:[l.length>0&&e.jsx("div",{style:{marginBottom:6,display:"flex",flexWrap:"wrap",gap:4},children:l.map(o=>e.jsx(ee,{icon:e.jsx(it,{}),closable:!0,onClose:()=>d(f=>f.filter(y=>y.uid!==o.uid)),style:{margin:0},children:o.name},o.uid))}),e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-end"},children:[e.jsx(On,{value:r,onChange:o=>a(o.target.value),placeholder:"Введите сообщение…",autoSize:{minRows:1,maxRows:5},onKeyDown:o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),h())},style:{flex:1,resize:"none"}}),e.jsx(It,{fileList:l,onChange:({fileList:o})=>d(o),beforeUpload:()=>!1,showUploadList:!1,multiple:!0,children:e.jsx(L,{icon:e.jsx(it,{}),type:"text"})}),e.jsx(L,{type:"primary",icon:e.jsx(fn,{}),onClick:h,loading:u,disabled:!r.trim()&&l.length===0})]})]})}function cl({chat:t,onChatUpdated:n,externalMsgTrigger:s,lastSupportReadMsgId:r,onMessageSent:a}){const[l,d]=i.useState(0),[u,c]=i.useState(!1),[p,h]=i.useState(null),o=i.useRef(0),f=i.useRef(!1),y=i.useRef(!1),j=i.useRef(t),m=i.useRef(n);i.useEffect(()=>{j.current=t},[t]),i.useEffect(()=>{m.current=n},[n]);const{showMessage:v,showRequestError:R}=W();i.useEffect(()=>{t&&(h(null),o.current=0,f.current=!1,y.current=!1,B(`helpdesk/chats/${t.id}/mark-read`).then(()=>n()).catch(()=>{}),d(S=>S+1))},[t==null?void 0:t.id]),i.useEffect(()=>{if(s>0){const S=y.current;y.current=!1,!S&&!f.current&&o.current>0&&(h(o.current),f.current=!0),d(D=>D+1);const F=j.current;F&&B(`helpdesk/chats/${F.id}/mark-read`).then(()=>m.current()).catch(()=>{})}},[s]);const b=(S,F)=>{c(!0),B(`helpdesk/chats/${t.id}/${S}`).then(()=>{v(F),n()}).catch(D=>R(D)).finally(()=>c(!1))};if(!t)return e.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",color:g.greyF[600],fontSize:14},children:"Выберите обращение"});const w=t.status==="open",C=t.archived;return e.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[e.jsxs("div",{style:{padding:"12px 16px",borderBottom:`1px solid ${g.greyF[100]}`,display:"flex",gap:8,alignItems:"flex-start",flexWrap:"wrap"},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx(Nn,{level:5,style:{margin:0,fontSize:15},children:t.subject}),e.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginTop:4},children:[t.category&&e.jsx(ee,{children:t.category.name}),Bn(t.status),C&&e.jsx(ee,{color:"orange",children:"Архив"})]})]}),e.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",flexShrink:0},children:[w?e.jsx(L,{size:"small",icon:e.jsx(hn,{}),onClick:()=>b("close","Чат закрыт"),loading:u,children:"Закрыть"}):e.jsx(L,{size:"small",type:"primary",icon:e.jsx(rt,{}),onClick:()=>b("reopen","Чат переоткрыт"),loading:u,children:"Переоткрыть"}),C?e.jsx(L,{size:"small",onClick:()=>b("unarchive","Убрано из архива"),loading:u,children:"Из архива"}):e.jsx(L,{size:"small",onClick:()=>b("archive","Перемещено в архив"),loading:u,children:"В архив"})]})]}),e.jsx("div",{style:{flex:1,overflowY:"auto"},children:e.jsx(ll,{chatId:t.id,refreshKey:l,showDividerAfterMsgId:p,onMessagesLoaded:S=>{o.current=S},lastSupportReadMsgId:r})}),w?e.jsx(ol,{chatId:t.id,onBeforeSend:()=>{a==null||a()},onSent:()=>{y.current=!0,h(null),f.current=!1,d(S=>S+1),n()}}):e.jsxs("div",{style:{padding:"12px 16px",borderTop:`1px solid ${g.greyF[100]}`,textAlign:"center"},children:[e.jsx(Q,{style:{color:g.greyF[600],fontSize:13},children:"Чат закрыт. "}),e.jsx(L,{type:"link",size:"small",icon:e.jsx(rt,{}),onClick:()=>b("reopen","Чат переоткрыт"),loading:u,style:{padding:0},children:"Переоткрыть"})]})]})}function dl({open:t,categories:n,onClose:s,onCreated:r}){const[a,l]=i.useState(""),[d,u]=i.useState(null),[c,p]=i.useState(""),[h,o]=i.useState([]),[f,y]=i.useState(!1),[j,m]=i.useState({}),{showRequestError:v}=W(),R=C=>{j[C]&&m(S=>({...S,[C]:null}))},b=()=>{const C={};if(a.trim()||(C.subject="Укажите тему обращения"),c.trim()||(C.text="Напишите сообщение"),Object.keys(C).length>0){m(C);return}y(!0);const S=new FormData;S.append("subject",a.trim()),d&&S.append("category_id",d),S.append("text",c.trim()),h.forEach(F=>S.append("attachments",F.originFileObj)),B("helpdesk/chats",S,{headers:{"Content-Type":"multipart/form-data"}}).then(F=>{r(F.data),l(""),u(null),p(""),o([]),m({}),s()}).catch(F=>{var H;const D=(H=F.response)==null?void 0:H.data;if(D&&typeof D=="object"&&!D.detail&&!D.error){const V={};for(const[A,I]of Object.entries(D))V[A]=Array.isArray(I)?I[0]:I;m(V)}else v(F)}).finally(()=>y(!1))},w=()=>{m({}),s()};return e.jsx(Fe,{open:t,onCancel:w,title:"Новое обращение",onOk:b,okText:"Создать",cancelText:"Отмена",okButtonProps:{loading:f},width:520,children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12,marginTop:16},children:[e.jsxs("div",{children:[e.jsx(Q,{style:{fontSize:13,marginBottom:4,display:"block"},children:"Тема"}),e.jsx(U,{value:a,onChange:C=>{l(C.target.value),R("subject")},placeholder:"Кратко опишите проблему",status:j.subject?"error":void 0}),j.subject&&e.jsx(Q,{style:{fontSize:12,color:"#ff4d4f",marginTop:2,display:"block"},children:j.subject})]}),n.length>0&&e.jsxs("div",{children:[e.jsx(Q,{style:{fontSize:13,marginBottom:4,display:"block"},children:"Категория"}),e.jsx(ae,{value:d,onChange:C=>{u(C),R("category_id")},placeholder:"Выберите категорию",allowClear:!0,style:{width:"100%"},options:n.map(C=>({value:C.id,label:C.name})),status:j.category_id?"error":void 0}),j.category_id&&e.jsx(Q,{style:{fontSize:12,color:"#ff4d4f",marginTop:2,display:"block"},children:j.category_id})]}),e.jsxs("div",{children:[e.jsx(Q,{style:{fontSize:13,marginBottom:4,display:"block"},children:"Сообщение"}),e.jsx(On,{value:c,onChange:C=>{p(C.target.value),R("text")},placeholder:"Подробно опишите ситуацию",autoSize:{minRows:4,maxRows:8},status:j.text?"error":void 0}),j.text&&e.jsx(Q,{style:{fontSize:12,color:"#ff4d4f",marginTop:2,display:"block"},children:j.text})]}),e.jsxs("div",{children:[e.jsx(Q,{style:{fontSize:13,marginBottom:4,display:"block"},children:"Вложения"}),e.jsxs(It.Dragger,{fileList:h,onChange:({fileList:C})=>o(C),beforeUpload:()=>!1,multiple:!0,style:{padding:"8px 0"},children:[e.jsx("p",{className:"ant-upload-drag-icon",style:{marginBottom:4},children:e.jsx(us,{style:{fontSize:28}})}),e.jsx("p",{style:{fontSize:13,color:g.greyF[600]},children:"Перетащите файлы или нажмите для выбора"})]})]})]})})}function ul(){const{profile:t,addPublicationHandler:n,removePublicationHandler:s}=pe(),{showRequestError:r}=W(),[a,l]=i.useState([]),[d,u]=i.useState(!0),[c,p]=i.useState(null),[h,o]=i.useState("open"),[f,y]=i.useState(""),[j,m]=i.useState(""),[v,R]=i.useState([]),[b,w]=i.useState(!1),[C,S]=i.useState(0),[F,D]=i.useState(0),[H,V]=i.useState(0),{notifyIncoming:A}=Hn(),I=i.useRef(!1),O=i.useRef(c);i.useEffect(()=>{O.current=c},[c]),i.useEffect(()=>{V(0)},[c]);const Y=i.useRef(!0);if(i.useEffect(()=>{Y.current=!0},[h,f]),i.useEffect(()=>{t.auth&&N("helpdesk/categories").then(M=>R(M.data.results??M.data)).catch(()=>{})},[t.auth]),i.useEffect(()=>{if(!t.auth)return;let M=!0;Y.current&&(u(!0),Y.current=!1);const K=sl(h);return f&&(K.search=f),N("helpdesk/chats",{params:K}).then(E=>{M&&l(E.data.results??E.data)}).catch(E=>{M&&r(E)}).finally(()=>{M&&u(!1)}),()=>{M=!1}},[t.auth,h,f,C]),i.useEffect(()=>{c&&a.length>0&&!a.find(M=>M.id===c)&&p(null)},[a]),i.useEffect(()=>{if(!t.auth)return;const M="helpdesk-user-page";return n(M,K=>{const{type:E,chat_id:ne}=K.data??{};if(E){if((E==="chat.created"||E==="chat.updated"||E==="message.created")&&(S(x=>x+1),E==="message.created")){const x=I.current;I.current=!1,x||A(),ne===O.current&&D(_=>_+1)}if(E==="chat.read"&&ne===O.current){const{read_up_to_message_id:x,reader:_}=K.data;_==="support"&&V(x)}}}),()=>s(M)},[t.auth,n,s]),t.auth===void 0)return e.jsx(Le,{});if(t.auth===!1)return e.jsx(pt,{});const ye=a.find(M=>M.id===c)??null,te=()=>y(j),he=()=>S(M=>M+1);return e.jsxs("div",{style:{margin:"0 -24px -24px",minHeight:"calc(100vh - 72px)",background:"#fff",display:"flex",flexDirection:"column"},children:[e.jsxs("div",{style:{padding:"12px 20px",borderBottom:`1px solid ${g.greyF[100]}`,display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[e.jsx(Nn,{level:4,style:{margin:0},children:"Поддержка"}),e.jsx(L,{type:"primary",icon:e.jsx(pn,{}),onClick:()=>w(!0),style:{marginLeft:"auto"},children:"Новое обращение"})]}),e.jsxs("div",{style:{display:"flex",flex:1,minHeight:0},children:[e.jsxs("div",{style:{width:320,flexShrink:0,borderRight:`1px solid ${g.greyF[100]}`,display:"flex",flexDirection:"column",overflow:"hidden"},children:[e.jsxs("div",{style:{padding:"10px 12px",borderBottom:`1px solid ${g.greyF[100]}`},children:[e.jsx(U,{prefix:e.jsx(Ct,{style:{color:g.greyF[600]}}),placeholder:"Поиск по теме и сообщениям",value:j,onChange:M=>m(M.target.value),onPressEnter:te,allowClear:!0,onClear:()=>{m(""),y("")},size:"small",style:{marginBottom:8}}),e.jsx(ce.Group,{options:nl,value:h,onChange:M=>{o(M.target.value),p(null)},optionType:"button",buttonStyle:"solid",size:"small",style:{display:"flex",flexWrap:"wrap",gap:2}})]}),e.jsx("div",{style:{flex:1,overflowY:"auto",padding:"6px 8px"},children:d?e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:8},children:Array.from({length:5}).map((M,K)=>e.jsx(G,{active:!0,paragraph:{rows:2}},K))}):a.length===0?e.jsx(xe,{description:"Нет обращений",style:{marginTop:40}}):a.map(M=>e.jsx(rl,{chat:M,selected:M.id===c,onClick:()=>p(M.id)},M.id))})]}),e.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",minWidth:0,height:"calc(100vh - 140px)"},children:e.jsx(cl,{chat:ye,onChatUpdated:he,externalMsgTrigger:F,lastSupportReadMsgId:H,onMessageSent:()=>{I.current=!0}})})]}),e.jsx(dl,{open:b,categories:v,onClose:()=>w(!1),onCreated:()=>{he(),o("open")}})]})}const{Title:Gn,Text:X}=T,{TextArea:pl}=U,hl=40,fl=50,xl=[{value:"open",label:"Открытые"},{value:"unread",label:"Непрочитанные"},{value:"closed",label:"Закрытые"},{value:"archived",label:"Архив"},{value:"mine",label:"Мои"},{value:"unassigned",label:"Без назначения"},{value:"all",label:"Все"}];function Un(t){if(!t)return"";const n=new Date(t),s=new Date;return n.toDateString()===s.toDateString()?n.toLocaleTimeString("ru-RU",{hour:"2-digit",minute:"2-digit"}):n.toLocaleDateString("ru-RU",{day:"numeric",month:"short"})}function Vn(t){return t==="open"?e.jsx(ee,{color:"green",style:{margin:0},children:"Открыт"}):e.jsx(ee,{color:"default",style:{margin:0},children:"Закрыт"})}function gl(t,n,s){const r={limit:hl};return t==="open"?r.status="open":t==="closed"?r.status="closed":t==="archived"?r.archived=!0:t==="unread"?r.only_unread=!0:t==="mine"?r.assigned="me":t==="unassigned"&&(r.assigned="unassigned"),n&&(r.search=n),s&&(r.category_id=s),r}function ml({chat:t,selected:n,onClick:s}){var d;const r=((d=t.last_message)==null?void 0:d.text)||"",a=r.length>55?r.slice(0,55)+"…":r,l=t.user?t.user.first_name?`${t.user.first_name} ${t.user.last_name||""}`.trim():t.user.email:"—";return e.jsxs("div",{role:"button",tabIndex:0,onClick:s,onKeyDown:u=>(u.key==="Enter"||u.key===" ")&&s(),style:{padding:"10px 12px",borderRadius:6,cursor:"pointer",background:n?g.primary[50]:"transparent",borderLeft:n?`3px solid ${g.primary[500]}`:"3px solid transparent",transition:"background 0.15s",marginBottom:2},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:2},children:[t.has_unread&&e.jsx(st,{dot:!0,style:{marginTop:2}}),e.jsx(nt,{style:{color:g.greyF[600],fontSize:12}}),e.jsx(X,{style:{fontSize:12,color:g.greyF[700],flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l}),e.jsx(X,{style:{fontSize:11,color:g.greyF[600],flexShrink:0},children:Un(t.updated_at)})]}),e.jsx(X,{strong:!0,style:{fontSize:13,display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontWeight:t.has_unread?700:500,marginBottom:3},children:t.subject}),e.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},children:[t.category&&e.jsx(ee,{style:{margin:0,fontSize:11},children:t.category.name}),Vn(t.status),t.archived&&e.jsx(ee,{color:"orange",style:{margin:0,fontSize:11},children:"Архив"}),t.unread_count>0&&e.jsx(st,{count:t.unread_count,size:"small",style:{marginLeft:"auto"}})]}),t.assigned_to?e.jsxs(X,{style:{fontSize:11,color:g.bluePale[500],display:"block",marginTop:3},children:["→ ",t.assigned_to.first_name||t.assigned_to.email]}):e.jsx(X,{style:{fontSize:11,color:g.red[500],display:"block",marginTop:3},children:"Не назначен"}),a?e.jsx(X,{style:{fontSize:12,color:g.greyF[600],display:"block",marginTop:3},children:a}):null]})}function yl({read:t}){const n=t?"rgba(255,255,255,0.9)":"rgba(255,255,255,0.45)";return e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",color:n,flexShrink:0},children:[e.jsx("span",{style:{fontSize:11,lineHeight:1},children:"✓"}),t&&e.jsx("span",{style:{fontSize:11,lineHeight:1,marginLeft:-4},children:"✓"})]})}function jl({msg:t,read:n}){var r,a,l,d,u;if(t.kind==="system")return e.jsx("div",{style:{textAlign:"center",margin:"8px 0"},children:e.jsx(X,{style:{fontSize:12,color:g.greyF[600],background:g.greyF[100],padding:"3px 10px",borderRadius:12},children:t.text})});const s=t.kind==="user";return e.jsx("div",{style:{display:"flex",justifyContent:s?"flex-start":"flex-end",margin:"4px 0"},children:e.jsxs("div",{style:{maxWidth:"70%",background:s?g.greyF[100]:g.bluePale[500],color:s?g.dark[500]:"#fff",borderRadius:s?"12px 12px 12px 2px":"12px 12px 2px 12px",padding:"8px 12px",fontSize:14},children:[e.jsx(X,{style:{fontSize:11,color:s?g.greyF[600]:"rgba(255,255,255,0.7)",display:"block",marginBottom:2},children:s?((r=t.author)==null?void 0:r.first_name)||((a=t.author)==null?void 0:a.email)||"Пользователь":((l=t.author)==null?void 0:l.first_name)||((d=t.author)==null?void 0:d.email)||"Поддержка"}),e.jsx("div",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:t.text}),((u=t.attachments)==null?void 0:u.length)>0&&e.jsx("div",{style:{marginTop:6,display:"flex",flexDirection:"column",gap:3},children:t.attachments.map(c=>e.jsxs("a",{href:c.file_url,target:"_blank",rel:"noopener noreferrer",style:{display:"flex",alignItems:"center",gap:4,fontSize:12,color:s?g.bluePale[500]:"rgba(255,255,255,0.85)"},children:[e.jsx(xn,{}),c.original_name]},c.id))}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:3,marginTop:4},children:[e.jsx(X,{style:{fontSize:10,color:s?g.greyF[600]:"rgba(255,255,255,0.65)"},children:Un(t.created_at)}),!s&&e.jsx(yl,{read:n})]})]})})}function vl({chatId:t,refreshKey:n,showDividerAfterMsgId:s,onMessagesLoaded:r,lastUserReadMsgId:a}){const[l,d]=i.useState([]),[u,c]=i.useState(!0),{showRequestError:p}=W(),h=i.useRef(null),o=i.useRef(r),f=i.useRef(!0);if(i.useEffect(()=>{o.current=r},[r]),i.useEffect(()=>{f.current=!0,d([])},[t]),i.useEffect(()=>{if(!t)return;let m=!0;return f.current&&(c(!0),f.current=!1),N(`helpdesk/support/chats/${t}/messages`,{params:{limit:fl}}).then(v=>{var C;if(!m)return;const b=[...v.data.results??v.data].reverse();d(b);const w=b.reduce((S,F)=>F.id>S?F.id:S,0);(C=o.current)==null||C.call(o,w)}).catch(v=>m&&p(v)).finally(()=>m&&c(!1)),()=>{m=!1}},[t,n]),i.useEffect(()=>{var m;(m=h.current)==null||m.scrollIntoView({behavior:"instant"})},[l]),u)return e.jsx("div",{style:{padding:16,display:"flex",flexDirection:"column",gap:8},children:Array.from({length:4}).map((m,v)=>e.jsx(G,{active:!0,paragraph:{rows:1}},v))});if(l.length===0)return e.jsx(xe,{description:"Нет сообщений",style:{marginTop:40}});const y=l.filter(m=>m.kind==="user").reduce((m,v)=>v.id>m?v.id:m,0),j=[];return l.forEach(m=>{const v=m.kind==="support"&&(a>0?m.id<=a:y>0&&m.id{if(!r.trim()&&l.length===0)return;c(!0),s==null||s();let o;if(l.length>0){const f=new FormData;f.append("text",r.trim()),l.forEach(y=>f.append("attachments",y.originFileObj)),o=B(`helpdesk/support/chats/${t}/messages`,f,{headers:{"Content-Type":"multipart/form-data"}})}else o=B(`helpdesk/support/chats/${t}/messages`,{text:r.trim()});o.then(()=>{a(""),d([]),n()}).catch(f=>p(f)).finally(()=>c(!1))};return e.jsxs("div",{style:{padding:"10px 16px",borderTop:`1px solid ${g.greyF[100]}`},children:[l.length>0&&e.jsx("div",{style:{marginBottom:6,display:"flex",flexWrap:"wrap",gap:4},children:l.map(o=>e.jsx(ee,{icon:e.jsx(it,{}),closable:!0,onClose:()=>d(f=>f.filter(y=>y.uid!==o.uid)),style:{margin:0},children:o.name},o.uid))}),e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-end"},children:[e.jsx(pl,{value:r,onChange:o=>a(o.target.value),placeholder:"Ответ пользователю…",autoSize:{minRows:1,maxRows:5},onKeyDown:o=>{o.key==="Enter"&&!o.shiftKey&&(o.preventDefault(),h())},style:{flex:1,resize:"none"}}),e.jsx(It,{fileList:l,onChange:({fileList:o})=>d(o),beforeUpload:()=>!1,showUploadList:!1,multiple:!0,children:e.jsx(L,{icon:e.jsx(it,{}),type:"text"})}),e.jsx(L,{type:"primary",icon:e.jsx(fn,{}),onClick:h,loading:u,disabled:!r.trim()&&l.length===0})]})]})}function bl({chat:t,onChatUpdated:n,profile:s,externalMsgTrigger:r,lastUserReadMsgId:a,onMessageSent:l}){var H,V;const[d,u]=i.useState(0),[c,p]=i.useState(!1),[h,o]=i.useState(null),f=i.useRef(0),y=i.useRef(!1),j=i.useRef(!1),m=i.useRef(t),v=i.useRef(n);i.useEffect(()=>{m.current=t},[t]),i.useEffect(()=>{v.current=n},[n]);const{showMessage:R,showRequestError:b}=W();i.useEffect(()=>{t&&(o(null),f.current=0,y.current=!1,j.current=!1,B(`helpdesk/support/chats/${t.id}/mark-read`).then(()=>n()).catch(()=>{}),u(A=>A+1))},[t==null?void 0:t.id]),i.useEffect(()=>{if(r>0){const A=j.current;j.current=!1,!A&&!y.current&&f.current>0&&(o(f.current),y.current=!0),u(O=>O+1);const I=m.current;I&&B(`helpdesk/support/chats/${I.id}/mark-read`).then(()=>v.current()).catch(()=>{})}},[r]);const w=(A,I)=>{p(!0),B(`helpdesk/support/chats/${t.id}/${A}`).then(()=>{R(I),n()}).catch(O=>b(O)).finally(()=>p(!1))},C=()=>{p(!0),B(`helpdesk/support/chats/${t.id}/assign`,{assigned_to:s.wb_id}).then(()=>{R("Чат назначен на вас"),n()}).catch(A=>b(A)).finally(()=>p(!1))};if(!t)return e.jsx("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",color:g.greyF[600],fontSize:14},children:"Выберите обращение из списка"});const S=t.status==="open",F=t.archived,D=t.user?t.user.first_name?`${t.user.first_name} ${t.user.last_name||""}`.trim():t.user.email:"—";return e.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[e.jsxs("div",{style:{padding:"12px 16px",borderBottom:`1px solid ${g.greyF[100]}`},children:[e.jsx("div",{style:{display:"flex",alignItems:"flex-start",gap:8,marginBottom:8},children:e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:2},children:[e.jsx(nt,{style:{color:g.greyF[600]}}),e.jsx(X,{style:{fontSize:13,color:g.greyF[700]},children:D}),((H=t.user)==null?void 0:H.email)&&e.jsxs(X,{style:{fontSize:12,color:g.greyF[600]},children:["(",t.user.email,")"]})]}),e.jsx(Gn,{level:5,style:{margin:0,fontSize:15},children:t.subject}),e.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginTop:4},children:[t.category&&e.jsx(ee,{children:t.category.name}),Vn(t.status),F&&e.jsx(ee,{color:"orange",children:"Архив"})]})]})}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 10px",background:t.assigned_to?g.greyF[50]:g.red[100],borderRadius:6,marginBottom:8},children:[e.jsx(X,{style:{fontSize:13,flex:1},children:t.assigned_to?e.jsxs(e.Fragment,{children:["Назначен: ",e.jsx(X,{strong:!0,children:t.assigned_to.first_name||t.assigned_to.email})]}):e.jsx(X,{style:{color:g.red[500]},children:"Не назначен"})}),((V=t.assigned_to)==null?void 0:V.wb_id)!==s.wb_id&&e.jsx(L,{size:"small",icon:e.jsx(nt,{}),onClick:C,loading:c,children:t.assigned_to?"Взять себе":"Назначить на себя"})]}),e.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[S?e.jsx(L,{size:"small",icon:e.jsx(hn,{}),onClick:()=>w("close","Чат закрыт"),loading:c,children:"Закрыть"}):e.jsx(L,{size:"small",type:"primary",icon:e.jsx(rt,{}),onClick:()=>w("reopen","Чат переоткрыт"),loading:c,children:"Переоткрыть"}),F?e.jsx(L,{size:"small",onClick:()=>w("unarchive","Убрано из архива"),loading:c,children:"Из архива"}):e.jsx(L,{size:"small",onClick:()=>w("archive","Перемещено в архив"),loading:c,children:"В архив"})]})]}),e.jsx("div",{style:{flex:1,overflowY:"auto"},children:e.jsx(vl,{chatId:t.id,refreshKey:d,showDividerAfterMsgId:h,onMessagesLoaded:A=>{f.current=A},lastUserReadMsgId:a})}),S?e.jsx(_l,{chatId:t.id,onBeforeSend:()=>{l==null||l()},onSent:()=>{j.current=!0,o(null),y.current=!1,u(A=>A+1),n()}}):e.jsxs("div",{style:{padding:"10px 16px",borderTop:`1px solid ${g.greyF[100]}`,textAlign:"center"},children:[e.jsxs(X,{style:{color:g.greyF[600],fontSize:13},children:["Чат закрыт."," "]}),e.jsx(L,{type:"link",size:"small",icon:e.jsx(rt,{}),onClick:()=>w("reopen","Чат переоткрыт"),loading:c,style:{padding:0},children:"Переоткрыть"})]})]})}function Sl(){var K;const{profile:t,addPublicationHandler:n,removePublicationHandler:s}=pe(),{showRequestError:r}=W(),[a,l]=i.useState([]),[d,u]=i.useState(!0),[c,p]=i.useState(null),[h,o]=i.useState("open"),[f,y]=i.useState(""),[j,m]=i.useState(""),[v,R]=i.useState([]),[b,w]=i.useState(null),[C,S]=i.useState(0),[F,D]=i.useState(0),[H,V]=i.useState(0),{notifyIncoming:A}=Hn(),I=i.useRef(!1),O=i.useRef(c);i.useEffect(()=>{O.current=c},[c]),i.useEffect(()=>{V(0)},[c]);const Y=i.useRef(!0);if(i.useEffect(()=>{Y.current=!0},[h,f,b]),i.useEffect(()=>{t.auth&&N("helpdesk/categories").then(E=>R(E.data.results??E.data)).catch(()=>{})},[t.auth]),i.useEffect(()=>{if(!t.auth)return;let E=!0;Y.current&&(u(!0),Y.current=!1);const ne=gl(h,f,b);return N("helpdesk/support/chats",{params:ne}).then(x=>{E&&l(x.data.results??x.data)}).catch(x=>E&&r(x)).finally(()=>E&&u(!1)),()=>{E=!1}},[t.auth,h,f,b,C]),i.useEffect(()=>{c&&a.length>0&&!a.find(E=>E.id===c)&&p(null)},[a]),i.useEffect(()=>{if(!t.auth)return;const E="helpdesk-support-page";return n(E,ne=>{const{type:x,chat_id:_}=ne.data??{};if(x){if((x==="chat.created"||x==="chat.updated"||x==="message.created")&&(S(k=>k+1),x==="message.created")){const k=I.current;I.current=!1,k||A(),_===O.current&&D($=>$+1)}if(x==="chat.read"&&_===O.current){const{read_up_to_message_id:k,reader:$}=ne.data;$==="user"&&V(k)}}}),()=>s(E)},[t.auth,n,s]),t.auth===void 0)return e.jsx(Le,{});if(t.auth===!1)return e.jsx(pt,{});if(((K=t.permissions)==null?void 0:K.includes("helpdesk.support_chat"))===!1)return e.jsx(ps,{status:"403",title:"Нет доступа",subTitle:"У вас нет прав для доступа к панели поддержки."});const te=a.find(E=>E.id===c)??null,he=()=>y(j),M=()=>S(E=>E+1);return e.jsxs("div",{style:{margin:"0 -24px -24px",minHeight:"calc(100vh - 72px)",background:"#fff",display:"flex",flexDirection:"column"},children:[e.jsxs("div",{style:{padding:"12px 20px",borderBottom:`1px solid ${g.greyF[100]}`,display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[e.jsx(Gn,{level:4,style:{margin:0},children:"Очередь обращений"}),e.jsx(ee,{color:"blue",style:{fontSize:12},children:"Поддержка"})]}),e.jsxs("div",{style:{display:"flex",flex:1,minHeight:0},children:[e.jsxs("div",{style:{width:360,flexShrink:0,borderRight:`1px solid ${g.greyF[100]}`,display:"flex",flexDirection:"column",overflow:"hidden"},children:[e.jsxs("div",{style:{padding:"10px 12px",borderBottom:`1px solid ${g.greyF[100]}`,display:"flex",flexDirection:"column",gap:8},children:[e.jsx(U,{prefix:e.jsx(Ct,{style:{color:g.greyF[600]}}),placeholder:"Поиск по пользователю, теме, сообщениям",value:j,onChange:E=>m(E.target.value),onPressEnter:he,allowClear:!0,onClear:()=>{m(""),y("")},size:"small"}),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx(ae,{value:h,onChange:E=>{o(E),p(null)},options:xl,size:"small",style:{flex:1}}),v.length>0&&e.jsx(ae,{value:b,onChange:w,placeholder:"Категория",allowClear:!0,options:v.map(E=>({value:E.id,label:E.name})),size:"small",style:{flex:1}})]})]}),e.jsx("div",{style:{flex:1,overflowY:"auto",padding:"6px 8px"},children:d?e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:8},children:Array.from({length:6}).map((E,ne)=>e.jsx(G,{active:!0,paragraph:{rows:2}},ne))}):a.length===0?e.jsx(xe,{description:"Нет обращений",style:{marginTop:40}}):a.map(E=>e.jsx(ml,{chat:E,selected:E.id===c,onClick:()=>p(E.id)},E.id))})]}),e.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",minWidth:0,height:"calc(100vh - 140px)"},children:e.jsx(bl,{chat:te,onChatUpdated:M,profile:t,externalMsgTrigger:F,lastUserReadMsgId:H,onMessageSent:()=>{I.current=!0}})})]})]})}const Cl=hs([{element:e.jsx(Us,{}),path:"/",children:[{path:"/",index:!0,element:e.jsx(ws,{})},{path:"/auth/login",element:e.jsx(pt,{})},{path:"/auth/logout",element:e.jsx(ti,{})},{path:"/auth/wblogin",element:e.jsx(qa,{})},{path:"/auth/ext-auth",element:e.jsx(Fn,{})},{path:"/wb-id-sdk/callback",element:e.jsx(Oa,{})},{path:"/profile",element:e.jsx(ei,{})},{path:"/devices",element:e.jsx(Tn,{})},{path:"/campaigns/:campaignId/bidder",element:e.jsx(lr,{})},{path:"/campaigns/:campaignId",element:e.jsx(br,{})},{path:"/campaigns",element:e.jsx(zs,{})},{path:"/subjects/:subjectId",element:e.jsx(Js,{})},{path:"/subjects",element:e.jsx(Xs,{})},{path:"/priority-subjects/:subjectId",element:e.jsx(Vs,{})},{path:"/priority-subjects",element:e.jsx(Zs,{})},{path:"/suppliers",element:e.jsx(yr,{})},{path:"/search-auction",element:e.jsx(Nr,{})},{path:"/external-analytics/niche-analysis/:subjectId",element:e.jsx($i,{})},{path:"/external-analytics/niche-analysis",element:e.jsx(ji,{})},{path:"/external-analytics/category-analysis",element:e.jsx(Ui,{})},{path:"/external-analytics/category-matrix",element:e.jsx(na,{})},{path:"/external-analytics/subject-matrix",element:e.jsx(pa,{})},{path:"/search-queries",element:e.jsx(ka,{})},{path:"/search-queries/:query",element:e.jsx(Na,{})},{path:"/wishes",element:e.jsx(Xa,{})},{path:"/helpdesk",element:e.jsx(ul,{})},{path:"/helpdesk-support",element:e.jsx(Sl,{})}]}]);function wl(){return e.jsx(fs,{router:Cl})}function kl(){return e.jsx(e.Fragment,{children:e.jsx(wl,{})})}xs.createRoot(document.getElementById("root")).render(e.jsx(rn.StrictMode,{children:e.jsx(gs,{theme:js,children:e.jsx($r,{children:e.jsx(bs,{children:e.jsx(Ws,{children:e.jsx(kl,{})})})})})}));