1import{b as Be,r as o,s as f,j as s}from"./site-C5SUB8ov.js";import{u as qe,bT as g,bo as Te,c as _,L as q,A as Ke,b2 as ze,bp as Ve,k as Ye,D as Ge,t as He,U as pe,w as he,aK as Je}from"./main-_fPdXjGG.js";const H="/.netlify/functions/kommo-fetch-deals",fe=["Selling price EUR netto","Selling price EUR","ЦÑна пÑÐ¾Ð´Ð°Ð¶Ñ EUR","Selling price"],Qe=["Paid amount","ÐплаÑено"];function We(t){return t?new Date(t).toLocaleDateString("uk-UA",{day:"2-digit",month:"2-digit",year:"numeric"}):"â"}function Xe(t){return new Intl.NumberFormat("uk-UA",{style:"currency",currency:"EUR",minimumFractionDigits:0,maximumFractionDigits:2}).format(t)}function Ze(t){const i=(t.name||"").toLowerCase(),u=t.tags.map(P=>P.toLowerCase()).join(" "),y=t.custom_fields,k=String(y.Format||y.format||"").toLowerCase(),D=String(y["Type of deal"]||y["Тип Ñгоди"]||"").toLowerCase(),c=`${i} ${u} ${k} ${D}`;return c.includes("premium")?"Premium":c.includes("standard+")||c.includes("standart+")?"Standard+":c.includes("flex")?"Flex":c.includes("mini")?"Mini":c.includes("вживан")||c.includes("used")?"Ðживана":(c.includes("standard")||c.includes("standart"),"Standard")}function _e(t){return String(t||"").toLowerCase().replace(/\s+/g," ").trim()}function T(t){if(typeof t=="number")return Number.isFinite(t)?t:0;if(t==null)return 0;let i=String(t).trim();if(!i)return 0;i=i.replace(/\u00A0/g,"").replace(/\s+/g,"");const u=i.includes(","),y=i.includes(".");u&&y?i.lastIndexOf(",")>i.lastIndexOf(".")?i=i.replace(/\./g,"").replace(",","."):i=i.replace(/,/g,""):u&&(i=i.replace(",",".")),i=i.replace(/[^0-9.-]/g,"");const k=Number.parseFloat(i);return Number.isFinite(k)?k:0}function J(t,i,u=0){if(!t)return T(u);const y=new Set(i.map(_e));for(const[k,D]of Object.entries(t))if(y.has(_e(k))){const c=T(D);return Number.isFinite(c)?c:T(u)}return T(u)}function ts(){const{t}=qe(),{companyId:i}=Be(),[u,y]=o.useState([]),[k,D]=o.useState([]),[c,P]=o.useState(!1),[w,ye]=o.useState([]),[F,Q]=o.useState([142]),[K,be]=o.useState(!1),[E,W]=o.useState([]),[z,X]=o.useState(!1),[V,ke]=o.useState([]),[I,Z]=o.useState({}),[N,ee]=o.useState({}),[se,te]=o.useState({}),[S,ae]=o.useState({}),[$,ne]=o.useState([]),[re,oe]=o.useState(!1),[ie,le]=o.useState(!1),[me,ce]=o.useState({}),[L,we]=o.useState(""),[A,je]=o.useState(""),[M,Ne]=o.useState("");o.useEffect(()=>{de(),ve(),Se(),Ce()},[]);const de=async()=>{P(!0);try{const a=await(await fetch(`${H}?action=pipelines`)).json();if(a.error)throw new Error(a.error);y(a.pipelines||[])}catch(e){g.error(t("admin.kommo.common.loadPipelinesError",{message:e instanceof Error?e.message:String(e)}))}finally{P(!1)}},Se=async()=>{try{const a=await(await fetch(`${H}?action=users`)).json();a.error||D(a.users||[])}catch(e){console.error("Failed to load Kommo users:",e)}},ve=async()=>{try{const{data:e,error:a}=await f.from("sales_manager_settings").select("user_id, manager_name, is_active").order("manager_name");if(a)throw a;ke(e||[])}catch{g.error(t("admin.kommo.common.loadManagersError"))}},Ce=async()=>{if(i)try{oe(!0);const{data:e,error:a}=await f.from("company_members").select("user_id").eq("company_id",i);if(a)throw a;const l=Array.from(new Set((e||[]).map(n=>n.user_id))).filter(Boolean);if(l.length===0){ne([]);return}const[x,r]=await Promise.all([f.from("user_profiles").select("user_id, first_name, last_name, email, fakturownia_client_id").in("user_id",l),f.from("user_profiles_fakturownia_clients").select("user_id, fakturownia_client_id").in("user_id",l)]);if(x.error)throw x.error;if(r.error)throw r.error;const d=(r.data||[]).reduce((n,m)=>{if(!m.user_id||!m.fakturownia_client_id)return n;const p=n.get(m.user_id)||[];return p.push(m.fakturownia_client_id),n.set(m.user_id,p),n},new Map),R=(x.data||[]).map(n=>{var U;const m=(n.first_name||"").trim(),p=(n.last_name||"").trim(),G=`${m} ${p}`.trim()||n.email||n.user_id,O=((U=n.fakturownia_client_id)==null?void 0:U.trim())||null,B=(d.get(n.user_id)||[]).find(C=>C==null?void 0:C.trim()),h=O||B||null;return{user_id:n.user_id,display_name:G,email:n.email||null,fakturownia_client_id:h,has_fakturownia_mapping:!!h}}).sort((n,m)=>n.display_name.localeCompare(m.display_name,"uk-UA"));ne(R)}catch(e){console.error("Failed to load client options:",e),g.error(t("admin.kommo.common.loadFranchiseesError"))}finally{oe(!1)}},De=async()=>
1{if(w.length===0){g.error(t("admin.kommo.common.selectPipeline"));return}X(!0),W([]);try{const e=new URLSearchParams({action:"deals",pipeline_ids:w.join(","),status_ids:F.join(",")}),l=await(await fetch(`${H}?${e}`)).json();if(l.error)throw new Error(l.error);const x=l.deals||[];W(x);const r={};x.forEach(d=>{r[d.id]=Ze(d)}),te(r),g.success(t("admin.kommo.common.dealsLoaded",{count:x.length}))}catch(e){g.error(t("admin.kommo.common.fetchError",{message:e instanceof Error?e.message:String(e)}))}finally{X(!1)}},Fe=o.useMemo(()=>{const e=new Map;return k.forEach(a=>e.set(a.id,a.name)),e},[k]),Ee=o.useMemo(()=>{const e=new Map;return u.forEach(a=>e.set(a.id,a.name)),e},[u]),j=o.useMemo(()=>{if(!L.trim())return E;const e=L.toLowerCase();return E.filter(a=>(a.name||"").toLowerCase().includes(e)||(a.contact_name||"").toLowerCase().includes(e)||String(a.id).includes(e)||(a.tags||[]).some(l=>l.toLowerCase().includes(e)))},[E,L]),b=o.useMemo(()=>Object.values(S).filter(Boolean).length,[S]),ue=o.useMemo(()=>{const e=new Map;return $.forEach(a=>e.set(a.user_id,a)),e},[$]),Ie=e=>{ye(a=>a.includes(e)?a.filter(l=>l!==e):[...a,e])},Le=e=>{Q(a=>a.includes(e)?a.filter(l=>l!==e):[...a,e])},Y=e=>{const a={};j.forEach(l=>{a[l.id]=e}),ae(a)},Ae=()=>{if(!A)return;const e={...I};j.forEach(a=>{S[a.id]&&(e[a.id]=A)}),Z(e),g.success(t("admin.kommo.common.managerAssigned",{count:b}))},Me=()=>{if(!M)return;const e={...N};j.forEach(a=>{S[a.id]&&(e[a.id]=M)}),ee(e),g.success(t("admin.kommo.common.franchiseeAssigned",{count:b}))},Ue=async()=>{const e=j.filter(n=>S[n.id]&&!me[n.id]);if(e.length===0){g.error(t("admin.kommo.common.noDealsToSave"));return}const a=e.filter(n=>!I[n.id]).length;if(a>0){g.error(t("admin.kommo.common.selectManagerForAll",{count:a}));return}const l=e.filter(n=>!N[n.id]).length;if(l>0){g.error(t("admin.kommo.common.selectFranchiseeForAll",{count:l}));return}const x=e.filter(n=>{var p;const m=N[n.id];return m?!((p=ue.get(m))!=null&&p.has_fakturownia_mapping):!1}).length;if(x>0){g.error(t("admin.kommo.common.missingFakturownia",{count:x}));return}const r=e;le(!0);let d=0,R=0;for(const n of r){const m=I[n.id],p=N[n.id],G=se[n.id]||"Standard",O=n.closed_at?n.closed_at.split("T")[0]:new Date().toISOString().split("T")[0],B=O.slice(0,7)+"-01";try{let{data:h}=await f.from("sales_manager_reports").select("id").eq("user_id",m).eq("report_month",B).single();if(!h){const v=V.find(Oe=>Oe.user_id===m),{data:Re,error:ge}=await f.from("sales_manager_reports").insert({user_id:m,manager_name:(v==null?void 0:v.manager_name)||"Unknown",report_month:B,hours_worked:0,total_payments:0,total_additional_payments:0,installations_count:0,mini_installations_count:0,sales_bonus:0,fixed_bonus:0,paid_first_half:0,paid_second_half:0}).select("id").single();if(ge)throw ge;h=Re}const{data:U}=await f.from("sales_manager_sales").select("id").eq("report_id",h.id).eq("kommo_lead_id",String(n.id)).maybeSingle();if(U){await f.from("sales_manager_sales").update({client_user_id:p,crm_link_normalized:(n.crm_link||"").trim()||null}).eq("id",U.id),await f.from("kommo_leads").update({processed:!0,processed_at:new Date().toISOString(),manager_user_id:m,sales_report_id:h.id,client_user_id:p}).eq("kommo_lead_id",String(n.id)),ce(v=>({...v,[n.id]:!0})),d++;continue}const C=J(n.custom_fields,fe,n.price||0),$e=J(n.custom_fields,Qe,C),{error:xe}=await f.from("sales_manager_sales").insert({report_id:h.id,sale_date:O,client_name:n.contact_name||n.name||`Deal #${n.id}`,client_link:n.crm_link,sale_type:G,sale_price:C,paid_amount:$e,client_user_id:p,kommo_lead_id:String(n.id),crm_link_normalized:(n.crm_link||"").trim()||null});if(xe)throw xe;await f.from("kommo_leads").update({processed:!0,processed_at:new Date().toISOString(),manager_user_id:m,sales_report_id:h.id,client_user_id:p}).eq("kommo_lead_id",String(n.id)),ce(v=>({...v,[n.id]:!0})),d++}catch(h){console.error(`Failed to save deal ${n.id}:`,h),R++}}g.success(t("admin.kommo.common.savedResult",{ok:d,failed:R})),le(!1)},Pe=o.useMemo(()=>{const e=[];return u.forEach(a=>{w.includes(a.id)&&e.push(...a.statuses)}),e},[u,w]);return s.jsxs("div",{className:"space-y-6",children:[s.jsxs("div",{className:"bg-white border border-gray-200 rounded-lg p-4",children:[s.jsx("h1",{className:"text-lg font-semibold text-gray-900",children:t("admin.kommoDeals.title")}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:t("admin.kommoDeals.subtitle")})]}),s.jsxs("div",{className:"bg-white border border-gray-200 rounded-lg p-4 space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("h2",{className:"text-sm font-semibold text-gray-900",children:t("admin.kommoDeals.pipelinesSection")}
1),s.jsxs("button",{onClick:de,disabled:c,className:"text-sm text-gray-500 hover:text-gray-700 flex items-center gap-1",children:[s.jsx(Te,{className:_("w-3.5 h-3.5",c&&"animate-spin")}),t("admin.kommo.common.refresh")]})]}),c?s.jsxs("div",{className:"flex items-center gap-2 text-gray-500 text-sm py-4",children:[s.jsx(q,{className:"w-4 h-4 animate-spin"})," ",t("admin.kommo.common.loadingPipelines")]}):u.length===0?s.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm py-4",children:[s.jsx(Ke,{className:"w-4 h-4"}),t("admin.kommo.common.pipelinesEmpty")]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2",children:u.map(e=>s.jsxs("label",{className:_("flex items-center gap-2 p-3 border rounded-lg cursor-pointer transition-colors",w.includes(e.id)?"border-emerald-400 bg-emerald-50":"border-gray-200 hover:bg-gray-50"),children:[s.jsx("input",{type:"checkbox",checked:w.includes(e.id),onChange:()=>Ie(e.id),className:"accent-emerald-600"}),s.jsx("span",{className:"text-sm font-medium text-gray-900",children:e.name}),s.jsxs("span",{className:"text-xs text-gray-400 ml-auto",children:["ID: ",e.id]})]},e.id))}),w.length>0&&s.jsxs("div",{children:[s.jsxs("button",{onClick:()=>be(!K),className:"flex items-center gap-1 text-sm text-gray-600 hover:text-gray-800",children:[s.jsx(ze,{className:"w-3.5 h-3.5"}),t("admin.kommo.common.statusFilter"),K?s.jsx(Ve,{className:"w-3.5 h-3.5"}):s.jsx(Ye,{className:"w-3.5 h-3.5"})]}),K&&s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.jsx("button",{onClick:()=>Q([142]),className:_("px-3 py-1 text-xs rounded-full border",F.length===1&&F[0]===142?"border-emerald-400 bg-emerald-100 text-emerald-800":"border-gray-200 text-gray-600 hover:bg-gray-50"),children:t("admin.kommo.common.successOnly")}),Pe.map(e=>s.jsxs("label",{className:_("inline-flex items-center gap-1 px-3 py-1 text-xs rounded-full border cursor-pointer",F.includes(e.id)?"border-emerald-400 bg-emerald-50 text-emerald-800":"border-gray-200 text-gray-600 hover:bg-gray-50"),children:[s.jsx("input",{type:"checkbox",checked:F.includes(e.id),onChange:()=>Le(e.id),className:"hidden"}),e.name,s.jsxs("span",{className:"text-gray-400",children:["(",e.id,")"]})]},e.id))]})]})]}),s.jsxs("button",{onClick:De,disabled:z||w.length===0,className:_("inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg transition-colors",w.length>0?"bg-emerald-600 text-white hover:bg-emerald-700":"bg-gray-200 text-gray-500 cursor-not-allowed"),children:[z?s.jsx(q,{className:"w-4 h-4 animate-spin"}):s.jsx(Ge,{className:"w-4 h-4"}),t("admin.kommo.common.loadDeals")]})]}),E.length>0&&s.jsxs("div",{className:"bg-white border border-gray-200 rounded-lg overflow-hidden",children:[s.jsxs("div",{className:"p-4 border-b space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx(He,{className:"min-w-[240px] flex-1",value:L,onChange:we,placeholder:t("common.search"),title:t("admin.kommoDeals.searchTitle")}),s.jsxs("div",{className:"text-sm text-gray-500",children:[t("admin.kommoDeals.totalCount",{count:E.length}),L&&s.jsxs(s.Fragment,{children:[" · ",t("admin.kommoDeals.shownCount",{count:j.length})]})]})]}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx("button",{onClick:()=>Y(!0),className:"px-3 py-1.5 text-xs border border-gray-300 rounded-md hover:bg-gray-50",children:t("admin.kommo.common.selectAll")}),s.jsx("button",{onClick:()=>Y(!1),className:"px-3 py-1.5 text-xs border border-gray-300 rounded-md hover:bg-gray-50",children:t("admin.kommo.common.deselectAll")}),s.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[s.jsx(pe,{className:"w-4 h-4 text-gray-400"}),s.jsxs("select",{value:M,onChange:e=>Ne(e.target.value),className:"h-8 px-2 border border-gray-300 rounded-md text-sm",children:[s.jsx("option",{value:"",children:t(re?"admin.kommo.common.franchiseeLoading":"admin.kommo.common.franchiseeBulk")}),$.map(e=>s.jsxs("option",{value:e.user_id,children:[e.display_name,e.fakturownia_client_id?` [${e.fakturownia_client_id}]`:` ${t("admin.kommo.common.withoutFid")}`]},e.user_id))]}
1),s.jsx("button",{onClick:Me,disabled:!M||b===0,className:_("px-3 py-1.5 text-xs rounded-md",M&&b>0?"bg-sky-600 text-white hover:bg-sky-700":"bg-gray-200 text-gray-500 cursor-not-allowed"),children:t("admin.kommoDeals.franchiseeBulk",{count:b})}),s.jsx(pe,{className:"w-4 h-4 text-gray-400"}),s.jsxs("select",{value:A,onChange:e=>je(e.target.value),className:"h-8 px-2 border border-gray-300 rounded-md text-sm",children:[s.jsx("option",{value:"",children:t("admin.kommo.common.managerPlaceholder")}),V.filter(e=>e.is_active).map(e=>s.jsx("option",{value:e.user_id,children:e.manager_name},e.user_id))]}),s.jsx("button",{onClick:Ae,disabled:!A||b===0,className:_("px-3 py-1.5 text-xs rounded-md",A&&b>0?"bg-indigo-600 text-white hover:bg-indigo-700":"bg-gray-200 text-gray-500 cursor-not-allowed"),children:t("admin.kommoDeals.assign",{count:b})})]}),s.jsxs("button",{onClick:Ue,disabled:ie||b===0,className:_("inline-flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg",b>0?"bg-emerald-600 text-white hover:bg-emerald-700":"bg-gray-200 text-gray-500 cursor-not-allowed"),children:[ie?s.jsx(q,{className:"w-4 h-4 animate-spin"}):s.jsx(he,{className:"w-4 h-4"}),t("admin.kommo.common.saveToReports")]})]})]}),s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"min-w-full text-sm",children:[s.jsx("thead",{className:"bg-gray-50 border-b",children:s.jsxs("tr",{children:[s.jsx("th",{className:"px-3 py-2 text-left w-10",children:s.jsx("input",{type:"checkbox",checked:j.length>0&&j.every(e=>S[e.id]),onChange:e=>Y(e.target.checked)})}),s.jsx("th",{className:"px-3 py-2 text-left",children:t("admin.kommo.common.deal")}),s.jsx("th",{className:"px-3 py-2 text-left",children:t("admin.kommo.common.contact")}),s.jsx("th",{className:"px-3 py-2 text-left",children:t("admin.kommo.common.pipeline")}),s.jsx("th",{className:"px-3 py-2 text-left",children:t("admin.kommo.common.responsibleKommo")}),s.jsx("th",{className:"px-3 py-2 text-right",children:t("admin.kommo.common.amount")}),s.jsx("th",{className:"px-3 py-2 text-left",children:t("admin.kommo.common.closed")}),s.jsx("th",{className:"px-3 py-2 text-left",children:t("admin.kommo.common.format")}),s.jsx("th",{className:"px-3 py-2 text-left",children:t("admin.kommo.common.franchiseeFid")}),s.jsx("th",{className:"px-3 py-2 text-left",children:t("admin.kommo.common.managerIntouch")}),s.jsx("th",{className:"px-3 py-2 text-left w-10"})]})}),s.jsx("tbody",{children:j.map(e=>{var x;const a=me[e.id],l=J(e.custom_fields,fe,e.price||0);return s.jsxs("tr",{className:_("border-b hover:bg-gray-50",a&&"bg-emerald-50",S[e.id]&&!a&&"bg-indigo-50/30"),children:[s.jsx("td",{className:"px-3 py-2",children:s.jsx("input",{type:"checkbox",checked:!!S[e.id],disabled:a,onChange:r=>ae(d=>({...d,[e.id]:r.target.checked}))})}),s.jsxs("td",{className:"px-3 py-2",children:[s.jsx("div",{className:"font-medium text-gray-900 max-w-[200px] truncate",children:e.name||"â"}),s.jsxs("div",{className:"text-xs text-gray-400",children:["#",e.id]})]}),s.jsx("td",{className:"px-3 py-2 text-gray-700",children:e.contact_name||"â"}),s.jsx("td",{className:"px-3 py-2",children:s.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full bg-gray-100 text-gray-700",children:Ee.get(e.pipeline_id)||e.pipeline_id})}),s.jsx("td",{className:"px-3 py-2 text-gray-600 text-xs",children:Fe.get(e.responsible_user_id
1)||e.responsible_user_id||"â"}),s.jsx("td",{className:"px-3 py-2 text-right font-medium text-gray-900",children:Xe(l)}),s.jsx("td",{className:"px-3 py-2 text-gray-600 text-xs",children:We(e.closed_at)}),s.jsx("td",{className:"px-3 py-2",children:s.jsxs("select",{value:se[e.id]||"Standard",onChange:r=>te(d=>({...d,[e.id]:r.target.value})),disabled:a,className:"h-7 px-1 border border-gray-300 rounded text-xs",children:[s.jsx("option",{value:"Standard",children:"Standard"}),s.jsx("option",{value:"Standard+",children:"Standard+"}),s.jsx("option",{value:"Flex",children:"Flex"}),s.jsx("option",{value:"Premium",children:"Premium"}),s.jsx("option",{value:"Mini",children:"Mini"}),s.jsx("option",{value:"Ðживана",children:"Ðживана"})]})}),s.jsx("td",{className:"px-3 py-2",children:s.jsxs("div",{className:"space-y-1",children:[s.jsxs("select",{value:N[e.id]||"",onChange:r=>ee(d=>({...d,[e.id]:r.target.value})),disabled:a,className:_("h-7 px-1 border rounded text-xs w-full min-w-[170px]",N[e.id]?"border-sky-400 bg-sky-50":"border-gray-300"),children:[s.jsx("option",{value:"",children:t(re?"admin.kommo.common.loading":"admin.kommo.common.franchiseePlaceholder")}),$.map(r=>s.jsxs("option",{value:r.user_id,children:[r.display_name,r.fakturownia_client_id?` [${r.fakturownia_client_id}]`:` ${t("admin.kommo.common.withoutFid")}`]},r.user_id))]}),N[e.id]&&!((x=ue.get(N[e.id]))!=null&&x.has_fakturownia_mapping)&&s.jsx("div",{className:"text-[10px] text-amber-700",children:t("admin.kommo.common.fakturowniaRequired")})]})}),s.jsx("td",{className:"px-3 py-2",children:s.jsxs("select",{value:I[e.id]||"",onChange:r=>Z(d=>({...d,[e.id]:r.target.value})),disabled:a,className:_("h-7 px-1 border rounded text-xs w-full min-w-[140px]",I[e.id]?"border-emerald-400 bg-emerald-50":"border-gray-300"),children:[s.jsx("option",{value:"",children:t("admin.kommo.common.notSelected")}),V.filter(r=>r.is_active).map(r=>s.jsx("option",{value:r.user_id,children:r.manager_name},r.user_id))]})}),s.jsx("td",{className:"px-3 py-2",children:a?s.jsx(he,{className:"w-4 h-4 text-emerald-500"}):s.jsx("a",{href:e.crm_link,target:"_blank",rel:"noopener noreferrer",children:s.jsx(Je,{className:"w-4 h-4 text-gray-400 hover:text-indigo-600"})})})]},e.id)})})]})}),j.length===0&&s.jsx("div",{className:"py-8 text-center text-gray-500 text-sm",children:t("admin.kommo.common.noDealsDisplay")})]}),z&&s.jsxs("div",{className:"bg-white border border-gray-200 rounded-lg p-8 flex items-center justify-center gap-2 text-gray-600",children:[s.jsx(q,{className:"w-5 h-5 animate-spin"}),t("admin.kommo.common.loadingDeals")]})]})}export{ts as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.