import{a as K,r as i,j as e,A as Tn,T as S,S as Le,R as Fn,L as O,F as _e,E as ye,u as xt,b as qt,I as V,c as In,B as E,d as mt,e as gt,f as yt,g as Oe,C as Ze,h as _t,i as q,k as ee,l as vt,W as Rn,m as Bt,n as Dn,D as Gt,o as En,p as Mn,q as Ln,N as Pn,O as $n,s as Ye,t as X,v as Ee,w as Qe,x as Ut,M as qe,y as Vt,z as ne,G as ce,P as Wn,H as je,J as be,K as Se,Q as An,U as zn,V as Nn,X as Kt,Y as Zt,Z as Yt,_ as Ve,$ as ut,a0 as Te,a1 as Qt,a2 as Xt,a3 as Jt,a4 as en,a5 as Hn,a6 as On,a7 as St,a8 as qn,a9 as Bn,aa as Gn,ab as Un,ac as Vn}from"./vendor-CLuDIj1P.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))a(r);new MutationObserver(r=>{for(const l of r)if(l.type==="childList")for(const c of l.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&a(c)}).observe(document,{childList:!0,subtree:!0});function s(r){const l={};return r.integrity&&(l.integrity=r.integrity),r.referrerPolicy&&(l.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?l.credentials="include":r.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function a(r){if(r.ep)return;r.ep=!0;const l=s(r);fetch(r.href,l)}})();const Be="/api",Xe=`${Be}/v2`,jt=`${Xe}/campaign`;function tn(){const t=document.cookie.match(/csrftoken=([^ ;]+)/);if(t)return t[1]}function G(t,n){return K.get(`${Be}/${t}`,n)}function Q(t,n,s){const a={"X-CSRFToken":tn()},r={withCredentials:!0,...s,headers:a};return K.post(`${Be}/${t}`,n,r)}function Kn(t,n){const s={"X-CSRFToken":tn()},a={withCredentials:!0,...n,headers:s};return K.delete(`${Be}/${t}`,a)}function W(t,n){return G(`v2/${t}/`,n)}function ve(t,n,s){return Q(`v2/${t}/`,n,s)}function Zn(t,n){return Kn(`v2/${t}/`,n)}function Je(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:{500:"#FF3F3F"},redPale:{400:"#FD7967"},greyF:{100:"#EFF1F5",700:"#6E7788"},greyS:{200:"#D1D1D6"},dark:{500:"#383540"}},Yn={token:{colorPrimary:"#F9AB0D",colorError:"#FF3F3F",colorText:"#383540",colorTextSecondary:"#6E7788",colorTextDisabled:"#C3C3C3",colorBgLayout:"#F7F8FA",borderRadius:6}},Qn=[],Xn=(t,n)=>{switch(n.type){case"ADD":return[n.payload,...t];case"REMOVE":return t.filter(s=>s.id!==n.payload);default:return t}},nn=i.createContext(Qn),A=()=>i.useContext(nn);function Jn({children:t}){const[n,s]=i.useReducer(Xn,[]),a=(o,d)=>{const p=Math.round(Math.random()*1e9);s({type:"ADD",payload:{id:p,severity:"info",text:o,...d}}),setTimeout(()=>{r(p)},5e3)},r=o=>{s({type:"REMOVE",payload:o})},l=(o,d={})=>{a(o,{...d,severity:"error"})},h={showMessage:a,showError:l,showRequestError:o=>{l(Je(o))}};return e.jsxs(nn.Provider,{value:h,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(o=>e.jsx(Tn,{type:o.severity==="error"?"error":"info",title:o.text,closable:!0,onClose:()=>r(o.id),showIcon:!0},o.id))})]})}const Ue="Панель";function ze({current:t,prev:n}){if(t==null||n==null)return"—";const s=t-n,a=n?(s/n*100).toFixed(1):0,r=s>=0,l=r?g.green[500]:g.red[500],c=r?gt:yt;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(c,{style:{fontSize:10}}),Math.abs(s).toLocaleString("ru-RU")," (",r?"+":"",a,"%)"]})]})}function Ct({placeholder:t,onSearch:n,options:s,onSelect:a,notFoundText:r}){const[l,c]=i.useState(""),[h,o]=xt("",300);i.useEffect(()=>{n(h)},[h]);const d=u=>{c(u),o(u)},p=(u,f)=>{a(u,f),c(""),o("")};return e.jsx(qt,{value:l,options:l.length>=2?s:[],onSelect:p,onChange:d,style:{width:"100%"},notFoundContent:l.length<2?null:e.jsx(ye,{image:ye.PRESENTED_IMAGE_SIMPLE,description:r||"Ничего не найдено"}),children:e.jsx(V,{placeholder:t,prefix:e.jsx(In,{style:{color:g.greyF[500]}}),allowClear:!0})})}function es(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(ze,{current:s.sellers,prev:s.sellers_prev})},{title:"Карточки",key:"cards",align:"right",render:(n,s)=>e.jsx(ze,{current:s.cards,prev:s.cards_prev})},{title:"Заказы",key:"orders",align:"right",render:(n,s)=>e.jsx(ze,{current:s.orders,prev:s.orders_prev})},{title:"",key:"actions",width:40,render:(n,s)=>e.jsx(E,{type:"text",size:"small",icon:e.jsx(mt,{style:{fontSize:10,color:g.greyF[500]}}),onClick:a=>{a.stopPropagation(),t(s.key)}})}]}function ts(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(ze,{current:s.day,prev:s.day_prev})},{title:"Неделя",key:"week",align:"right",render:(n,s)=>e.jsx(ze,{current:s.week,prev:s.week_prev})},{title:"",key:"actions",width:40,render:(n,s)=>e.jsx(E,{type:"text",size:"small",icon:e.jsx(mt,{style:{fontSize:10,color:g.greyF[500]}}),onClick:a=>{a.stopPropagation(),t(s.record_id)}})}]}function ns(){const{showRequestError:t}=A(),[n,s]=i.useState(!0),[a,r]=i.useState(!1),[l,c]=i.useState([]),[h,o]=i.useState([]),[d,p]=i.useState([]),[u,f]=i.useState([]),m=i.useRef(null),y=i.useRef(null),[_,j]=i.useState([]),[T,b]=i.useState([]);i.useEffect(()=>{const x=sessionStorage.getItem("wb_key");x&&(sessionStorage.removeItem("wb_key"),ve("user/key-check",{key:x}))},[]),i.useEffect(()=>{k()},[]);const w=i.useCallback(x=>{if(x.length<2){j([]);return}G("wbstat/subjects/search/",{params:{query:x}}).then(v=>{j(v.data||[])})},[]),F=i.useCallback(x=>{if(x.length<2){b([]);return}G("wbstat/phrases/search/",{params:{query:x}}).then(v=>{b(v.data||[])})},[]);async function k(){var x,v;s(!0);try{const[C,R]=await Promise.all([G("wbstat/dashboard/phrase-groups/"),G("wbstat/dashboard/subject-groups/")]),D=(C.data||[]).find($e=>$e.name===Ue),M=(R.data||[]).find($e=>$e.name===Ue);m.current=D||null,y.current=M||null;const[N,te]=await Promise.all([D?G(`wbstat/dashboard/phrase-groups/${D.id}/phrases/`):Promise.resolve({data:{phrases:[]}}),M?G(`wbstat/dashboard/subject-groups/${M.id}/subjects/`):Promise.resolve({data:{subjects:[]}})]),ge=((x=N.data)==null?void 0:x.phrases)||[],ke=((v=te.data)==null?void 0:v.subjects)||[];o(ge),c(ke),await L(ke,ge)}catch(C){t(C)}finally{s(!1)}}async function L(x=l,v=h){var D,M;const C=x.map(N=>N.subject_id),R=v.map(N=>N.text);if(C.length===0&&R.length===0){p([]),f([]);return}r(!0);try{const N=await Q("wbstat/dashboard/tables/",{subject_ids:C,queries:R});p(((D=N.data)==null?void 0:D.subjects)||[]),f(((M=N.data)==null?void 0:M.queries)||[])}catch(N){t(N)}finally{r(!1)}}async function I(){if(m.current)return m.current;const x=await Q("wbstat/dashboard/phrase-groups/",{name:Ue,description:"Dashboard panel"});return m.current=x.data,x.data}async function Z(){if(y.current)return y.current;const x=await Q("wbstat/dashboard/subject-groups/",{name:Ue,description:"Dashboard panel"});return y.current=x.data,x.data}async function pe(x){var C;const v=Number(x);if(!(!v||l.some(R=>R.subject_id===v)))try{const R=await Z(),M=((C=(await Q(`wbstat/dashboard/subject-groups/${R.id}/add/`,{subjects:[v]})).data)==null?void 0:C.subjects)||[];c(M),await L(M,h)}catch(R){t(R)}}async function fe(x){var C;const v=l.find(R=>R.subject_id===x);if(v)try{const R=y.current,M=((C=(await Q(`wbstat/dashboard/subject-groups/${R.id}/remove/`,{ids:[v.id]})).data)==null?void 0:C.subjects)||[];c(M),await L(M,h)}catch(R){t(R)}}async function P(x){var v;if(!(!x||h.some(C=>C.text===x)))try{const C=await I(),D=((v=(await Q(`wbstat/dashboard/phrase-groups/${C.id}/add/`,{phrases:[x]})).data)==null?void 0:v.phrases)||[];o(D),await L(l,D)}catch(C){t(C)}}async function z(x){var v;try{const C=m.current,D=((v=(await Q(`wbstat/dashboard/phrase-groups/${C.id}/remove/`,{ids:[x]})).data)==null?void 0:v.phrases)||[];o(D),await L(l,D)}catch(C){t(C)}}const se=new Set(l.map(x=>x.subject_id)),xe=_.filter(x=>!se.has(x.id)).map(x=>{var v;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(S.Text,{type:"secondary",style:{fontSize:12},children:(v=x.category)==null?void 0:v.name})]})}}),me=new Set(h.map(x=>x.text)),Pe=T.filter(x=>!me.has(x.text)).map(x=>{var v;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(S.Text,{type:"secondary",style:{fontSize:12},children:[x.subject&&e.jsxs(e.Fragment,{children:[x.subject," · "]}),(v=x.count)==null?void 0:v.toLocaleString("ru-RU")]})]})}}),st=d.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})),at=u.map(x=>{const v=h.find(C=>C.text===x.text);return{key:x.text,record_id:v==null?void 0:v.id,text:x.text,day:x.yesterday_count,day_prev:x.yesterday_prev_count,week:x.week_count,week_prev:x.week_prev_count}}),rt=es(fe),it=ts(z);return n?e.jsx("div",{style:{display:"flex",justifyContent:"center",paddingTop:100},children:e.jsx(Le,{indicator:e.jsx(Fn,{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(S.Title,{level:4,style:{margin:0},children:"Предметы"}),e.jsx(O,{to:"/external-analytics/niche-analysis",style:{textDecoration:"none",color:g.primary[500],fontWeight:600,fontSize:13},children:"Смотреть все"})]}),e.jsx(Ct,{placeholder:"Найти предмет...",onSearch:w,options:xe,onSelect:pe,notFoundText:"Предмет не найден"}),l.length>0?e.jsx(_e,{dataSource:st,columns:rt,pagination:!1,size:"small",bordered:!1,loading:a,locale:{emptyText:e.jsx(ye,{description:"Нет данных",image:ye.PRESENTED_IMAGE_SIMPLE})}}):e.jsx(S.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(S.Title,{level:4,style:{margin:0},children:"Запросы"}),e.jsx(O,{to:"/search-queries",style:{textDecoration:"none",color:g.primary[500],fontWeight:600,fontSize:13},children:"Смотреть все"})]}),e.jsx(Ct,{placeholder:"Найти запрос...",onSearch:F,options:Pe,onSelect:P,notFoundText:"Запрос не найден"}),h.length>0?e.jsx(_e,{dataSource:at,columns:it,pagination:!1,size:"small",bordered:!1,loading:a,locale:{emptyText:e.jsx(ye,{description:"Нет данных",image:ye.PRESENTED_IMAGE_SIMPLE})}}):e.jsx(S.Text,{type:"secondary",style:{padding:"8px 0"},children:"Добавьте запросы для отслеживания"})]})]})}const Ge=[{id:6,name:"Поиск"},{id:5,name:"Карточки"}],ss=[{id:0,name:"Все"},{id:1,name:"Активные"},{id:2,name:"Остановлены"},{id:3,name:"Неактивные"},{id:4,name:"Без биддера"}],sn=[{id:7,name:"Завершена"},{id:9,name:"Активна"},{id:11,name:"Приостановлена"}],as=[{id:0,name:"Все"},...sn],rs=t=>{const n=sn.find(s=>s.id===t);return n?n.name:""},is=[{title:"Кампания",dataIndex:"id",key:"id"},{title:"Параметры",key:"name",render:(t,n)=>{var s,a;return n.name||((s=n.bidder)==null?void 0:s.query)||((a=n.bidder)==null?void 0:a.name)}},{title:"Статус",key:"status",render:(t,n)=>rs(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(Ze,{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 ls({rows:t}){const n=Oe();return e.jsx(_e,{columns:is,dataSource:t||[],rowKey:(s,a)=>a,size:"small",pagination:!1,scroll:{x:900},onRow:s=>({onClick:()=>{const a=s.bidder?`/campaigns/${s.bidder.id}/bidder`:`/campaigns/${s.id}`;n(a)},style:{cursor:"pointer"}})})}function os({options:t,value:n,onChange:s}){function a(l){return t.findIndex(c=>c.id===l)}const r=t.map((l,c)=>({key:String(c),label:l.name}));return e.jsxs("div",{children:[e.jsx("h4",{children:"Типы кампаний"}),e.jsx(_t,{tabPosition:"left",activeKey:String(a(n)),onChange:l=>{s&&s(t[parseInt(l)].id)},items:r})]})}function cs({options:t,value:n,onChange:s}){const a=t.map((r,l)=>({key:String(l),label:r.name}));return e.jsxs("div",{children:[e.jsx("h4",{children:"Магазины"}),e.jsx(_t,{tabPosition:"left",activeKey:String(n),onChange:r=>{s&&s(parseInt(r))},items:a})]})}function ae({count:t=4}){return e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[...Array(t)].map((n,s)=>e.jsx(q.Input,{active:!0,block:!0,style:{height:32,width:"100%"}},s))})}function ds({status:t,bidder:n,onChange:s}){return e.jsxs("div",{style:{display:"flex",gap:8,marginBottom:8},children:[e.jsx(ee,{style:{flex:1},size:"small",value:t||0,onChange:a=>s&&s("status",a),options:as.map(a=>({value:a.id,label:a.name})),placeholder:"Статус"}),e.jsx(ee,{style:{flex:1},size:"small",value:n||0,onChange:a=>s&&s("bidder",a),options:ss.map(a=>({value:a.id,label:a.name})),placeholder:"Биддер"})]})}const us=`${Xe}/supplier/`,hs=(t,n,s)=>{const a=new URLSearchParams({...s,advert_type:t,supplier_id:n});return`${jt}/?${a.toString()}`};function ps(){const[t,n]=vt(),[s,a]=i.useState(!0),[r,l]=i.useState([]),[c,h]=i.useState([]),[o,d]=i.useState(void 0),p=parseInt(t.get("type")||6),u=parseInt(t.get("supplier")||0),f=parseInt(t.get("status")||0),m=parseInt(t.get("bidder")||0),y=(_,j)=>{const T=new URLSearchParams(t);T.set(_,j),n(T)};return i.useEffect(()=>(r.length===0&&(a(!0),K.get(us).then(_=>{l(_.data)}).finally(()=>a(!1))),()=>{}),[]),i.useEffect(()=>{var _;if(r.length>0){const j=hs(p,(_=r[u])==null?void 0:_.id,{status:f,bidder:m});a(!0),K.get(j).then(T=>{h(T.data)}).finally(()=>a(!1))}},[r,t]),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(S.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(os,{options:Ge,value:p,onChange:_=>y("type",_)}),e.jsx(cs,{options:r,value:u,onChange:_=>y("supplier",_)})]}),e.jsxs("div",{style:{flexGrow:1},children:[e.jsx(ds,{status:f,bidder:m,onChange:(_,j)=>y(_,j)}),s?e.jsx(ae,{count:5}):e.jsx(ls,{rows:c})]})]})]})}const fs="ooo_mkeeper_web",Me=new Rn({clientId:fs,redirectUri:`${window.location.protocol}//${window.location.host}/wb-id-sdk/callback`,scope:"openid phone"}),an="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",xs="auth_redirect",rn=()=>{const[t,n]=i.useState(!1),s=Bt(),a=()=>{var l;const r=(l=s.state)==null?void 0:l.from;r&&r!=="/auth/login"&&localStorage.setItem(xs,r),Me.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:an,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),a()},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:r=>r.currentTarget.style.backgroundColor="#EDEDF0",onMouseLeave:r=>r.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"})]})]})]})})},ht={},ln=i.createContext(ht);function ms({children:t}){const[n,s]=i.useState(ht),a=i.useRef(null),r=i.useRef(0),l=i.useCallback(()=>{const o=++r.current;return W("user/profile").then(d=>{o===r.current&&s({...d.data})})},[]),c=()=>{s({...ht,auth:!1})};i.useEffect(()=>{l()},[]),i.useEffect(()=>{if(!n.wb_id)return;const o=new Dn([{transport:"websocket",endpoint:"/api/centrifugo/connection/websocket"}],{getToken:()=>W("user/centrifugo-token").then(p=>p.data.token)}),d=o.newSubscription(`#wb_${n.wb_id}`);return d.on("publication",p=>{var u;((u=p.data)==null?void 0:u.op)==="getProfile"&&l()}),d.subscribe(),o.connect(),a.current=o,()=>{d.unsubscribe(),o.disconnect(),a.current=null}},[n.wb_id,l]);const h={profile:n,getProfile:l,clearProfile:c};return e.jsx(ln.Provider,{value:h,children:t})}const re=()=>i.useContext(ln);function gs(){const t=Oe(),{clearProfile:n,profile:s}=re(),a=()=>{Me.logout().then(()=>{}).catch(l=>console.log("wb logout error:",l)),Q("user/logout").then(()=>{n(),t("/")}).catch(l=>{})};if(!s.auth)return e.jsx(O,{to:"/auth/login",style:{color:"inherit",textDecoration:"none"},children:e.jsx(E,{type:"text",children:"Войти"})});const r=[{key:"profile",label:e.jsx(O,{to:"/profile",style:{color:"inherit",textDecoration:"none"},children:"Управление"})},{key:"logout",label:"Выйти",onClick:a}];return e.jsx(Gt,{menu:{items:r},trigger:["click"],children:e.jsx(E,{type:"text",icon:e.jsx(En,{}),style:{fontSize:"20px"}})})}const ys=[{key:"niche-analysis",label:e.jsx(O,{to:"/external-analytics/niche-analysis",style:{color:"inherit",textDecoration:"none"},children:"Анализ ниш"})},{key:"category-analysis",label:e.jsx(O,{to:"/external-analytics/category-analysis",style:{color:"inherit",textDecoration:"none"},children:"Анализ категорий"})},{key:"category-matrix",label:e.jsx(O,{to:"/external-analytics/category-matrix",style:{color:"inherit",textDecoration:"none"},children:"Матрица категорий"})},{key:"subject-matrix",label:e.jsx(O,{to:"/external-analytics/subject-matrix",style:{color:"inherit",textDecoration:"none"},children:"Матрица предметов"})},{key:"search-queries",label:e.jsx(O,{to:"/search-queries",style:{color:"inherit",textDecoration:"none"},children:"Запросы"})}];function _s(){const{profile:t}=re(),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(O,{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:an,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(Gt,{menu:{items:ys},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(Mn,{style:{fontSize:"10px"}})]})})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[n&&e.jsx(O,{to:"/wishes",children:e.jsx(E,{type:"text",icon:e.jsx(Ln,{}),style:{fontSize:"20px"}})}),e.jsx(gs,{})]})]})}function wt(){return e.jsx("div",{children:e.jsx(_s,{})})}const vs="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 et(){const[t,n]=i.useState(0);return i.useEffect(()=>(n(1),()=>{n(0)}),[]),e.jsx("div",{className:"spinner-wrapper",children:e.jsx("img",{src:vs,className:"spinner-img",style:{opacity:t}})})}const kt="cookie_banner_dismissed";function js(){const[t,n]=i.useState(()=>!localStorage.getItem(kt));if(!t)return null;const s=()=>{localStorage.setItem(kt,"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 bs=["/auth/login","/auth/logout","/auth/ext-auth","/wb-id-sdk/callback","/auth/wblogin"];function Ss(){const{profile:t}=re(),n=Bt(),s=bs.includes(n.pathname);return t.auth===void 0?e.jsxs("div",{style:{display:"flex"},children:[e.jsx(wt,{}),e.jsxs("main",{style:{flexGrow:1,minWidth:0,overflowX:"hidden",padding:"0 24px 24px 24px"},children:[e.jsx("div",{style:{height:"72px"}}),e.jsx(et,{})]})]}):t.auth===!1&&!s?e.jsx(Pn,{to:"/auth/login",replace:!0,state:{from:n.pathname+n.search+n.hash}}):e.jsxs("div",{style:{display:"flex"},children:[e.jsx(wt,{}),e.jsxs("main",{style:{flexGrow:1,minWidth:0,overflowX:"hidden",padding:"0 24px 24px 24px"},children:[e.jsx("div",{style:{height:"72px"}}),e.jsx($n,{})]}),e.jsx(js,{})]})}const on=({label:t,headers:n,rows:s})=>e.jsxs("div",{children:[t&&e.jsx(S.Title,{level:4,style:{padding:"16px"},children:t}),e.jsx(_e,{columns:n,dataSource:s||[],rowKey:(a,r)=>r,size:"small",pagination:!1,scroll:{x:900},locale:{emptyText:"Empty..."}})]}),Cs=()=>{let{subjectId:t}=Ye();const[n,s]=i.useState(!0),[a,r]=i.useState([]),l="Запросы по категории",c=[{title:"ПОИСКОВЫЙ ЗАПРОС",key:"text",dataIndex:"text"},{title:"ПРИОРИТЕТ",key:"priority",dataIndex:"priority",align:"right"},{title:"ПОКАЗОВ В МЕСЯЦ",key:"requestCount",dataIndex:"requestCount",align:"right"}];return i.useEffect(()=>{s(!0),W("wbstat/priority-subjects",{params:{id:t}}).then(o=>{var d;r(((d=o.data)==null?void 0:d.results)||[])}).finally(()=>s(!1))},[]),n?e.jsx(Le,{}):e.jsx("div",{children:e.jsx(on,{label:l,headers:c,rows:a})})},ws=()=>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(X.Group,{style:{marginBottom:8},children:[e.jsx(X,{value:"isByWord",children:"По словам"}),e.jsx(X,{value:"isBySearch",children:"История запросов"}),e.jsx(X,{value:"isByCategory",children:"По категории"})]}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx(V,{placeholder:"Поисковый запрос",size:"small",style:{flex:1}}),e.jsx(E,{type:"primary",style:{padding:"0 25px",fontSize:12,fontWeight:700},children:"Подобрать"})]})]}),ks=()=>{const t=[{title:"СТАТИСТИКА ПО СЛОВАМ",align:"left"},{title:"ПОКАЗОВ В МЕСЯЦ",align:"left"}];return e.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.jsx(ws,{}),e.jsx(on,{headers:t})]})};function Ts({options:t,onChange:n,value:s}){return e.jsx(Ee,{dataSource:t||[],renderItem:(a,r)=>{var l;return e.jsx(Ee.Item,{onClick:()=>{n(a)},style:{cursor:"pointer",background:(a==null?void 0:a.id)===(s==null?void 0:s.id)?"#FFFBF3":"transparent",padding:"8px 16px"},children:e.jsx(Ee.Item.Meta,{title:a.name,description:(l=a.category)==null?void 0:l.name})},r)}})}function Y(t){return t.toLocaleString()}const Fs=[{title:"Фраза",dataIndex:"text",key:"text"},{title:"Приоритет",dataIndex:"priority",key:"priority"},{title:"Запросов за неделю",key:"weekRequestCount",render:(t,n)=>Y(n.weekRequestCount)},{title:"Запросов за месяц",key:"monthRequestCount",render:(t,n)=>Y(n.monthRequestCount)},{title:"Запросов за 3 месяца",key:"quarterRequestCount",render:(t,n)=>Y(n.quarterRequestCount)}];function cn({rows:t}){return t!=null&&t.length?e.jsx(_e,{columns:Fs,dataSource:t||[],rowKey:(n,s)=>s,size:"small",pagination:!1,scroll:{x:900}}):null}function Is(){const[t,n]=i.useState(!1),[s,a]=i.useState([]),[r,l]=i.useState(""),[c,h]=i.useState([]),[o,d]=i.useState([]),[p,u]=i.useState(void 0),[f,m]=xt("",300);i.useEffect(()=>{p&&(n(!0),W(`wbstat/subjects/phrases/${p.id}`).then(j=>{var T,b;h(((T=j.data)==null?void 0:T.results)||[]),d(((b=j.data)==null?void 0:b.count)||0)}).finally(()=>n(!1)))},[p]),i.useEffect(()=>{if(r.length<3){a([]);return}W("wbstat/subjects/search",{params:{query:r}}).then(T=>{var b;a(((b=T.data)==null?void 0:b.results)||[])}).finally(()=>n(!1))},[f]);const y=j=>{l(j),m(j)},_=()=>{window.location.href=`/api/wbstat/subjects/phrases/${p.id}/xlsx/${p.name}.xlsx`};return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(S.Title,{level:4,style:{margin:0},children:"Фразы по категориям"}),e.jsx("div",{children:e.jsx(V,{onChange:j=>{y(j.target.value)},value:r,placeholder:"Введите текст для поиска категории",size:"large"})}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"240px 1fr",gap:"20px"},children:[e.jsx("div",{children:e.jsx(Ts,{options:s,onChange:u,value:p})}),e.jsxs("div",{style:{flexGrow:1},children:[t?e.jsx(ae,{count:1}):e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:!!(c!=null&&c.length)&&e.jsxs(E,{onClick:_,icon:e.jsx(Qe,{}),children:["Скачать ",o," фраз в xlsx"]})}),t?e.jsx(ae,{count:5}):e.jsx(cn,{rows:c})]})]})]})}function Rs(){const{subjectId:t}=Ye(),[n,s]=i.useState(!1),[a,r]=i.useState([]),[l,c]=i.useState(0),[h,o]=i.useState(void 0);i.useEffect(()=>{W("wbstat/subjects/search",{params:{id:t}}).then(u=>{var f,m,y;o(((m=(f=u.data)==null?void 0:f.results)==null?void 0:m.length)>0?(y=u.data)==null?void 0:y.results[0]:void 0)}).finally(()=>s(!1))},[]),i.useEffect(()=>{h&&(s(!0),W(`wbstat/subjects/phrases/${t}`).then(p=>{var u,f;r(((u=p.data)==null?void 0:u.results)||[]),c(((f=p.data)==null?void 0:f.count)||0)}).finally(()=>s(!1)))},[h]);const d=()=>{window.location.href=`/api/wbstat/subjects/phrases/${t}/xlsx/${h.name}.xlsx`};return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsxs(S.Title,{level:4,style:{margin:0},children:["Приоритетные фразы по категории ",h==null?void 0:h.name]}),e.jsxs("div",{style:{flexGrow:1},children:[n?e.jsx(ae,{count:1}):e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsxs(E,{onClick:d,icon:e.jsx(Qe,{}),children:["Скачать ",l," фраз в xlsx"]})}),n?e.jsx(ae,{count:5}):e.jsx(cn,{rows:a})]})]})}const Ds=t=>`/campaigns/${t}`,Es=t=>`/campaigns/${t}/bidder`;function Ms({instance:t,campaignId:n}){var s,a,r;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:Ds(n),children:e.jsx(E,{type:"link",children:"Изменить параметры"})})]}),e.jsx(S.Title,{level:5,style:{margin:0},children:"Параметры биддера"}),e.jsx(V,{id:"max-cpm",placeholder:"Максимальная ставка",value:((s=t.bidder)==null?void 0:s.maxbet)??"",size:"small"}),e.jsx(V,{id:"top-place",placeholder:"Верхняя позиция",value:((a=t.bidder)==null?void 0:a.top_place)??"",size:"small"}),e.jsx(V,{id:"low-place",placeholder:"Нижняя позиция",value:((r=t.bidder)==null?void 0:r.low_place)??"",size:"small"}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx(E,{type:"primary",children:"Сохранить изменения"}),e.jsx(E,{children:"Запустить биддер"})]})]})}const Ls=[{title:"Позиция",dataIndex:"place",key:"place"},{title:"Бренд",key:"brand",render:(t,n)=>`${n.brand} (${n.advert_id})`},{title:"Ставка",dataIndex:"cpm",key:"cpm",align:"right"}];function dn({data:t,place:n,campaignId:s}){const a=t==null?void 0:t.filter(r=>!n&&r.place<=20||r.place<4||r.place>t.length-3||0<=n-r.place&&n-r.place<10||0<=r.place-n&&r.place-n<5);return e.jsx(_e,{columns:Ls,dataSource:a||[],rowKey:"place",size:"small",pagination:!1,rowClassName:r=>r.advert_id===s?"ant-table-row-bold":""})}function Ps({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(S.Title,{level:5,style:{margin:0},children:"Состояние"}),e.jsx(Ee,{dataSource:s,renderItem:a=>e.jsx(Ee.Item,{children:e.jsx(Ee.Item.Meta,{title:a.value,description:a.label})})})]})}const $s=(t,n)=>(Ge.find(s=>s.id===t),`${jt}/${n}`),Ws=t=>`${Xe}/auction/${t}/`;function As(){var d,p;const{campaignId:t}=Ye(),[n,s]=i.useState(!0),[a,r]=i.useState([]),[l,c]=i.useState([]),[h,o]=i.useState(void 0);return i.useEffect(()=>{s(!0),K.get($s(6,t)).then(u=>{r(u.data)}).finally(()=>s(!1)),K.get(Ws(t)).then(u=>{var f,m;(m=(f=u.data)==null?void 0:f.data)==null||m.forEach((y,_)=>{y.place=_+1}),c(u.data)})},[t]),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsx(Ut,{items:[{title:e.jsx("a",{href:"/campaigns",children:"Мои кампании"})},{title:t}]}),e.jsxs(S.Title,{level:5,style:{margin:0},children:[(d=Ge.find(u=>u.id===a.advert_type))==null?void 0:d.name,": ",a.name]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"20px"},children:[e.jsx(Ms,{instance:a,campaignId:t}),e.jsx("div",{children:e.jsx(Ps,{instance:a.bidder||{}})}),e.jsx("div",{children:e.jsx(dn,{...l,campaignId:t,place:(p=a.bidder)==null?void 0:p.place})})]})]})}function zs({supplierId:t}){const[n,s]=i.useState(!1),a=()=>{s(!0)},r=()=>{s(!1)},l=()=>"Ключ API";return e.jsxs(e.Fragment,{children:[e.jsx(E,{onClick:a,type:"link",children:"Добавить"}),e.jsxs(qe,{open:n,onCancel:r,title:`Добавить ${l()} API`,onOk:r,okText:"Сохранить",cancelText:"Отмена",children:[e.jsx("p",{children:"Добавьте ключ API в кабинете поставщика и вставьте его сюда"}),e.jsx(V,{autoFocus:!0,id:"api_key",placeholder:l()})]})]})}function Ns({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(S.Title,{level:5,style:{margin:0},children:t.name}),e.jsx(E,{type:"text",children:"Удалить"})]}),e.jsxs("div",{children:["Ключ API: ",t!=null&&t.api_key?"Есть":e.jsx(zs,{supplierId:t.id,keyType:"uni"})]})]})}function Hs(){const[t,n]=i.useState(!1),s=()=>{n(!0)},a=()=>{n(!1)};return e.jsxs(e.Fragment,{children:[e.jsx(E,{onClick:s,type:"primary",children:"Добавить поставщика"}),e.jsxs(qe,{open:t,onCancel:a,title:"Добавить поставщика",onOk:a,okText:"Сохранить",cancelText:"Отмена",children:[e.jsx("p",{children:"Добавьте ключ API в кабинете поставщика и вставьте его сюда"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsx(V,{autoFocus:!0,id:"name",placeholder:"Наименование"}),e.jsx(V,{id:"api_key",placeholder:"Ключ API"})]})]})]})}const oe=({children:t,...n})=>{const{variant:s,color:a,sx:r,size:l,type:c,disabled:h,onClick:o,component:d,href:p,target:u,...f}=n;let m="default",y=!1;s==="contained"?m="primary":s==="outlined"&&(m="default"),a==="error"&&(y=!0);const _={fontSize:"16px",lineHeight:"26px",fontWeight:500,padding:"8px 20px",height:"auto",...r||{}};return d==="a"||p?e.jsx("a",{href:p,target:u,style:{textDecoration:"none"},children:e.jsx(E,{type:m,danger:y,disabled:h,onClick:o,style:_,htmlType:c,children:t})}):e.jsx(E,{type:m,danger:y,disabled:h,onClick:o,style:_,htmlType:c,children:t})},un=()=>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"})]}),Os=[{label:"1 месяц (30 дней)",value:1},{label:"3 месяца (90 дней)",value:3},{label:"6 месяцев (180 дней)",value:6},{label:"1 год (365 дней)",value:12}],qs=[{value:"russia",label:"Российская Федерация",icon:"🇷🇺"},{value:"foreign",label:"Иностранная карта",icon:"🌐"}];function Bs({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(S.Text,{style:{fontSize:13,textAlign:"center"},children:t.label})]})}function Ne({children:t,disabled:n,variant:s="contained",licenseKey:a}){const[r,l]=Vt.useState(!1),[c,h]=i.useState([]),[o,d]=i.useState(!0),[p,u]=i.useState(!1),[f,m]=i.useState(null),[y,_]=i.useState(1),[j,T]=i.useState("russia"),[b,w]=i.useState(!1),{showRequestError:F}=A(),k=()=>{d(!0),Promise.all([W("user/tariff"),W("user/tariff/current").catch(()=>null)]).then(([P,z])=>{const se=P.data??[],xe=z==null?void 0:z.data,me=xe?[xe,...se.filter(Pe=>Pe.id!==xe.id)]:se;me.length&&(h(me),m(me[0].id))}).catch(P=>{F(P)}).finally(()=>d(!1))};i.useEffect(()=>{r&&k()},[r]);const L=()=>{u(!0);const P=j!=="foreign"?b?"cloudpayments2":"cloudpayments":void 0;Q("billing/get_payment_link",{tariff:f,period:y,payment_method:j,autopay:j==="russia"?b:!1,...P?{agent:P}:{},...a?{key:a}:{}}).then(z=>{z.data.url?(window.open(z.data.url,"_blank").focus(),Z()):F("Ошибка при создании платежа")}).catch(z=>{F(`Ошибка при создании платежа: ${Je(z)}`)}).finally(()=>u(!1))},I=()=>l(!0),Z=()=>l(!1),pe=c.find(P=>P.id===f),fe=pe?pe.price*y:null;return e.jsxs(e.Fragment,{children:[e.jsx(oe,{disabled:n,variant:s,onClick:I,color:"primary",children:t}),e.jsx(qe,{open:!!r,onCancel:Z,title:"Покупка тарифа",footer:null,closeIcon:e.jsx(un,{}),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(S.Text,{style:{color:g.greyF[700]},children:"Тариф:"}),e.jsx(ee,{style:{width:"100%"},loading:o,value:f,onChange:m,options:c.map(P=>({label:P.name,value:P.id}))})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx(S.Text,{style:{color:g.greyF[700]},children:"Срок оплаты:"}),e.jsx(ee,{style:{width:"100%"},value:y,onChange:_,options:Os})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx(S.Text,{style:{color:g.greyF[700]},children:"Способ оплаты:"}),e.jsx("div",{style:{display:"flex",gap:8},children:qs.map(P=>e.jsx(Bs,{method:P,selected:j===P.value,onClick:()=>T(P.value)},P.value))})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[e.jsx(Ze,{checked:b&&j==="russia",onChange:P=>w(P.target.checked),disabled:j==="foreign",children:"Подключить автоплатёж"}),j==="foreign"&&e.jsx(S.Text,{style:{fontSize:12,color:g.greyF[700]},children:"При оплате методом «Иностранная карта» нет возможности подключить автоплатёж."})]}),e.jsx(ne,{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(S.Text,{style:{color:g.greyF[700],fontSize:13},children:"Итого:"}),e.jsx(S.Text,{strong:!0,style:{fontSize:22},children:fe!==null?`${fe.toLocaleString("ru-RU")} ₽`:"—"})]}),e.jsx(oe,{variant:"contained",color:"primary",onClick:L,disabled:!f||p,loading:p,children:"Оплатить"})]}),e.jsxs(S.Text,{style:{textAlign:"center",color:g.greyF[700],fontSize:13},children:["По вопросам с оплатой — ",e.jsx(S.Link,{href:"https://t.me/adm_mkeeper",target:"_blank",children:"@adm_mkeeper"})]})]})})]})}function Gs(){var p;const[t,n]=i.useState(!1),[s,a]=i.useState(void 0),{showRequestError:r,showError:l}=A();i.useEffect(()=>{n(!0),W("user/license").then(u=>{a(u.data)}).catch(u=>r(u)).finally(()=>n(!1))},[]);const c=()=>{Q("billing/get_payment_link",{}).then(u=>{u.data.url?window.open(u.data.url,"_blank").focus():l("Ошибка при создании платежа")}).catch(u=>{r(`Ошибка при создании платежа: ${Je(u)}`)})};if(t)return e.jsx(ae,{count:3});let h=!1;if(!(s!=null&&s.length))h=!0;else{const u=s[0];new Date(u.action_date).getFullYear()<2020&&(h=!0)}if(h)return e.jsxs("div",{style:{display:"flex",columnGap:12,alignItems:"center"},children:[e.jsx(S.Text,{children:"Отстутствует лицензия"}),e.jsx(Ne,{children:"Активировать подписку"})]});const o=s[0],d=new Date(o.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(S.Text,{style:{lineHeight:1.4},children:["Номер лицензии: ",o.key]}),e.jsxs(S.Text,{style:{lineHeight:1.4},children:["Тариф ",(p=o.tariff)==null?void 0:p.name]}),o.is_active?e.jsxs(S.Text,{style:{lineHeight:1.4},children:["Подписка активна до ",d.toLocaleDateString()]}):e.jsxs(S.Text,{style:{lineHeight:1.4},children:["Подписка закончилась ",d.toLocaleDateString()]})]}),e.jsx("div",{style:{marginTop:8,display:"flex",gap:8},children:o.tariff===void 0?e.jsx(Ne,{children:"Выбрать тариф"}):e.jsx(e.Fragment,{children:e.jsx(oe,{variant:"contained",onClick:c,children:"Продлить подписку"})})})]})}const Us="user/suppliers";function Vs(){const[t,n]=i.useState(!0),[s,a]=i.useState([]);return i.useEffect(()=>{n(!0),W(Us).then(r=>{a(r.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(Hs,{}),e.jsx(Gs,{}),e.jsx(O,{to:"/devices",children:e.jsx(E,{children:"Расширение Chrome"})})]}),s.map((r,l)=>e.jsx(Ns,{item:r},l))]})}const Ks=`${Be}/cabinet/supplier_full/`;function Zs(){const[t,n]=i.useState([]),[s,a]=i.useState(!0);return i.useEffect(()=>{t.length===0&&(a(!0),K.get(Ks).then(r=>{n(r.data)}).finally(()=>a(!1)))},[]),e.jsxs("div",{children:[e.jsx("h1",{children:"Поставщики и ключи API"}),e.jsx(Vs,{suppliers:t})]})}function Ys({instance:t,campaignId:n}){return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsx(V,{id:"name",placeholder:"Наименование кампании",value:t.name??"",size:"small"}),e.jsx(V,{id:"cpm",placeholder:"Ставка",value:t.bet??"",size:"small",type:"number"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",columnGap:8},children:[e.jsx(E,{type:"primary",children:"Сохранить изменения"}),e.jsx("a",{href:Es(n),children:e.jsx(E,{type:"link",children:"Запустить биддер"})})]})]})}const Qs=(t,n)=>(Ge.find(s=>s.id===t),`${jt}/${n}`),Xs=t=>`${Xe}/auction/${t}/`;function Js(){var d;const{campaignId:t}=Ye(),[n,s]=i.useState(!0),[a,r]=i.useState([]),[l,c]=i.useState([]),[h,o]=i.useState(void 0);return i.useEffect(()=>{s(!0),K.get(Qs(6,t)).then(p=>{r(p.data)}).finally(()=>s(!1)),K.get(Xs(t)).then(p=>{var u,f;(f=(u=p.data)==null?void 0:u.data)==null||f.forEach((m,y)=>{m.place=y+1}),c(p.data)})},[t]),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsx(Ut,{items:[{title:e.jsx("a",{href:"/campaigns",children:"Мои кампании"})},{title:t}]}),e.jsxs(S.Title,{level:5,style:{margin:0},children:["Изменение: ",(d=Ge.find(p=>p.id===a.advert_type))==null?void 0:d.name,": ",a.name]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:"20px"},children:[n?e.jsx("div",{style:{width:"100%"},children:e.jsx(ae,{})}):e.jsx(Ys,{instance:a,campaignId:t}),e.jsx("div",{}),e.jsx(dn,{...l,campaignId:t})]})]})}const ea="&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",ta=async t=>{let{data:n}=await K.get(`https://catalog-ads.wildberries.ru/api/v5/search?keyword=${t}`);if(!n.adverts)return null;const s=[];n.adverts.forEach(h=>s.push(h.id));let a=localStorage.getItem("geoData")||ea;const{data:r}=await K.get(`/api/wp/clist/?${a}&nm=${s.join(";")}`);if(!r)return null;const l=r.data.products.map(h=>(h.deliveryHours=h.time1+h.time2,h.nmId=h.id,h));return{advData:n,advGoods:l}};async function na(t){const{data:n}=await K.get("https://static-basket-01.wb.ru/vol0/data/subject-base.json");let s=[];const a=(r,l)=>{r.forEach(c=>{if(c.id==l){const h={id:c.id,subj_name:c.name};s.push(h)}else c.childs&&a(c.childs,l)})};return t.forEach(r=>a(n,r)),s}const sa=function(t,n,s){const{advData:a}=t;a.pages.sort((l,c)=>l.page-c.page);const r={};return s=ra(s,a),a.pages.forEach(l=>{let c=s.splice(0,l.positions.length);c.forEach((h,o)=>{const d=a.adverts.find(p=>p.id===h.nmId);aa(h,d,l.positions[o],l.page)}),l.page===1&&(c=n.concat(c)),c.sort((h,o)=>h.advStatFields.position-o.advStatFields.position),r[l.page]=c}),r},aa=function(t,n,s,a=1){var r,l,c,h;t.advStatFields={advertId:n.advertId,position:s,cpm:(r=(l=t.advStatFields)===null||l===void 0?void 0:l.cpm)!==null&&r!==void 0?r:n.cpm,subjectId:t.subjectId,brandId:t.brandCod,kindId:t.kindId,page:a,mk_cpmweight:(c=(h=t.advStatFields)===null||h===void 0?void 0:h.mk_cpmweight)!==null&&c!==void 0?c:0,mk_deliveryweight:(c=(h=t.advStatFields)===null||h===void 0?void 0:h.mk_deliveryweight)!==null&&c!==void 0?c:0,totalWeight:(c=(h=t.advStatFields)===null||h===void 0?void 0:h.totalWeight)!==null&&c!==void 0?c:0,cpmRatio:t.advStatFields.cpmRatio,deliveryRatio:t.advStatFields.deliveryRatio}},ra=function(t,n){var s,a;if((s=n.adverts)===null||s===void 0||!s.length||t==null||!t.length)return[];const r=n.adverts.reduce((c,h)=>c.set(h.id,h),new Map);if((a=n.prioritySubjects)!==null&&a!==void 0&&a.length)return ia(t,n,r);const l=hn(t,n.adverts.length);return pn(l,n,r)},hn=function(t,n){return{advertsCount:n??0,products:t??[]}},ia=function(t,n,s){const a=t.reduce((c,h)=>c.set(h.nmId,h),new Map),r=n.adverts.reduce((c,h)=>{var o;const d=h.subject,p=a.get(h.id),u=(o=c.get(d))!==null&&o!==void 0?o:hn();return u.advertsCount++,p&&u.products.push(p),c.set(d,u)},new Map),l=[];for(let c=0;co.advStatFields.totalWeight==d.advStatFields.totalWeight&&d.advStatFields.cpm!=o.advStatFields.cpm?d.advStatFields.cpm-o.advStatFields.cpm:d.advStatFields.totalWeight-o.advStatFields.totalWeight),a},la=function(t,n,s){const{cpms:a,deliveries:r}=t.reduce((o,d)=>{if(!d)return;const p=n.get(d.nmId);return o.deliveries.add(d.deliveryHours),o.cpms.add(p.cpm),o},{cpms:new Set,deliveries:new Set}),l=1/s.advertsCount;function c(o){let d=1;return o.reduce((p,u)=>p.has(u)?p:(p.size>0&&(d-=l),p.set(u,d)),new Map)}function h(o,d){const p=Array.from(o);return p.sort(d),p}return{weightMapCpm:c(h(a,(o,d)=>d-o)),weightMapDelivery:c(h(r,(o,d)=>o-d))}},oa=function(t){var n,s;let a=.6666666666666666,r=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&&(a=t.sortWeights.cpm/l,r=t.sortWeights.delivery/l)}return{cpmRatio:a,deliveryRatio:r}};function ca(t,n){const s=new Map;t.advData.adverts.forEach(d=>{s.has(d.id)||s.set(d.id,d)});const a=sa(t,[],t.advGoods),r=[];let l=0,c=0,h=0;Object.entries(a).forEach((d,p)=>{d[1].forEach(u=>{const f=++l;let m;n&&(m=n.find(_=>_.id===u.advStatFields.subjectId)),c||(c=u.advStatFields.cpmRatio),h||(h=u.advStatFields.deliveryRatio);const y={brand:u.brand,deliveryHours:u.deliveryHours,id:u.cod1S||u.id,n:f,page:u.advStatFields.page,pl:l,position:u.advStatFields.position,subj_name:m?m.subj_name:"",cpm:u.advStatFields.cpm,cpmWeight:u.advStatFields.mk_cpmweight.toFixed(3),deliveryWeight:u.advStatFields.mk_deliveryweight.toFixed(3),totalWeight:u.advStatFields.totalWeight.toFixed(3),subject:"",name:u.name};r.push(y)})});const o={cpm:"",delivery:"",cpmPercentages:null,deliveryPercentages:null};return t.advData.sortWeights&&(o.cpm=`${t.advData.sortWeights.cpm}/${t.advData.sortWeights.cpm+t.advData.sortWeights.delivery}`,o.delivery=`${t.advData.sortWeights.delivery}/${t.advData.sortWeights.cpm+t.advData.sortWeights.delivery}`),o.cpmPercentages=c*100,o.deliveryPercentages=h*100,{data:r,ratio:o}}async function da(t){const n=await ta(t);if(n===null)return new Promise((r,l)=>r([]));const s=await na(n.advData.prioritySubjects),a=ca(n,s);return new Promise((r,l)=>r(a.data))}var le=(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))(le||{});const tt=i.createContext({resolution:1920}),Tt=()=>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 ua({children:t}){const[n,s]=i.useState(document.body.clientWidth);return i.useEffect(()=>{window.addEventListener("resize",()=>s(Tt())),s(Tt())},[]),e.jsx(tt.Provider,{value:{resolution:n},children:t})}function fn(t,n=246,s=328){return`//basket-${ha(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 ha(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 pa({rows:t,skeleton:n}){return n?e.jsx("div",{children:[...Array(5)].map((s,a)=>e.jsxs("div",{style:{border:"1px solid #d5d5d5",padding:"8px",borderRadius:"10px",marginTop:a>0?"15px":0},children:[e.jsx(q.Input,{active:!0,block:!0,style:{height:15,width:"100%"}}),e.jsxs("div",{style:{display:"flex",marginTop:"4px",width:"100%"},children:[e.jsx(q.Image,{active:!0,style:{height:80,width:60,marginRight:"4px"}}),e.jsxs("div",{style:{width:"100%"},children:[e.jsx(q.Input,{active:!0,block:!0,style:{height:15,width:"100%"}}),e.jsx(q.Input,{active:!0,block:!0,style:{height:15,width:"100%",marginTop:"4px"}}),e.jsx(q.Input,{active:!0,block:!0,style:{height:15,width:"100%",marginTop:"4px"}})]})]})]},a))}):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:`${fn(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 fa=[{title:"№",dataIndex:"n",key:"n",align:"center",render:t=>Y(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:`${fn(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)=>`${Y(n.cpm)} ₽`},{title:"Вес ставки",key:"cpmWeight",align:"center",render:(t,n)=>Y(n.cpmWeight)},{title:"Доставка",key:"deliveryHours",align:"center",render:(t,n)=>`${Y(n.deliveryHours)} ч.`},{title:"Вес доставки",key:"deliveryWeight",align:"center",render:(t,n)=>Y(n.deliveryWeight)},{title:"Общий вес",key:"totalWeight",align:"center",render:(t,n)=>Y(n.totalWeight)},{title:"Место",key:"pl",align:"center",render:(t,n)=>Y(n.pl)},{title:"Страница",key:"page",align:"center",render:(t,n)=>Y(n.page)},{title:"Позиция",key:"position",align:"center",render:(t,n)=>Y(n.position)}];function xa({rows:t,skeleton:n}){return n?e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[...Array(8)].map((s,a)=>e.jsx(q.Input,{active:!0,block:!0,style:{height:32,width:"100%"}},a))}):e.jsx(_e,{columns:fa,dataSource:t||[],rowKey:"id",size:"small",pagination:!1,locale:{emptyText:"Пусто..."}})}function ma({rows:t,skeleton:n}){const{resolution:s}=i.useContext(tt);return e.jsx(e.Fragment,{children:s<=le.Mobile?e.jsx(pa,{skeleton:n,rows:t}):e.jsx(xa,{skeleton:n,rows:t})})}const ga=async t=>{const{data:n}=await K.get(`https://search.wb.ru/suggests/api/v3/hint?query=${t}&gender=common&locale=ru&lang=ru`);let s=[];return n.forEach(a=>{a.type==="suggest"&&s.push({label:a.name})}),new Promise((a,r)=>a(s))};function ya(){const[t,n]=i.useState(""),[s,a]=i.useState(!1),[r,l]=xt("",300),[c,h]=i.useState([]),[o,d]=i.useState([]),p=f=>{n(f),f&&(l(f),a(!0))};i.useEffect(()=>{if(!t){h([]),d([]),a(!1);return}da(t).then(f=>{h(f),a(!1)}),ga(t).then(f=>{Array.isArray(f)&&d(f)})},[r]);const u=o.map(f=>({value:f.label,label:f.label}));return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(S.Title,{level:4,style:{margin:0},children:"Аукцион поиска"}),e.jsx("div",{children:e.jsx(qt,{style:{width:"100%"},options:u,value:t,onSelect:f=>p(f),onSearch:f=>p(f),children:e.jsx(V.Search,{placeholder:"Введите текст для поиска",size:"large"})})}),e.jsx("div",{children:e.jsx(ma,{rows:c,skeleton:s})})]})}function _a({onConfirm:t,title:n,button:s,children:a}){const[r,l]=i.useState(!1),c=()=>{l(!0)},h=()=>{l(!1)},o=()=>{t&&t(),l(!1)};return e.jsxs(e.Fragment,{children:[e.jsx("div",{onClick:c,className:"hoverable-icon",children:s}),e.jsxs(qe,{open:r,onCancel:h,title:n,footer:null,closeIcon:e.jsx(un,{}),width:455,styles:{body:{padding:"16px 16px 0"}},children:[a&&e.jsx("div",{style:{marginBottom:16},children:a}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx(oe,{onClick:o,variant:"outlined",color:"error",sx:{width:"100%"},children:"Подтвердить"}),e.jsx(oe,{onClick:h,variant:"outlined",color:"secondary",sx:{width:"100%"},children:"Отмена"})]})]})]})}const va=30,Ce=44,ja=30,we=40,ba="_textCell_j8spt_1",Ft={textCell:ba},U=({value:t,textAlignment:n="left",link:s,routerLink:a,afterIcon:r})=>{let l=t;return a?l=e.jsx(O,{to:a,children:t}):s&&(l=e.jsx("a",{href:s,target:"_blank",children:t})),e.jsxs("div",{className:Ft.textCell,style:{textAlign:n},children:[e.jsx("span",{className:Ft.text,style:{fontSize:"16px",lineHeight:1.4,color:"#383540"},children:l}),r||""]})},Sa="_headerContainer_1o3pk_1",Ca="_customHeaderLabel_1o3pk_19",It={headerContainer:Sa,customHeaderLabel:Ca},wa=({size:t=16,color:n,direction:s="right"})=>{const a={up:"0deg",right:"90deg",down:"180deg"},r=n||g.dark[500];return e.jsx("svg",{style:{transform:`rotate(${a[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:r})})},de=t=>{const[n,s]=i.useState(!1),[a,r]=i.useState(!1),l=()=>{const h=t.column.getSort();s(h==="asc"),r(h==="desc")},c=h=>{const o=n?"desc":"asc";t.setSort(o,h.shiftKey)};return i.useEffect(()=>{t.column.addEventListener("sortChanged",l),l()},[]),e.jsxs("div",{className:It.headerContainer,onClick:c,onTouchEnd:c,style:t.enableSorting?{cursor:"pointer"}:{},children:[e.jsx("span",{className:It.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(wa,{direction:a?"down":"up",color:n||a?g.blue[500]:g.greyF[700]})}):""]})},ka=()=>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"})})})]}),ue=({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||"Нет данных"})}),Rt="user/device";function Ta(){const[t,n]=i.useState(!0),[s,a]=i.useState([]),{showRequestError:r}=A(),l=()=>{n(!0),W(Rt).then(d=>{a(d.data)}).catch(d=>{r(d)}).finally(()=>n(!1))};i.useEffect(()=>{l()},[]);const c=d=>d?new Date(d).toLocaleString("ru-RU",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"—",h=d=>{Zn(`${Rt}/${d}`).then(p=>{l()})};if(t)return e.jsx(ae,{count:2});const o=[{headerName:"Ключ активации",field:"key",cellRenderer:d=>e.jsx(U,{value:d.value})},{headerName:"User Agent",field:"user_agent",cellRenderer:d=>e.jsx(U,{value:d.value})},{headerName:"Дата использования",field:"last_check",cellRenderer:d=>e.jsx(U,{value:c(d.value)})},{headerName:"Дата активации",field:"activation_date",cellRenderer:d=>e.jsx(U,{value:c(d.value),afterIcon:e.jsx("div",{style:{height:"24px",marginLeft:"auto"},children:e.jsx(_a,{button:e.jsx(ka,{}),title:"Деактивировать устройство?",onConfirm:()=>h(d.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(ce,{domLayout:"autoHeight",rowHeight:ja,headerHeight:va,rowData:s,columnDefs:o,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!1,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:de},onFirstDataRendered:d=>d.api.sizeColumnsToFit(),noRowsOverlayComponent:ue})})})})}function xn(){const{profile:t}=re();return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:24},children:[e.jsx(S.Title,{level:5,style:{margin:0},children:"Устройства"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:16},children:e.jsx(Ta,{})})]})}function mn({hidden:t}){const n=Oe(),{profile:s}=re(),{showRequestError:a,showError:r}=A(),[l,c]=i.useState("");return i.useEffect(()=>{s.auth?ve("user/device/new").then(h=>{var o;(o=h.data)!=null&&o.key?c(h.data.key):(r("Нет свободных активаций. Отвяжите одно устройство или повысьте тариф"),n("/"))}).catch(h=>{}):n("/auth/login")},[]),e.jsxs("div",{children:[!t&&e.jsx(et,{}),e.jsx("input",{type:"hidden",id:"new-device-key",value:l})]})}function ie({label:t,value:n}){return e.jsxs("div",{style:{display:"flex",gap:16,paddingBlock:10},children:[e.jsx(S.Text,{style:{minWidth:180,color:"#888"},children:t}),e.jsx(S.Text,{children:n})]})}function lt({children:t}){return e.jsx(S.Title,{level:5,style:{margin:0},children:t})}function Fa({onDevicesClick:t}){var f;const{profile:n}=re(),[s,a]=i.useState(void 0),[r,l]=i.useState(!0),{showRequestError:c,showError:h,showMessage:o}=A();if(i.useEffect(()=>{l(!0),W("user/license").then(m=>{a(m.data)}).catch(m=>c(m)).finally(()=>l(!1))},[]),r)return e.jsx(ae,{count:4});const d=s==null?void 0:s[0],p=d&&new Date(d.action_date).getFullYear()>=2020,u=p?new Date(d.action_date).toLocaleDateString("ru-RU"):null;return e.jsxs("div",{style:{display:"flex",flexDirection:"column",maxWidth:560},children:[e.jsx(lt,{children:"Общая информация"}),e.jsx(ne,{style:{marginTop:8,marginBottom:0}}),n.wb_id&&e.jsx(ie,{label:"WB ID:",value:n.wb_id}),e.jsx(ie,{label:"Telegram:",value:n.tg_id??"—"}),e.jsxs("div",{style:{marginTop:24},children:[e.jsx(lt,{children:"Информация о тарифе"}),e.jsx(ne,{style:{marginTop:8,marginBottom:0}}),p?e.jsxs(e.Fragment,{children:[e.jsx(ie,{label:"Тариф:",value:((f=d.tariff)==null?void 0:f.name)??"—"}),e.jsx(ie,{label:"Лицензионный ключ:",value:d.key}),e.jsx(ie,{label:"Действует до:",value:u}),d.devices>0&&e.jsx(ie,{label:"Подключено устройств:",value:e.jsxs(S.Link,{onClick:t,children:[d.devices_used??0," из ",d.devices]})}),e.jsxs("div",{style:{marginTop:16,display:"flex",gap:8},children:[e.jsx(Ne,{variant:"contained",licenseKey:d.key,children:"Продлить тариф"}),e.jsx(Ne,{disabled:!0,variant:"outlined",licenseKey:d.key,children:"Сменить тариф"}),e.jsx(oe,{disabled:!0,variant:"outlined",children:"История оплат"})]})]}):e.jsx("div",{style:{paddingTop:12},children:e.jsx(Ne,{children:"Активировать подписку"})})]}),p&&e.jsxs("div",{style:{marginTop:24},children:[e.jsx(lt,{children:"Автоплатёж"}),e.jsx(ne,{style:{marginTop:8,marginBottom:0}}),d.next_pay_at&&e.jsx(ie,{label:"Следующее списание:",value:new Date(d.next_pay_at).toLocaleDateString("ru-RU")}),d.next_pay_amount!=null&&e.jsx(ie,{label:"Сумма списания:",value:`${d.next_pay_amount.toLocaleString("ru-RU")} ₽`}),d.autopay&&e.jsxs("div",{style:{paddingTop:10},children:[e.jsx(S.Text,{children:"Автоплатёж подключён. Вы можете "}),e.jsx(Wn,{title:"Отключить автоплатёж?",description:"Автоплатёж будет отключён. Текущий период останется активным.",okText:"Отключить",cancelText:"Назад",okButtonProps:{danger:!0},onConfirm:()=>{ve("user/cancel-payment",{}).then(m=>{var y;(y=m.data)!=null&&y.message&&o(m.data.message),a(_=>_.map((j,T)=>T===0?{...j,autopay:!1,next_pay_at:null}:j))}).catch(m=>{var y,_;h(((_=(y=m.response)==null?void 0:y.data)==null?void 0:_.error)??Je(m))})},children:e.jsx(S.Link,{children:"Отключить автоплатёж"})})]})]})]})}function Ia(){const{profile:t}=re(),[n]=vt(),[s,a]=i.useState("general"),r=n.get("auth")==="success";if(t.auth===void 0)return e.jsx(et,{});if(t.auth===!1)return e.jsx(rn,{});const l=[{key:"general",label:"Общее",children:e.jsx(Fa,{onDevicesClick:()=>a("devices")})},{key:"payment",label:"Оплата",children:null},{key:"devices",label:"Устройства",children:e.jsx(xn,{})},{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(S.Title,{level:4,style:{margin:0,marginBottom:24},children:"Профиль"}),e.jsx(_t,{items:l,activeKey:s,onChange:a}),r&&e.jsx(mn,{hidden:!0})]})}const Ra=()=>{const{clearProfile:t}=re(),n=Oe(),s=()=>{Me.logout().then(()=>{}).catch(a=>console.log("wb logout error:",a)),Q("user/logout").then(()=>{t(),n("/")}).catch(a=>{})};return i.useEffect(()=>{s()},[s]),e.jsx("div",{className:"auth-page",children:"Выход..."})},Da="_numberCell_1xqpf_1",Ea="_number_1xqpf_1",Ma="_tag_1xqpf_17",Fe={numberCell:Da,number:Ea,tag:Ma},$=({value:t,digits:n,cellStyle:s,textAlignment:a="end",tag:r=!1,icon:l=!1,prefix:c=!1,suffix:h=!1})=>{const o=d=>isNaN(d)||!isFinite(d)?"--":n!==void 0?d.toLocaleString("ru-RU",{minimumFractionDigits:n,maximumFractionDigits:n}):d.toLocaleString("ru-RU");return e.jsxs("div",{className:Fe.numberCell,style:{...s,justifyContent:a},children:[r&&e.jsx("div",{className:Fe.tag,children:r}),l&&e.jsx("div",{className:Fe.icon,children:l}),e.jsxs("span",{className:Fe.number,style:{fontSize:"16px",lineHeight:1.4,color:"#383540"},children:[c&&t!=null&&e.jsx("div",{className:Fe.prefix,children:c}),o(Number(t)),h&&t!=null&&e.jsx("div",{className:Fe.suffix,children:h})]})]})},La="_container_10jp5_1",Pa="_input_10jp5_10",ot={container:La,input:Pa},$a=500,he=i.forwardRef((t,n)=>{const[s,a]=i.useState(""),[r,l]=i.useState(""),c=i.useRef(null);i.useImperativeHandle(n,()=>({onParentModelChanged(u){u||(a(""),l(""))}}));const h=(u,f)=>{const m=u?Number(u):null,y=f?Number(f):null;m!=null&&y!=null?t.onModelChange({type:"inRange",filter:m,filterTo:y}):m!=null?t.onModelChange({type:"greaterThanOrEqual",filter:m}):y!=null?t.onModelChange({type:"lessThanOrEqual",filter:y}):t.onModelChange(null)},o=(u,f)=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{h(u,f)},$a)},d=u=>{const f=u.target.value;a(f),o(f,r)},p=u=>{const f=u.target.value;l(f),o(s,f)};return e.jsxs("div",{className:ot.container,children:[e.jsx("input",{className:ot.input,type:"number",placeholder:"От",value:s,onChange:d}),e.jsx("input",{className:ot.input,type:"number",placeholder:"До",value:r,onChange:p})]})});he.displayName="RangeFloatingFilter";je.setLicenseKey("key");be.registerModules([Se]);const Wa=64,Aa=10,za=()=>e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",width:"100%",height:"100%"},children:e.jsx(q.Input,{active:!0,size:"small",block:!0,style:{height:20,minWidth:0}})}),He=t=>n=>{var s;return(s=n.context)!=null&&s.loading?e.jsx(za,{}):t(n)},Na={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 Ha(t){const n={};for(const[s,a]of Object.entries(t)){const r=Na[s];r&&("text"in r?a.filter&&(n[r.text]=a.filter):a.type==="inRange"?(a.filter!=null&&(n[r.min]=String(a.filter)),a.filterTo!=null&&(n[r.max]=String(a.filterTo))):a.type==="greaterThanOrEqual"?a.filter!=null&&(n[r.min]=String(a.filter)):a.type==="lessThanOrEqual"&&a.filter!=null&&(n[r.max]=String(a.filter)))}return n}const B=(t,n,s={})=>({headerName:t,field:n,filter:"agNumberColumnFilter",floatingFilter:!0,floatingFilterComponent:he,minWidth:130,cellRenderer:He(a=>e.jsx($,{value:a.value,...s}))}),Oa=t=>t==null||isNaN(t)||!isFinite(t)?"--":t.toLocaleString("ru-RU"),H=(t,n)=>({headerName:t,field:n,filter:"agNumberColumnFilter",floatingFilter:!0,floatingFilterComponent:he,minWidth:170,cellRenderer:He(s=>{const a=s.value;if(a==null)return e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",width:"100%",height:"100%"},children:"--"});const r=a>=0,l=r?g.green[500]:g.red[500],c=r?gt:yt;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(c,{style:{fontSize:10}}),Oa(a),"%"]})})}),pt=[{headerName:"Категория",field:"category_name",filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:200,cellRenderer:He(t=>e.jsx(U,{value:t.value}))},{headerName:"Предмет",field:"subject_name",filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:150,cellRenderer:He(t=>e.jsx(U,{value:t.value,routerLink:`/external-analytics/niche-analysis/${t.data.subject}`}))},B("Выручка","revenue",{suffix:" ₽"}),H("Δ Выручка, %","revenue_change_pc"),B("Карточек товаров","cards_count"),H("Δ Карточек товаров, %","cards_count_change_pc"),{...B("Карточек с заказами","cards_with_orders_count"),minWidth:140},{...H("Δ Карточек с заказами, %","cards_with_orders_count_change_pc"),minWidth:160},{...B("Продавцы","suppliers"),minWidth:110},H("Δ Продавцы, %","suppliers_change_pc"),{...B("Продавцы с заказами","suppliers_with_sells"),minWidth:140},{...H("Δ Продавцы с заказами, %","suppliers_with_sells_change_pc"),minWidth:160},{...B("% выкупа","redemption_pc",{suffix:"%"}),minWidth:110},H("Δ % выкупа, %","redemption_pc_change_pc"),B("Заказы, шт","orders_qty"),H("Δ Заказы шт, %","orders_qty_change_pc"),B("Заказы, ₽","orders_rub",{suffix:" ₽"}),H("Δ Заказы ₽, %","orders_rub_change_pc"),B("Выкупы, шт","buyouts_qty"),H("Δ Выкупы шт, %","buyouts_qty_change_pc"),B("Выкупы, ₽","buyouts_rub",{suffix:" ₽"}),H("Δ Выкупы ₽, %","buyouts_rub_change_pc"),{...B("Средний чек","avg_check",{suffix:" ₽"}),minWidth:120},H("Δ Средний чек, %","avg_check_change_pc"),B("Оборачиваемость","weekly_turnover_days"),H("Δ Оборачиваемость, %","weekly_turnover_days_change_pc"),B("Монополизация","monopolization_pc"),H("Δ Монополизация, %","monopolization_pc_change_pc"),{...B("Среднее кол-во остатков","remaining_count"),minWidth:160},{...H("Δ Среднее кол-во остатков, %","remaining_count_change_pc"),minWidth:180},{headerName:"Средний рейтинг",field:"avg_rating",filter:"agNumberColumnFilter",floatingFilter:!0,floatingFilterComponent:he,minWidth:130,cellRenderer:He(t=>e.jsx($,{value:t.value,digits:1,icon:e.jsx(An,{style:{color:g.primary[500],fontSize:14}})}))},H("Δ Средний рейтинг, %","avg_rating_change_pc")],Dt=pt.map(t=>({field:t.field,headerName:t.headerName})),qa=t=>Array.from({length:t},(n,s)=>({_id:s}));function Ba({rowData:t,loading:n,onFilterChanged:s,onSortChanged:a,hiddenColumns:r=[]}){const l=i.useRef(Aa);!n&&t.length&&(l.current=t.length);const c=i.useMemo(()=>n?qa(l.current):t,[n,t]),h=i.useMemo(()=>({loading:n}),[n]),o=i.useMemo(()=>r.length?pt.filter(u=>!r.includes(u.field)):pt,[r]),d=i.useCallback(u=>{if(!s)return;const f=u.api.getFilterModel(),m=Ha(f);s(m)},[s]),p=i.useCallback(u=>{if(!a)return;const f=u.api.getColumnState().filter(m=>m.sort).map(m=>m.sort==="desc"?`-${m.colId}`:m.colId);a(f.length?f.join(","):null)},[a]);return e.jsx("div",{style:{width:"100%"},children:e.jsx(ce,{domLayout:"autoHeight",rowHeight:we,headerHeight:Ce,floatingFiltersHeight:Wa,rowData:c,columnDefs:o,context:h,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!0,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:de,headerComponentParams:{enableSorting:!0,wrapText:!0}},onGridReady:u=>{u.api.sizeColumnsToFit()},onGridSizeChanged:u=>{u.api.sizeColumnsToFit()},onFilterChanged:d,onSortChanged:p,noRowsOverlayComponent:ue})})}function gn(t,n){const[s,a]=i.useState(()=>{try{const p=localStorage.getItem(t);return p?JSON.parse(p):[]}catch{return[]}}),[r,l]=i.useState(!1),c=i.useCallback(()=>l(!0),[]),h=i.useCallback(()=>l(!1),[]),o=i.useCallback((p,u)=>{a(f=>{const m=u?f.filter(y=>y!==p):[...f,p];return localStorage.setItem(t,JSON.stringify(m)),m})},[t]),d=i.useMemo(()=>new Set(n.map(p=>p.field).filter(p=>!s.includes(p))),[n,s]);return{hiddenColumns:s,visibleColumns:d,open:r,openModal:c,closeModal:h,toggleColumn:o}}function yn({columns:t,hiddenColumns:n,open:s,onClose:a,onToggle:r}){return e.jsx(qe,{open:s,onCancel:a,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(zn,{size:"small",checked:!n.includes(l.field),onChange:c=>r(l.field,c)})]},l.field))})})}function _n({onClick:t}){return e.jsx(E,{icon:e.jsx(Nn,{}),onClick:t,children:"Настроить колонки"})}const{Title:Ga}=S,Ua="wbstat/external_analytics",Va=[{label:"Неделя",value:"week"},{label:"Месяц",value:"month"},{label:"Квартал",value:"quarter"}];function Ka(){const[t,n]=i.useState([]),[s,a]=i.useState(!0),[r,l]=i.useState({}),[c,h]=i.useState(null),[o,d]=i.useState("month"),{showRequestError:p}=A(),u=gn("niche_analysis_columns",Dt),f=i.useCallback(_=>{a(!0),G(`${Ua}/`,{params:_}).then(j=>{n(j.data.results)}).catch(j=>{p(j)}).finally(()=>{a(!1)})},[p]);i.useEffect(()=>{const _={...r,period:o,page_size:100};c&&(_.ordering=c),f(_)},[r,c,o]);const m=i.useCallback(_=>{l(_)},[]),y=i.useCallback(_=>{h(_)},[]);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(Ga,{level:3,style:{margin:0},children:"Анализ ниш"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap",justifyContent:"space-between"},children:[e.jsx(X.Group,{options:Va,value:o,onChange:_=>d(_.target.value),optionType:"button",buttonStyle:"solid"}),e.jsx(_n,{onClick:u.openModal})]}),e.jsx(yn,{columns:Dt,hiddenColumns:u.hiddenColumns,open:u.open,onClose:u.closeModal,onToggle:u.toggleColumn}),e.jsx(Ba,{rowData:t,loading:s,onFilterChanged:m,onSortChanged:y,hiddenColumns:u.hiddenColumns})]})}const Et=[{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]}],Za=["orders_qty","buyouts_qty","orders_rub","buyouts_rub"];function Ya(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 Qa(t){return t?new Date(t).toLocaleDateString("ru-RU",{day:"2-digit",month:"2-digit"}):""}function Xa({data:t}){const[n,s]=i.useState(Za),a=i.useMemo(()=>[...t].sort((o,d)=>new Date(o.period_start)-new Date(d.period_start)),[t]),r=i.useMemo(()=>a.map(o=>Qa(o.period_start)),[a]),l=i.useCallback((o,d)=>{s(p=>d?[...p,o]:p.filter(u=>u!==o))},[]),c=i.useMemo(()=>Et.filter(o=>n.includes(o.key)),[n]),h=i.useMemo(()=>{const o=c.map((p,u)=>({type:"log",name:p.name,nameTextStyle:{color:p.color,fontSize:11},position:u%2===0?"left":"right",offset:Math.floor(u/2)*70,axisLine:{show:!0,lineStyle:{color:p.color}},axisLabel:{fontSize:11,color:p.color,formatter:Ya},splitLine:{show:u===0}})),d=c.map((p,u)=>({name:p.name,type:"line",yAxisIndex:u,data:a.map(f=>f[p.key]),smooth:!0,symbol:"none",lineStyle:{width:2,color:p.color},itemStyle:{color:p.color}}));return{tooltip:{trigger:"axis",axisPointer:{type:"cross"}},grid:{left:20+Math.floor(c.filter((p,u)=>u%2===0).length/1)*35,right:20+Math.floor(c.filter((p,u)=>u%2!==0).length/1)*35,top:40,bottom:30,containLabel:!0},xAxis:{type:"category",data:r,axisLabel:{fontSize:11}},yAxis:o.length>0?o:[{type:"log"}],series:d}},[c,a,r]);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:Et.map(o=>e.jsx(Ze,{checked:n.includes(o.key),onChange:d=>l(o.key,d.target.checked),style:{color:o.color,fontWeight:500},children:e.jsx("span",{style:{color:o.color},children:o.name})},o.key))}),e.jsx(Kt,{option:h,style:{height:400},notMerge:!0})]})}je.setLicenseKey("key");be.registerModules([Se]);const Ja=10,er=()=>e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",width:"100%",height:"100%"},children:e.jsx(q.Input,{active:!0,size:"small",block:!0,style:{height:20,minWidth:0}})}),J=t=>n=>{var s;return(s=n.context)!=null&&s.loading?e.jsx(er,{}):t(n)};function tr(t){return t?new Date(t).toLocaleDateString("ru-RU"):""}const nr=[{headerName:"Период",field:"period_start",minWidth:120,cellRenderer:J(t=>e.jsx(U,{value:tr(t.value)}))},{headerName:"Брендов с выкупами",field:"brands_with_buyouts",minWidth:140,cellRenderer:J(t=>e.jsx($,{value:t.value}))},{headerName:"Брендов с заказами",field:"brands_with_orders",minWidth:140,cellRenderer:J(t=>e.jsx($,{value:t.value}))},{headerName:"Продавцов с заказами",field:"sellers_with_orders",minWidth:150,cellRenderer:J(t=>e.jsx($,{value:t.value}))},{headerName:"Продавцов с выкупами",field:"sellers_with_buyouts",minWidth:150,cellRenderer:J(t=>e.jsx($,{value:t.value}))},{headerName:"Карточек с выкупами",field:"cards_with_buyouts",minWidth:150,cellRenderer:J(t=>e.jsx($,{value:t.value}))},{headerName:"Карточек с заказами",field:"cards_with_orders",minWidth:150,cellRenderer:J(t=>e.jsx($,{value:t.value}))},{headerName:"Заказы (шт)",field:"orders_qty",minWidth:120,cellRenderer:J(t=>e.jsx($,{value:t.value}))},{headerName:"Заказы (₽)",field:"orders_rub",minWidth:130,cellRenderer:J(t=>e.jsx($,{value:t.value,suffix:" ₽"}))},{headerName:"Выкупы (шт)",field:"buyouts_qty",minWidth:120,cellRenderer:J(t=>e.jsx($,{value:t.value}))},{headerName:"Выкупы (₽)",field:"buyouts_rub",minWidth:130,cellRenderer:J(t=>e.jsx($,{value:t.value,suffix:" ₽"}))}],sr=t=>Array.from({length:t},(n,s)=>({_id:s}));function ar({rowData:t,loading:n}){const s=i.useRef(Ja);!n&&t.length&&(s.current=t.length);const a=i.useMemo(()=>n?sr(s.current):t,[n,t]),r=i.useMemo(()=>({loading:n}),[n]);return e.jsx("div",{style:{width:"100%"},children:e.jsx(ce,{domLayout:"autoHeight",rowHeight:we,headerHeight:Ce,rowData:a,columnDefs:nr,context:r,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!1,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:de},onGridReady:l=>{l.api.sizeColumnsToFit()},onGridSizeChanged:l=>{l.api.sizeColumnsToFit()},noRowsOverlayComponent:ue})})}const{Title:rr}=S,ir="sales/subject-dynamic",lr=[{label:"День",value:"day"},{label:"Неделя",value:"week"},{label:"Месяц",value:"month"}];async function or(t,n){let s=1,a=[];for(;;){const r=await G(`${ir}/`,{params:{subject_id:t,period:n,page:s}}),{results:l,next:c}=r.data;if(a=a.concat(l),!c)break;s++}return a}function cr(){const{subjectId:t}=Zt(),[n,s]=i.useState([]),[a,r]=i.useState(!0),[l,c]=i.useState("month"),{showRequestError:h}=A(),o=i.useCallback(()=>{r(!0),or(t,l).then(p=>s(p)).catch(p=>h(p)).finally(()=>r(!1))},[t,l,h]);i.useEffect(()=>{o()},[o]);const d=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(O,{to:"/external-analytics/niche-analysis",children:e.jsx(Yt,{style:{fontSize:20,color:"#383540"}})}),e.jsx(rr,{level:3,style:{margin:0},children:a&&!d?e.jsx(Le,{size:"small"}):`Динамика ниши: ${d}`})]}),e.jsx(X.Group,{options:lr,value:l,onChange:p=>c(p.target.value),optionType:"button",buttonStyle:"solid"}),!a&&n.length>0&&e.jsx(Xa,{data:n}),e.jsx(ar,{rowData:n,loading:a})]})}je.setLicenseKey("key");be.registerModules([Se]);const dr=64,ur=10,hr=()=>e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",width:"100%",height:"100%"},children:e.jsx(q.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(hr,{}):t(n)},pr={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 fr(t){const n={};for(const[s,a]of Object.entries(t)){const r=pr[s];r&&("text"in r?a.filter&&(n[r.text]=a.filter):a.type==="inRange"?(a.filter!=null&&(n[r.min]=String(a.filter)),a.filterTo!=null&&(n[r.max]=String(a.filterTo))):a.type==="greaterThanOrEqual"?a.filter!=null&&(n[r.min]=String(a.filter)):a.type==="lessThanOrEqual"&&a.filter!=null&&(n[r.max]=String(a.filter)))}return n}const Ie=(t,n,s={})=>({headerName:t,field:n,filter:"agNumberColumnFilter",floatingFilter:!0,floatingFilterComponent:he,minWidth:130,cellRenderer:bt(a=>e.jsx($,{value:a.value,...s}))}),xr=t=>t==null||isNaN(t)||!isFinite(t)?"--":t.toLocaleString("ru-RU"),Re=(t,n)=>({headerName:t,field:n,filter:"agNumberColumnFilter",floatingFilter:!0,floatingFilterComponent:he,minWidth:170,cellRenderer:bt(s=>{const a=s.value;if(a==null)return e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",width:"100%",height:"100%"},children:"--"});const r=a>=0,l=r?g.green[500]:g.red[500],c=r?gt:yt;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(c,{style:{fontSize:10}}),xr(a),"%"]})})}),ft=[{headerName:"Категория",field:"category_name",filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:200,cellRenderer:bt(t=>e.jsx(U,{value:t.value}))},Ie("Заказы, ₽","orders_rub",{suffix:" ₽"}),Re("Δ Заказы ₽, %","orders_rub_change_pc"),Ie("Заказы, шт","orders_qty"),Re("Δ Заказы шт, %","orders_qty_change_pc"),Ie("Выкупы, ₽","buyouts_rub",{suffix:" ₽"}),Re("Δ Выкупы ₽, %","buyouts_rub_change_pc"),Ie("Выкупы, шт","buyouts_qty"),Re("Δ Выкупы шт, %","buyouts_qty_change_pc"),Ie("Карточек товаров","cards_count"),Re("Δ Карточек товаров, %","cards_count_change_pc"),{...Ie("Карточек с заказами","cards_with_orders_count"),minWidth:140},{...Re("Δ Карточек с заказами, %","cards_with_orders_count_change_pc"),minWidth:160}],Mt=ft.map(t=>({field:t.field,headerName:t.headerName})),mr=t=>Array.from({length:t},(n,s)=>({_id:s}));function gr({rowData:t,loading:n,onFilterChanged:s,onSortChanged:a,hiddenColumns:r=[]}){const l=i.useRef(ur);!n&&t.length&&(l.current=t.length);const c=i.useMemo(()=>n?mr(l.current):t,[n,t]),h=i.useMemo(()=>({loading:n}),[n]),o=i.useMemo(()=>r.length?ft.filter(u=>!r.includes(u.field)):ft,[r]),d=i.useCallback(u=>{if(!s)return;const f=u.api.getFilterModel(),m=fr(f);s(m)},[s]),p=i.useCallback(u=>{if(!a)return;const f=u.api.getColumnState().filter(m=>m.sort).map(m=>m.sort==="desc"?`-${m.colId}`:m.colId);a(f.length?f.join(","):null)},[a]);return e.jsx("div",{style:{width:"100%"},children:e.jsx(ce,{domLayout:"autoHeight",rowHeight:we,headerHeight:Ce,floatingFiltersHeight:dr,rowData:c,columnDefs:o,context:h,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!0,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:de,headerComponentParams:{enableSorting:!0,wrapText:!0}},onGridReady:u=>{u.api.sizeColumnsToFit()},onGridSizeChanged:u=>{u.api.sizeColumnsToFit()},onFilterChanged:d,onSortChanged:p,noRowsOverlayComponent:ue})})}const{Title:yr}=S,_r="wbstat/external_analytics_category",vr=[{label:"Неделя",value:"week"},{label:"Месяц",value:"month"},{label:"Квартал",value:"quarter"}];function jr(){const[t,n]=i.useState([]),[s,a]=i.useState(!0),[r,l]=i.useState({}),[c,h]=i.useState(null),[o,d]=i.useState("month"),{showRequestError:p}=A(),u=gn("category_analysis_columns",Mt),f=i.useCallback(_=>{a(!0),G(`${_r}/`,{params:_}).then(j=>{n(j.data.results)}).catch(j=>{p(j)}).finally(()=>{a(!1)})},[p]);i.useEffect(()=>{const _={...r,period:o,page_size:100};c&&(_.ordering=c),f(_)},[r,c,o]);const m=i.useCallback(_=>{l(_)},[]),y=i.useCallback(_=>{h(_)},[]);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(yr,{level:3,style:{margin:0},children:"Анализ категорий"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap",justifyContent:"space-between"},children:[e.jsx(X.Group,{options:vr,value:o,onChange:_=>d(_.target.value),optionType:"button",buttonStyle:"solid"}),e.jsx(_n,{onClick:u.openModal})]}),e.jsx(yn,{columns:Mt,hiddenColumns:u.hiddenColumns,open:u.open,onClose:u.closeModal,onToggle:u.toggleColumn}),e.jsx(gr,{rowData:t,loading:s,onFilterChanged:m,onSortChanged:y,hiddenColumns:u.hiddenColumns})]})}function Ke(t,n,s,a,r){if(n===s)return;let l;if(a==="log"){const h=Math.log1p(n),o=Math.log1p(s);l=(Math.log1p(t)-h)/(o-h)}else if(a==="quantile"){if(!r||r.length<2)return;let h=0,o=r.length-1;for(;h>1;r[d]n.date_from.slice(0,7))}function jn(t){const[n,s]=t.split("-"),r=new Date(Number(n),Number(s)-1,1).toLocaleDateString("ru-RU",{month:"long",year:"numeric"});return r.charAt(0).toUpperCase()+r.slice(1)}function bn(t,n){let s=1/0,a=-1/0;for(const r of t)for(const l of n){const c=r[l];c!=null&&isFinite(c)&&(ca&&(a=c))}return isFinite(s)?{min:s,max:a}:{min:0,max:0}}function Sn(t,n){const s=[];for(const a of t)for(const r of n){const l=a[r];l!=null&&isFinite(l)&&s.push(l)}return s.sort((a,r)=>a-r),s}function Cn(t,n){let s=1/0;for(const a of n){const r=t[a];r!=null&&isFinite(r)&&r>0&&rArray.from({length:t},(n,s)=>({_id:s}));je.setLicenseKey("key");be.registerModules([Se]);const br=10,Sr=()=>e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",width:"100%",height:"100%"},children:e.jsx(q.Input,{active:!0,size:"small",block:!0,style:{height:20,minWidth:0}})}),Lt=t=>n=>{var s;return(s=n.context)!=null&&s.loading?e.jsx(Sr,{}):t(n)};function Cr(t){return!t||!t.length?[]:t.map(n=>{const s={category_name:n.category_name};return n.values&&n.values.forEach(a=>{const r=a.date_from.slice(0,7);s[r]=a.value}),s})}const wr={category_name:{text:"category"}};function kr(t){const n={};for(const[s,a]of Object.entries(t)){const r=wr[s];r&&"text"in r&&a.filter&&(n[r.text]=a.filter)}return n}function Tr({rowData:t,loading:n,onFilterChanged:s,onSortChanged:a}){const r=i.useRef(null),l=i.useRef(br),[c,h]=i.useState("linear"),o=i.useMemo(()=>vn(t),[t]),d=i.useMemo(()=>Cr(t),[t]),{min:p,max:u}=i.useMemo(()=>bn(d,o),[d,o]),f=i.useMemo(()=>Sn(d,o),[d,o]);!n&&d.length&&(l.current=d.length);const m=i.useMemo(()=>n?kn(l.current):d,[n,d]),y=i.useMemo(()=>({loading:n}),[n]),_=i.useMemo(()=>{const w=[{headerName:"Категория",field:"category_name",filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:200,pinned:"left",cellRenderer:Lt(F=>e.jsx(U,{value:F.value}))}];return o.forEach(F=>{w.push({headerName:jn(F),field:F,filter:"agNumberColumnFilter",minWidth:140,cellRenderer:Lt(k=>e.jsx($,{value:k.value})),cellStyle:k=>{if(k.value==null||!isFinite(k.value))return;let L;if(c==="dynamics"){const I=Cn(k.data,o);L=Ke(k.value,I,I*3,"linear")}else L=Ke(k.value,p,u,c,f);return L?{backgroundColor:L}:void 0}})}),w},[o,p,u,c,f]),j=i.useCallback(w=>{if(!s)return;const F=w.api.getFilterModel(),k=kr(F);s(k)},[s]),T=i.useCallback(w=>{if(!a)return;const F=w.api.getColumnState().filter(k=>k.sort).map(k=>k.sort==="desc"?`-${k.colId}`:k.colId);a(F.length?F.join(","):null)},[a]),b=i.useCallback(()=>{var w;(w=r.current)!=null&&w.api&&r.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(X.Group,{options:wn,value:c,onChange:w=>h(w.target.value),optionType:"button",size:"small"}),e.jsx(E,{icon:e.jsx(Qe,{}),onClick:b,children:"Скачать"})]}),e.jsx(ce,{ref:r,rowHeight:we,headerHeight:Ce,rowData:m,columnDefs:_,context:y,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!0,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:de,headerComponentParams:{enableSorting:!0,wrapText:!0}},onGridReady:()=>{},onGridSizeChanged:()=>{},onFilterChanged:j,onSortChanged:T,noRowsOverlayComponent:ue})]})}const{Title:Fr}=S,Ir="wbstat/category_matrix",Rr=[{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 Dr(){const[t,n]=i.useState([]),[s,a]=i.useState(!0),[r,l]=i.useState({}),[c,h]=i.useState(null),[o,d]=i.useState("orders_qty"),[p,u]=i.useState(null),[f,m]=i.useState(null),{showRequestError:y}=A(),_=i.useCallback(b=>{a(!0),G(`${Ir}/`,{params:b}).then(w=>{n(w.data.results)}).catch(w=>{y(w)}).finally(()=>{a(!1)})},[y]);i.useEffect(()=>{const b={...r,indicator:o,page_size:100};c&&(b.ordering=c),p!=null&&(b.value_min=p),f!=null&&(b.value_max=f),_(b)},[r,c,o,p,f]);const j=i.useCallback(b=>{l(b)},[]),T=i.useCallback(b=>{h(b)},[]);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(Fr,{level:3,style:{margin:0},children:"Матрица категорий"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[e.jsx(ee,{options:Rr,value:o,onChange:d,style:{width:260}}),e.jsx(Ve,{placeholder:"От",value:p,onChange:u,style:{width:140}}),e.jsx(Ve,{placeholder:"До",value:f,onChange:m,style:{width:140}})]}),e.jsx(Tr,{rowData:t,loading:s,onFilterChanged:j,onSortChanged:T})]})}je.setLicenseKey("key");be.registerModules([Se]);const Er=10,Mr=()=>e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",width:"100%",height:"100%"},children:e.jsx(q.Input,{active:!0,size:"small",block:!0,style:{height:20,minWidth:0}})}),ct=t=>n=>{var s;return(s=n.context)!=null&&s.loading?e.jsx(Mr,{}):t(n)};function Lr(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(a=>{const r=a.date_from.slice(0,7);s[r]=a.value}),s})}const Pr={category_name:{text:"category"},subject_name:{text:"subject_name"}};function $r(t){const n={};for(const[s,a]of Object.entries(t)){const r=Pr[s];r&&"text"in r&&a.filter&&(n[r.text]=a.filter)}return n}function Wr({rowData:t,loading:n,onFilterChanged:s,onSortChanged:a}){const r=i.useRef(null),l=i.useRef(Er),[c,h]=i.useState("linear"),o=i.useMemo(()=>vn(t),[t]),d=i.useMemo(()=>Lr(t),[t]),{min:p,max:u}=i.useMemo(()=>bn(d,o),[d,o]),f=i.useMemo(()=>Sn(d,o),[d,o]);!n&&d.length&&(l.current=d.length);const m=i.useMemo(()=>n?kn(l.current):d,[n,d]),y=i.useMemo(()=>({loading:n}),[n]),_=i.useMemo(()=>{const w=[{headerName:"Категория",field:"category_name",filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:200,pinned:"left",cellRenderer:ct(F=>e.jsx(U,{value:F.value}))},{headerName:"Предмет",field:"subject_name",filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:180,pinned:"left",cellRenderer:ct(F=>e.jsx(U,{value:F.value}))}];return o.forEach(F=>{w.push({headerName:jn(F),field:F,filter:"agNumberColumnFilter",minWidth:140,cellRenderer:ct(k=>e.jsx($,{value:k.value})),cellStyle:k=>{if(k.value==null||!isFinite(k.value))return;let L;if(c==="dynamics"){const I=Cn(k.data,o);L=Ke(k.value,I,I*3,"linear")}else L=Ke(k.value,p,u,c,f);return L?{backgroundColor:L}:void 0}})}),w},[o,p,u,c,f]),j=i.useCallback(w=>{if(!s)return;const F=w.api.getFilterModel(),k=$r(F);s(k)},[s]),T=i.useCallback(w=>{if(!a)return;const F=w.api.getColumnState().filter(k=>k.sort).map(k=>k.sort==="desc"?`-${k.colId}`:k.colId);a(F.length?F.join(","):null)},[a]),b=i.useCallback(()=>{var w;(w=r.current)!=null&&w.api&&r.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(X.Group,{options:wn,value:c,onChange:w=>h(w.target.value),optionType:"button",size:"small"}),e.jsx(E,{icon:e.jsx(Qe,{}),onClick:b,children:"Скачать"})]}),e.jsx(ce,{ref:r,rowHeight:we,headerHeight:Ce,rowData:m,columnDefs:_,context:y,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!0,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:de,headerComponentParams:{enableSorting:!0,wrapText:!0}},onGridReady:()=>{},onGridSizeChanged:()=>{},onFilterChanged:j,onSortChanged:T,noRowsOverlayComponent:ue})]})}const{Title:Ar}=S,zr="wbstat/subject_matrix",Nr=[{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 Hr(){const[t,n]=i.useState([]),[s,a]=i.useState(!0),[r,l]=i.useState({}),[c,h]=i.useState(null),[o,d]=i.useState("orders_qty"),[p,u]=i.useState(null),[f,m]=i.useState(null),{showRequestError:y}=A(),_=i.useCallback(b=>{a(!0),G(`${zr}/`,{params:b}).then(w=>{n(w.data.results)}).catch(w=>{y(w)}).finally(()=>{a(!1)})},[y]);i.useEffect(()=>{const b={...r,indicator:o,page_size:100};c&&(b.ordering=c),p!=null&&(b.value_min=p),f!=null&&(b.value_max=f),_(b)},[r,c,o,p,f]);const j=i.useCallback(b=>{l(b)},[]),T=i.useCallback(b=>{h(b)},[]);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(Ar,{level:3,style:{margin:0},children:"Матрица предметов"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap"},children:[e.jsx(ee,{options:Nr,value:o,onChange:d,style:{width:260}}),e.jsx(Ve,{placeholder:"От",value:p,onChange:u,style:{width:140}}),e.jsx(Ve,{placeholder:"До",value:f,onChange:m,style:{width:140}})]}),e.jsx(Wr,{rowData:t,loading:s,onFilterChanged:j,onSortChanged:T})]})}je.setLicenseKey("key");be.registerModules([Se]);const Or=64,qr=10,Br=()=>e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",width:"100%",height:"100%"},children:e.jsx(q.Input,{active:!0,size:"small",block:!0,style:{height:20,minWidth:0}})}),nt=t=>n=>{var s;return(s=n.context)!=null&&s.loading?e.jsx(Br,{}):t(n)},Gr={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 Ur(t){const n={};for(const[s,a]of Object.entries(t)){const r=Gr[s];r&&("text"in r?a.filter&&(n[r.text]=a.filter):a.type==="inRange"?(a.filter!=null&&(n[r.min]=String(a.filter)),a.filterTo!=null&&(n[r.max]=String(a.filterTo))):a.type==="greaterThanOrEqual"?a.filter!=null&&(n[r.min]=String(a.filter)):a.type==="lessThanOrEqual"&&a.filter!=null&&(n[r.max]=String(a.filter)))}return n}const Vr=(t,n,s={})=>({headerName:t,field:n,filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:200,cellRenderer:nt(a=>e.jsx(U,{value:a.value})),...s}),De=(t,n,s={})=>({headerName:t,field:n,filter:"agNumberColumnFilter",floatingFilter:!0,floatingFilterComponent:he,minWidth:130,cellRenderer:nt(a=>e.jsx($,{value:a.value,...s}))}),Pt=(t,n)=>({headerName:t,field:n,filter:"agNumberColumnFilter",floatingFilter:!0,floatingFilterComponent:he,minWidth:130,cellRenderer:nt(s=>s.value==null?null:e.jsx($,{value:s.value,suffix:"%"}))}),Kr=[{headerName:"Запрос",field:"text",filter:"agTextColumnFilter",filterParams:{debounceMs:500},floatingFilter:!0,minWidth:250,cellRenderer:nt(t=>e.jsx(U,{value:t.value,routerLink:`/search-queries/${encodeURIComponent(t.value)}`}))},De("Частота","count"),De("Пред. частота","prev_count"),Vr("Предмет","subject",{minWidth:160}),De("Просмотры","views"),De("В корзину","added"),Pt("В корзину, %","added_conv"),De("Заказы","orders"),Pt("Заказы, %","orders_conv"),De("Предметов","subjects")],Zr=t=>Array.from({length:t},(n,s)=>({_id:s}));function Yr({rowData:t,loading:n,onFilterChanged:s,onSortChanged:a}){const r=i.useRef(qr);!n&&t.length&&(r.current=t.length);const l=i.useMemo(()=>n?Zr(r.current):t,[n,t]),c=i.useMemo(()=>({loading:n}),[n]),h=i.useCallback(d=>{if(!s)return;const p=d.api.getFilterModel(),u=Ur(p);s(u)},[s]),o=i.useCallback(d=>{if(!a)return;const p=d.api.getColumnState().filter(u=>u.sort).map(u=>u.sort==="desc"?`-${u.colId}`:u.colId);a(p.length?p.join(","):null)},[a]);return e.jsx("div",{style:{width:"100%"},children:e.jsx(ce,{domLayout:"autoHeight",rowHeight:we,headerHeight:Ce,floatingFiltersHeight:Or,rowData:l,columnDefs:Kr,context:c,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!0,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:de,headerComponentParams:{enableSorting:!0,wrapText:!0}},onGridReady:d=>{d.api.sizeColumnsToFit()},onGridSizeChanged:d=>{d.api.sizeColumnsToFit()},onFilterChanged:h,onSortChanged:o,noRowsOverlayComponent:ue})})}const{Title:Qr}=S,Xr="wbstat/queries",Jr=[50,100,200],ei=[{label:"День",value:"yesterday"},{label:"Неделя",value:"week"},{label:"Месяц",value:"month"}];function ti(){const[t,n]=i.useState([]),[s,a]=i.useState(!0),[r,l]=i.useState("week"),[c,h]=i.useState({}),[o,d]=i.useState(null),[p,u]=i.useState(1),[f,m]=i.useState(100),[y,_]=i.useState(0),{showRequestError:j}=A(),T=i.useCallback(I=>{a(!0),G(`${Xr}/`,{params:I}).then(Z=>{n(Z.data.results),_(Z.data.count)}).catch(Z=>{j(Z)}).finally(()=>{a(!1)})},[j]);i.useEffect(()=>{const I={...c,period:r,page:p,page_size:f};o&&(I.ordering=o),T(I)},[c,r,o,p,f]);const b=i.useCallback(I=>{l(I.target.value),u(1)},[]),w=i.useCallback(I=>{h(I),u(1)},[]),F=i.useCallback(I=>{d(I),u(1)},[]),k=i.useCallback(I=>{u(I)},[]),L=i.useCallback(I=>{m(I),u(1)},[]);return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(Qr,{level:3,style:{margin:0},children:"Поисковые запросы"}),e.jsx(X.Group,{options:ei,value:r,onChange:b,optionType:"button",buttonStyle:"solid"}),e.jsx(Yr,{rowData:t,loading:s,onFilterChanged:w,onSortChanged:F}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:12},children:[e.jsx(ut,{current:p,total:y,pageSize:f,onChange:k,showSizeChanger:!1,showTotal:I=>`Всего ${I}`}),e.jsx(ee,{value:f,onChange:L,options:Jr.map(I=>({value:I,label:`${I} / стр`})),style:{width:110}})]})]})}const $t=[{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]}],ni=["queries_week","queries_month"];function si(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 ai(t){return t?new Date(t).toLocaleDateString("ru-RU",{day:"2-digit",month:"2-digit"}):""}function ri({data:t}){const[n,s]=i.useState(ni),a=i.useMemo(()=>[...t].sort((o,d)=>new Date(o.period_start)-new Date(d.period_start)),[t]),r=i.useMemo(()=>a.map(o=>ai(o.period_start)),[a]),l=i.useCallback((o,d)=>{s(p=>d?[...p,o]:p.filter(u=>u!==o))},[]),c=i.useMemo(()=>$t.filter(o=>n.includes(o.key)),[n]),h=i.useMemo(()=>{const o=c.map((p,u)=>({type:"log",name:p.name,nameTextStyle:{color:p.color,fontSize:11},position:u%2===0?"left":"right",offset:Math.floor(u/2)*70,axisLine:{show:!0,lineStyle:{color:p.color}},axisLabel:{fontSize:11,color:p.color,formatter:si},splitLine:{show:u===0}})),d=c.map((p,u)=>({name:p.name,type:"line",yAxisIndex:u,data:a.map(f=>f[p.key]||null),smooth:!0,symbol:"none",lineStyle:{width:2,color:p.color},itemStyle:{color:p.color}}));return{tooltip:{trigger:"axis",axisPointer:{type:"cross"}},grid:{left:20+Math.floor(c.filter((p,u)=>u%2===0).length/1)*35,right:20+Math.floor(c.filter((p,u)=>u%2!==0).length/1)*35,top:40,bottom:30,containLabel:!0},xAxis:{type:"category",data:r,axisLabel:{fontSize:11}},yAxis:o.length>0?o:[{type:"log"}],series:d}},[c,a,r]);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:$t.map(o=>e.jsx(Ze,{checked:n.includes(o.key),onChange:d=>l(o.key,d.target.checked),style:{color:o.color,fontWeight:500},children:e.jsx("span",{style:{color:o.color},children:o.name})},o.key))}),e.jsx(Kt,{option:h,style:{height:400},notMerge:!0})]})}je.setLicenseKey("key");be.registerModules([Se]);const ii=10,li=()=>e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"4px 8px",width:"100%",height:"100%"},children:e.jsx(q.Input,{active:!0,size:"small",block:!0,style:{height:20,minWidth:0}})}),We=t=>n=>{var s;return(s=n.context)!=null&&s.loading?e.jsx(li,{}):t(n)};function oi(t){return t?new Date(t).toLocaleDateString("ru-RU"):""}const ci=[{headerName:"Период",field:"period_start",minWidth:120,cellRenderer:We(t=>e.jsx(U,{value:oi(t.value)}))},{headerName:"Запросы (неделя)",field:"queries_week",minWidth:140,cellRenderer:We(t=>e.jsx($,{value:t.value}))},{headerName:"Запросы (месяц)",field:"queries_month",minWidth:140,cellRenderer:We(t=>e.jsx($,{value:t.value}))},{headerName:"Товаров в выдаче",field:"items_count",minWidth:140,cellRenderer:We(t=>e.jsx($,{value:t.value}))},{headerName:"Запросов вчера",field:"yesterday_count",minWidth:140,cellRenderer:We(t=>e.jsx($,{value:t.value}))}],di=t=>Array.from({length:t},(n,s)=>({_id:s}));function ui({rowData:t,loading:n}){const s=i.useRef(ii);!n&&t.length&&(s.current=t.length);const a=i.useMemo(()=>n?di(s.current):t,[n,t]),r=i.useMemo(()=>({loading:n}),[n]);return e.jsx("div",{style:{width:"100%"},children:e.jsx(ce,{domLayout:"autoHeight",rowHeight:we,headerHeight:Ce,rowData:a,columnDefs:ci,context:r,defaultColDef:{suppressHeaderMenuButton:!0,sortable:!1,suppressMovable:!0,resizable:!0,suppressHeaderFilterButton:!0,suppressFloatingFilterButton:!0,headerComponent:de},onGridReady:l=>{l.api.sizeColumnsToFit()},onGridSizeChanged:l=>{l.api.sizeColumnsToFit()},noRowsOverlayComponent:ue})})}const{Title:hi}=S,pi="wbstat/phrase_analysis",fi=[{label:"День",value:"day"},{label:"Неделя",value:"week"},{label:"Месяц",value:"month"}];async function xi(t,n){let s=1,a=[],r=null;for(;;){const l=await G(`${pi}/`,{params:{query:t,period:n,page:s,page_size:20}}),{results:c,next:h,cluster_summary:o}=l.data;if(a=a.concat(c),o&&(r=o),!h)break;s++}return{results:a,clusterSummary:r}}function mi(){var u,f;const{query:t}=Zt(),[n,s]=i.useState([]),[a,r]=i.useState(null),[l,c]=i.useState(!0),[h,o]=i.useState("week"),{showRequestError:d}=A(),p=i.useCallback(()=>{c(!0),xi(t,h).then(({results:m,clusterSummary:y})=>{s(m),r(y)}).catch(m=>d(m)).finally(()=>c(!1))},[t,h]);return i.useEffect(()=>{p()},[p]),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12},children:[e.jsx(O,{to:"/search-queries",children:e.jsx(Yt,{style:{fontSize:20,color:"#383540"}})}),e.jsx(hi,{level:3,style:{margin:0},children:l&&!n.length?e.jsx(Le,{size:"small"}):`Анализ фразы: ${t}`})]}),e.jsx(X.Group,{options:fi,value:h,onChange:m=>o(m.target.value),optionType:"button",buttonStyle:"solid"}),a&&!l&&e.jsx("div",{style:{background:"#fff",borderRadius:8,padding:16,border:"1px solid #EFF1F5"},children:e.jsxs(Te,{title:"Кластер",size:"small",column:{xs:1,sm:2,md:3},children:[e.jsx(Te.Item,{label:"Фраза",children:a.text}),e.jsx(Te.Item,{label:"Норм. фраза",children:a.norm_text}),e.jsx(Te.Item,{label:"Запросы (неделя)",children:(u=a.cluster_week_count)==null?void 0:u.toLocaleString("ru-RU")}),e.jsx(Te.Item,{label:"Запросы (месяц)",children:(f=a.cluster_month_count)==null?void 0:f.toLocaleString("ru-RU")}),e.jsx(Te.Item,{label:"Обновлено",children:a.updated_at})]})}),!l&&n.length>0&&e.jsx(ri,{data:n}),e.jsx(ui,{rowData:n,loading:l})]})}function gi(){const t=Oe(),{getProfile:n}=re(),{showRequestError:s}=A();return i.useEffect(()=>{Me.handleCallback().then(()=>{const a=Me.accessToken;return ve("user/wb-login",{access_token:a})}).then(a=>{var r;((r=a.data)==null?void 0:r.is_new)===!0&&ym(107086743,"reachGoal","ym-register")}).then(()=>n()).then(()=>{const a=sessionStorage.getItem("wb_key");if(a)return sessionStorage.removeItem("wb_key"),ve("user/key-check",{key:a}).then(()=>n()).catch(()=>{})}).then(()=>{const a=localStorage.getItem("auth_redirect");a?(localStorage.removeItem("auth_redirect"),t(a,{replace:!0})):t("/")}).catch(a=>{console.error("WB ID callback error:",a),s(a),t("/auth/login")})},[]),e.jsx(et,{})}const yi=()=>{const[t]=vt();return i.useEffect(()=>{const n=t.get("key");n&&sessionStorage.setItem("wb_key",n),Me.login()},[]),e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",minHeight:"calc(100vh - 200px)"},children:e.jsx(Le,{size:"large"})})};function _i(t){return t?new Date(t).toLocaleDateString("ru-RU",{day:"numeric",month:"short",year:"numeric"}):""}function vi(t){return!!(t!=null&&t.official_response)}function Wt({wishId:t,open:n,onVote:s,onLoad:a,variant:r="sidebar"}){const[l,c]=i.useState(null),[h,o]=i.useState(!1),{showRequestError:d}=A(),{resolution:p}=i.useContext(tt);i.useEffect(()=>{n&&t?(o(!0),W(`wishes/${t}`).then(T=>{c(T.data),a==null||a(T.data)}).catch(T=>{d(T)}).finally(()=>{o(!1)})):n||c(null)},[n,t]);const u=()=>{l!=null&&l.has_voted||s(t).then(T=>{T!=null&&T.has_voted&&c(b=>b&&{...b,votes_count:T.votes_count,has_voted:!0})}).catch(()=>{})},f=l?_i(l.created_at):"",m=l?l.votes_count>0||l.has_voted:!1,y=r==="sheet",_=r==="sidebar"&&p>le.Tablet;if(!n)return null;const j={display:"flex",flexDirection:"column",gap:16,...y?{}:_?{maxHeight:"calc(100vh - 96px)",overflowY:"auto",position:"sticky",top:72}:{}};return e.jsx("div",{style:j,children:h?e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",minHeight:220},children:e.jsx(Le,{})}):l?e.jsxs(e.Fragment,{children:[e.jsx("h2",{style:{fontSize:y?24:28,fontWeight:400,lineHeight:1.2,margin:0},children:l.title}),e.jsx(Qt,{color:g.greyF[700],style:{margin:0,borderRadius:4,alignSelf:"flex-start"},children:l.status}),e.jsx(ne,{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(E,{size:"small",icon:e.jsx(Xt,{}),disabled:l.has_voted,onClick:u,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:m?l.votes_count:null}),vi(l)?e.jsxs(e.Fragment,{children:[e.jsx(ne,{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(Jt,{style:{fontSize:14,color:g.greyF[700]}}),"Есть ответ"]})]}):null,e.jsx(ne,{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:ji}=V,bi=50,Si=500;function At({onClose:t,onSubmit:n,variant:s="inline"}){const[a,r]=i.useState(""),[l,c]=i.useState(""),[h,o]=i.useState(!1),d=()=>{!a.trim()||!l.trim()||h||(o(!0),n({title:a.trim(),description:l.trim()}).then(()=>{r(""),c(""),t()}).catch(()=>{}).finally(()=>{o(!1)}))},p=()=>{h||(r(""),c(""),t())},u=a.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(V,{placeholder:"Кратко опишите идею",value:a,onChange:m=>r(m.target.value),maxLength:bi,showCount:!0,disabled:h})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsx("span",{style:{fontSize:14,fontWeight:500},children:"Описание"}),e.jsx(ji,{placeholder:"Подробно опишите вашу идею",value:l,onChange:m=>c(m.target.value),maxLength:Si,showCount:!0,rows:5,disabled:h,style:{resize:"none"}})]})]}),e.jsxs("div",{style:{display:"flex",gap:10,marginTop:f?"auto":4,paddingBottom:f?20:0},children:[e.jsxs(oe,{variant:"contained",onClick:d,disabled:!u||h,sx:{flex:f?1:void 0,minWidth:f?void 0:226,height:40,fontSize:14,padding:"0 20px"},children:[e.jsx(en,{}),h?"Отправка...":"Предложить"]}),e.jsx(E,{onClick:p,disabled:h,icon:e.jsx(mt,{}),style:{width:56,height:40},"aria-label":f?"Закрыть форму":"Закрыть форму создания"})]})]})}const{Title:zt}=S,Nt=[{label:"Все",value:"all"},{label:"Новые",value:"Новое"},{label:"Запланировано",value:"Запланировано"},{label:"Сделано",value:"Сделано"}],Ci=[{label:"Все теги",value:"all"},{label:"Новые",value:"Новое"},{label:"Запланировано",value:"Запланировано"},{label:"Сделано",value:"Сделано"}],Ht=[{label:"Больше голосов",value:"most_votes"},{label:"Меньше голосов",value:"least_votes"},{label:"Сначала новые",value:"newest"},{label:"Сначала старые",value:"oldest"}],Ae=20;function wi(t){return t?new Date(t).toLocaleDateString("ru-RU",{day:"numeric",month:"short",year:"numeric"}):""}function ki(t){return!!(t!=null&&t.official_response)}function dt(t,n){return n!=null&&n.id?t.map(s=>s.id===n.id?{...s,...n}:s):t}function Ti(){const[t,n]=i.useState([]),[s,a]=i.useState(!0),[r,l]=i.useState("all"),[c,h]=i.useState("most_votes"),[o,d]=i.useState(1),[p,u]=i.useState(0),[f,m]=i.useState(null),[y,_]=i.useState(!1),{showMessage:j,showRequestError:T}=A(),{resolution:b}=i.useContext(tt),w=b<=le.Tablet,F=i.useRef(new Map),k=i.useRef(new Set),L=x=>(x!=null&&x.id&&F.current.set(x.id,x),x),I=x=>{const v=F.current.get(x.id);return v?{...x,...v}:x};i.useEffect(()=>{let x=!0;a(!0);const v={ordering:c,page:o,limit:Ae};return r!=="all"&&(v.status=r),W("wishes",{params:v}).then(C=>{if(!x)return;const R=C.data.results.map(I);n(R),u(C.data.count);const D=R.filter(M=>!M.description&&!k.current.has(M.id));D.length!==0&&(D.forEach(M=>{k.current.add(M.id)}),Promise.allSettled(D.map(M=>W(`wishes/${M.id}`))).then(M=>{if(!x)return;const N=M.reduce((te,ge,ke)=>{const $e=D[ke].id;return k.current.delete($e),ge.status==="fulfilled"&&te.push(L(ge.value.data)),te},[]);N.length>0&&n(te=>N.reduce((ge,ke)=>dt(ge,ke),te))}))}).catch(C=>{x&&T(C)}).finally(()=>{x&&a(!1)}),()=>{x=!1}},[r,c,o]),i.useEffect(()=>{if(!f)return;t.some(v=>v.id===f)||m(null)},[f,t]),i.useEffect(()=>{if(w&&(y||f))return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[w,y,f]);const Z=x=>{l(x),d(1)},pe=x=>{h(x),d(1)},fe=x=>{_(!1),m(v=>v===x.id?null:x.id)},P=x=>ve("wishes",x).then(()=>{_(!1),j("Идея отправлена на модерацию")}).catch(v=>{throw T(v),v}),z=x=>{const v=t.find(C=>C.id===x);return v!=null&&v.has_voted?Promise.resolve({has_voted:!0,votes_count:v.votes_count}):ve(`wishes/${x}/vote`).then(C=>(n(R=>R.map(D=>D.id===x?{...D,votes_count:C.data.votes_count,has_voted:!0}:D)),j("Ваш голос учтён!"),{has_voted:!0,votes_count:C.data.votes_count})).catch(C=>{var R,D,M;if(((R=C.response)==null?void 0:R.status)===400&&((M=(D=C.response)==null?void 0:D.data)!=null&&M.detail)){if(j(C.response.data.detail),C.response.data.has_voted)return n(N=>N.map(te=>te.id===x?{...te,votes_count:C.response.data.votes_count,has_voted:!0}:te)),{has_voted:!0,votes_count:C.response.data.votes_count}}else T(C);throw C})},se=!!f&&!y&&!w,xe=b<=le.Tablet,me=i.useRef(null),[Pe,st]=i.useState(!1),at=i.useCallback(x=>{if(me.current=x,!x)return;const v=new ResizeObserver(([C])=>{st(C.contentRect.width<600)});return v.observe(x),()=>v.disconnect()},[]),rt=se?{display:"grid",gap:16,gridTemplateColumns:b>=le.Large?"693px minmax(0, 687px)":b>le.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"},it={alignItems:"flex-start",display:"flex",gap:10,justifyContent:"space-between",...b<=le.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(ee,{options:Ci,value:r,onChange:Z,variant:"filled",style:{flex:"0 0 146px"}}),e.jsx(ee,{options:Ht,value:c,onChange:pe,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(Ot,{loading:s,onVote:z,onWishClick:fe,selectedWishId:f,wishes:t}),p>Ae?e.jsx("div",{style:{display:"flex",justifyContent:"center",marginTop:4},children:e.jsx(ut,{current:o,total:p,pageSize:Ae,onChange:d,showSizeChanger:!1})}):null]}),e.jsx(Hn,{type:"primary",icon:e.jsx(On,{style:{fontSize:24}}),onClick:()=>{m(null),_(!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:rt,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:y?e.jsx(At,{onClose:()=>_(!1),onSubmit:P}):e.jsxs(oe,{variant:"outlined",onClick:()=>{m(null),_(!0)},sx:{height:36,fontSize:13,padding:"0 16px",alignSelf:"flex-start"},children:[e.jsx(en,{}),"Предложить идею"]})}),e.jsx(ne,{style:{margin:0}}),e.jsxs("div",{ref:at,style:it,children:[Pe?e.jsx(ee,{options:Nt,value:r,onChange:Z,variant:"filled",style:{flex:"0 0 146px"}}):e.jsx(X.Group,{options:Nt,value:r,onChange:x=>Z(x.target.value),optionType:"button",buttonStyle:"solid"}),e.jsx(ee,{options:Ht,value:c,onChange:pe,variant:"filled",style:{minWidth:180}})]}),e.jsx(Ot,{loading:s,onVote:z,onWishClick:fe,selectedWishId:f,wishes:t}),p>Ae?e.jsx("div",{style:{display:"flex",justifyContent:"center",marginTop:4},children:e.jsx(ut,{current:o,total:p,pageSize:Ae,onChange:d,showSizeChanger:!1})}):null]}),se?e.jsx("div",{style:{alignSelf:"stretch",minWidth:0,overflowY:"auto",...xe?{borderTop:`1px solid ${g.greyF[100]}`,paddingTop:16}:{borderLeft:`1px solid ${g.greyF[100]}`,paddingLeft:16}},children:e.jsx(Wt,{wishId:f,open:se,onLoad:x=>{L(x),n(v=>dt(v,x))},onVote:z,variant:"sidebar"})}):null]})]})}),e.jsxs("div",{style:{position:"fixed",inset:0,zIndex:1e3,pointerEvents:"none"},children:[e.jsx(St,{open:w&&y,onClose:()=>_(!1),placement:"bottom",height:"75%",closable:!1,getContainer:!1,rootStyle:{pointerEvents:y?"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(At,{onClose:()=>_(!1),onSubmit:P,variant:"sheet"})}),e.jsx(St,{open:w&&!!f,onClose:()=>m(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(Wt,{wishId:f,open:!!f,onLoad:x=>{L(x),n(v=>dt(v,x))},onVote:z,variant:"sheet"})})]})]})}function Ot({wishes:t,loading:n,selectedWishId:s,onWishClick:a,onVote:r}){return n?e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:Array.from({length:5}).map((l,c)=>e.jsx(q,{active:!0,paragraph:{rows:2}},`wish-skeleton-${c}`))}):t.length===0?e.jsx(ye,{description:"Нет идей для отображения"}):e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:t.map(l=>e.jsx(Fi,{onClick:()=>a(l),onVote:r,selected:l.id===s,wish:l},l.id))})}function Fi({wish:t,selected:n,onClick:s,onVote:a}){const r=wi(t.created_at),l=t.votes_count>0||t.has_voted,c=ki(t);return e.jsxs(qn,{hoverable:!0,role:"button",tabIndex:0,onClick:s,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.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(Qt,{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(E,{size:"small",icon:e.jsx(Xt,{}),disabled:t.has_voted,onClick:h=>{h.stopPropagation(),a(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}),c?e.jsxs(e.Fragment,{children:[e.jsx(ne,{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(Jt,{style:{fontSize:14,color:g.greyF[700]}}),"Есть ответ"]})]}):null,e.jsx(ne,{type:"vertical",style:{margin:0}}),e.jsx("span",{style:{fontSize:14,lineHeight:1.2},children:r})]})]})}const Ii=Bn([{element:e.jsx(Ss,{}),path:"/",children:[{path:"/",index:!0,element:e.jsx(ns,{})},{path:"/auth/login",element:e.jsx(rn,{})},{path:"/auth/logout",element:e.jsx(Ra,{})},{path:"/auth/wblogin",element:e.jsx(yi,{})},{path:"/auth/ext-auth",element:e.jsx(mn,{})},{path:"/wb-id-sdk/callback",element:e.jsx(gi,{})},{path:"/profile",element:e.jsx(Ia,{})},{path:"/devices",element:e.jsx(xn,{})},{path:"/campaigns/:campaignId/bidder",element:e.jsx(As,{})},{path:"/campaigns/:campaignId",element:e.jsx(Js,{})},{path:"/campaigns",element:e.jsx(ps,{})},{path:"/subjects/:subjectId",element:e.jsx(Rs,{})},{path:"/subjects",element:e.jsx(Is,{})},{path:"/priority-subjects/:subjectId",element:e.jsx(Cs,{})},{path:"/priority-subjects",element:e.jsx(ks,{})},{path:"/suppliers",element:e.jsx(Zs,{})},{path:"/search-auction",element:e.jsx(ya,{})},{path:"/external-analytics/niche-analysis/:subjectId",element:e.jsx(cr,{})},{path:"/external-analytics/niche-analysis",element:e.jsx(Ka,{})},{path:"/external-analytics/category-analysis",element:e.jsx(jr,{})},{path:"/external-analytics/category-matrix",element:e.jsx(Dr,{})},{path:"/external-analytics/subject-matrix",element:e.jsx(Hr,{})},{path:"/search-queries",element:e.jsx(ti,{})},{path:"/search-queries/:query",element:e.jsx(mi,{})},{path:"/wishes",element:e.jsx(Ti,{})}]}]);function Ri(){return e.jsx(Gn,{router:Ii})}function Di(){return e.jsx(e.Fragment,{children:e.jsx(Ri,{})})}Un.createRoot(document.getElementById("root")).render(e.jsx(Vt.StrictMode,{children:e.jsx(Vn,{theme:Yn,children:e.jsx(ua,{children:e.jsx(Jn,{children:e.jsx(ms,{children:e.jsx(Di,{})})})})})}));