PageSourceSearch

https://olyvia.lovable.app/assets/Proposals-DMwRgaeZ.js

js olyvia.lovable.app collected 2026-10-03 03:34:48 UTC 159,471 bytes, 10 lines download raw bytes

1import{r as n,j as e}from"./index-B-5bfxDF.js";import{aX as fn,s as d,J as vt,K as bt,M as Nt,N as wt,aC as ht,aM as ds,O as Fi,ak as St,g as qa,aD as nt,l as de,aq as rt,aY as cs,aZ as Qi,k as Ws,F as xt,S as os,u as Ia,i as g,a_ as H,a$ as gn,b0 as Bi,b1 as _n,p as Di,n as ka,ad as jn,ae as vn,af as qs,ah as Is,aA as Da,f as bn,v as me,an as Hi,b2 as Nn,d as wn,b3 as Ui,e as Gi,au as Ts,as as Wi,I as kt,b4 as yn,am as kn,a7 as Sn,ap as Rs,b5 as Cn,Q as Vt,P as zs,Z as Pn,m as we,b6 as qn,t as In,Y as Us,C as _e,b as Se,a as Ds,c as Es,a3 as Dn,a4 as En,a5 as Mn,a6 as An,aB as Xt,R as $s,V as Os,W as Ls,X as Vs,_ as Fs,$ as Qs,a0 as Bs,a1 as Hs,h as Tn,aF as Rn,aG as zn,aH as $n,j as Ms,aI as On,aJ as Ei,aK as Ln,ao as ns,aL as Vn,aO as Fn,aP as Qn,aQ as Bn,y as Hn,z as Un,E as Mi,G as Ye,ar as Ai,H as Gn,a2 as et,aR as Wn,aS as Jn,aa as Kn,b7 as Xn,w as Ti,b8 as Zn,b9 as Ri,aT as Yn,aU as At,aV as ge,aW as Tt,r as el}from"./App-AEo09UKd.js";import{s as Ji}from"./clientSearch-C_PTz70a.js";import{P as tl}from"./PageFAQSheet-BJGhtZkj.js";import{S as Rt,a as zt,b as $t,c as Ot,d as tt}from"./select-CUbCY2qF.js";import{p as sl}from"./validations-B2DlsKYi.js";import{P as jt}from"./PermissionGate-BCF2ysqi.js";import{u as al}from"./usePermissionScope-DSURAInJ.js";import{u as il}from"./useComercialUsers-huA_UMbD.js";import{u as rl,P as nl}from"./PortalStatusBadge-BQhH7bEH.js";import{E as ll}from"./EntitySearchInput-DSGjfZNe.js";import{d as it,C as ol}from"./calendar-sH4HauJw.js";import{P as dl,c as cl}from"./ProposalManualItemsEditor-B_t6Hpxn.js";import{R as ml}from"./RegisterCallDialog-Bw0ayIM5.js";import{C as Ft}from"./clock-BxjvlPf_.js";import{M as ul}from"./map-pin-CSL0P6Dp.js";import{G as xl}from"./globe-DxpVgDHc.js";import{M as hl}from"./monitor-Bts2Tp2S.js";import{T as pl}from"./tablet-Cy8yFDPG.js";import{S as fl}from"./smartphone-BB2Z1_2M.js";import{f as Re,s as gl}from"./format-Bmmh-amw.js";import{D as _l,u as jl}from"./useAlertSettings-DbVVodAL.js";import{l as vl,P as bl}from"./proposalPortalData-C9aK-A_N.js";import{g as Ki,d as Sa}from"./generateProposalPdfBlob-CpXNh-XS.js";import{g as Nl}from"./generateQuotePdfBlob-BeeTporJ.js";import{r as wl}from"./quoteCostResolver-D6ndrbib.js";import{P as yl}from"./percent-BDagJeD0.js";import{C as Ca}from"./copy-Buowv1bb.js";import{R as va}from"./receipt-D9O-JNlv.js";import{P as kl}from"./PipelineBreadcrumb-j-zja9CN.js";import{P as Sl}from"./progress-DfegQ6x7.js";import{u as Cl,M as Pl}from"./ModuleAlertsBanner-t-VBi5oQ.js";import{C as ql,a as Il,b as Dl}from"./collapsible-BJH2kVJS.js";import{L as El}from"./lightbulb-B3LH_dej.js";import{p as Ee}from"./parseISO-DZMlCMi0.js";import{D as Ml,C as Al,P as Tl}from"./dnd.esm-BiCHlS4m.js";import{c as As,a as zi,I as Rl}from"./InlineQuoteBuilder-B6Fmv7JP.js";import{S as zl}from"./settings-2-Cw7uU7cy.js";import{P as $i}from"./palette-_jbtpp8W.js";import{P as ba}from"./pencil-CegLYyAE.js";import{L as $l}from"./layout-list-DzQRsUBw.js";import{C as Oi}from"./columns-3-D4kA60wU.js";import{L as Li}from"./link-2-qxOCMZUy.js";import{E as Ol}from"./ellipsis-116QTA2V.js";import{A as Ll}from"./arrow-up-down-aB8Smrjj.js";import{A as Vl,a as Fl}from"./arrow-up-CpoQtJbJ.js";import{R as Na}from"./rotate-ccw-DRtaVQuS.js";import{D as Ql}from"./download-B-eeCNom.js";import{S as Bl}from"./square-check-big-DZ38ikUb.js";import{K as Hl}from"./key-round-CETE8763.js";import"./useQuery-k5LUBPmv.js";import"./message-square-text-B2rzCyal.js";import"./userTypeRoles-BSvOn3lL.js";import"./isBefore-Dt3tAxRI.js";import"./isSameMonth-DQTMs1_b.js";import"./chevron-left-Q8zv4eGa.js";import"./save-WgNF0Gx8.js";import"./grip-vertical-SGy0tPg1.js";import"./upload-mRqO3vVj.js";import"./image-DTYy8jR3.js";import"./input-otp-BMT2sXjP.js";import"./dot-D0rc-7o3.js";import"./shield-check-BXbD7I2F.js";import"./react-pdf.browser-ChqWkpOr.js";import"./_commonjs-dynamic-modules-TDtrdbi3.js";import"./__vite-browser-external-D7Ct-6yo.js";import"./registry-B61AmglX.js";import"./calculator-LZRG0evo.js";import"./file-pen-line-BLSQo4yv.js";import"./user-check-Bhjwm3UO.js";import"./index-CTTq3PJS.js";import"./tiny-invariant-BaFNuDhB.js";import"./LineAttributesDialog-s4oWc5YG.js";import"./product-attribute-ranges-DYDGB5AG.js";import"./QuoteAIAssistant-BxofEgve.js";import"./proxy-DgFVz06D.js";import"./index-Cmgb-L2F.js";import"./command-DFluIPai.js";import"./minus-D3if4Nbm.js";function Lt(c){return+fn(c)<Date.now()}const Vi={email:{label:"Email",icon:ht,color:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300"},portal:{label:"Portal Cliente",icon:cs,color:"bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300"},whatsapp:{label:"WhatsApp",icon:Qi,color:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300"}};function Ul({open:c,onOpenChange:_,proposalId:o,proposalTitle:q}){const[x,b]=n.useState([]),[z,Q]=n.useState(!0);n.useEffect(()=>{c&&o&&ee()},[c,o]);const ee=async()=>
1{if(o){Q(!0);try{const{data:m,error:T}=await d.from("proposal_sends").select("*").eq("proposal_id",o).order("sent_at",{ascending:!1});if(T)throw T;b(m||[])}catch(m){console.error("Error loading send history:",m)}finally{Q(!1)}}},ae=m=>{switch(m==null?void 0:m.toLowerCase()){case"mobile":return e.jsx(fl,{className:"h-4 w-4"});case"tablet":return e.jsx(pl,{className:"h-4 w-4"});default:return e.jsx(hl,{className:"h-4 w-4"})}},F=m=>m<60?`${m}s`:m<3600?`${Math.floor(m/60)}m ${m%60}s`:`${Math.floor(m/3600)}h ${Math.floor(m%3600/60)}m`,y=m=>{const T=Vi[m]||Vi.email,ie=T.icon;return e.jsxs(de,{variant:"outline",className:`text-xs ${T.color} border-0`,children:[e.jsx(ie,{className:"h-3 w-3 mr-1"}),T.label]})};return e.jsx(vt,{open:c,onOpenChange:_,children:e.jsxs(bt,{className:"sm:max-w-2xl max-h-[80vh]",children:[e.jsx(Nt,{children:e.jsxs(wt,{className:"flex items-center gap-2",children:[e.jsx(ht,{className:"h-5 w-5"}),"Histórico de Envios",q&&e.jsxs("span",{className:"text-muted-foreground font-normal text-sm",children:["- ",q]})]})}),e.jsx(ds,{className:"max-h-[60vh] pr-4",children:z?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Fi,{size:40})}):x.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ht,{className:"h-12 w-12 mx-auto mb-2 opacity-30"}),e.jsx("p",{children:"Nenhum envio registado"})]}):e.jsx("div",{className:"space-y-4",children:x.map((m,T)=>e.jsxs("div",{children:[T>0&&e.jsx(St,{className:"my-4"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[y(m.channel||"email"),e.jsx("span",{className:"font-medium",children:m.recipient_name||m.recipient_email||"—"}),m.recipient_name&&m.recipient_email&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["(",m.recipient_email,")"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(qa,{className:"h-3 w-3"}),Re(new Date(m.sent_at),"dd MMM yyyy 'às' HH:mm",{locale:nt})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:m.open_count>0?e.jsxs(de,{variant:"default",className:"bg-green-600",children:[e.jsx(rt,{className:"h-3 w-3 mr-1"}),"Visto ",m.open_count,"x"]}):e.jsxs(de,{variant:"secondary",children:[e.jsx(Ft,{className:"h-3 w-3 mr-1"}),"Pendente"]})})]}),m.first_opened_at&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 space-y-2 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Primeira visualização:"}),e.jsx("div",{className:"font-medium",children:Re(new Date(m.first_opened_at),"dd/MM/yyyy HH:mm",{locale:nt})})]}),m.last_opened_at&&m.last_opened_at!==m.first_opened_at&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Última visualização:"}),e.jsx("div",{className:"font-medium",children:Re(new Date(m.last_opened_at),"dd/MM/yyyy HH:mm",{locale:nt})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-4",children:[m.total_view_time_seconds>0&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ft,{className:"h-3 w-3 text-muted-foreground"}),e.jsxs("span",{children:["Tempo total: ",F(m.total_view_time_seconds)]})]}),m.device_type&&e.jsxs("div",{className:"flex items-center gap-1",children:[ae(m.device_type),e.jsx("span",{children:m.device_type}),m.browser&&e.jsxs("span",{className:"text-muted-foreground",children:["(",m.browser,")"]})]}),(m.location_city||m.location_country)&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ul,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{children:[m.location_city,m.location_country].filter(Boolean).join(", ")})]}),m.ip_address&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(xl,{className:"h-3 w-3"}),e.jsx("span",{children:m.ip_address})]})]})]}),m.subject&&e.jsxs("div",{className:"text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Assu
1nto:"})," ",m.subject]})]})]},m.id))})})]})})}function Xi({open:c,onOpenChange:_,proposalId:o}){const[q,x]=n.useState(!0),[b,z]=n.useState(null),{toast:Q}=Ws(),ee=async()=>{try{const{blob:F,fileName:y}=await Ki(o);Sa(F,y)}catch(F){Q({title:"Erro ao gerar PDF",description:(F==null?void 0:F.message)||"Tenta novamente.",variant:"destructive"})}},ae=async F=>{try{const{blob:y,fileName:m}=await Nl(F);Sa(y,m)}catch(y){Q({title:"Erro ao gerar PDF",description:(y==null?void 0:y.message)||"Tenta novamente.",variant:"destructive"})}};return n.useEffect(()=>{if(!c||!o)return;let F=!1;return z(null),x(!0),(async()=>{const y=await vl(o);F||(z(y),x(!1))})(),()=>{F=!0}},[c,o]),e.jsx(vt,{open:c,onOpenChange:_,children:e.jsxs(bt,{className:"max-w-4xl max-h-[90vh] overflow-hidden p-0",children:[e.jsxs(Nt,{className:"px-6 pt-6 pb-2",children:[e.jsxs(wt,{className:"flex items-center gap-2",children:[e.jsx(xt,{className:"h-5 w-5"}),"Preview — Visão do Cliente no Portal"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Esta é a visualização que o cliente terá ao abrir esta proposta no portal.",(b==null?void 0:b.template)&&e.jsx(de,{variant:"secondary",className:"ml-2",children:b.template.name})]})]}),e.jsx("div",{className:"max-h-[calc(90vh-100px)] overflow-y-auto px-6 pb-6",children:q?e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx(os,{className:"h-8 w-48"}),e.jsx(os,{className:"h-32 w-full"}),e.jsx(os,{className:"h-64 w-full"})]}):b!=null&&b.proposal?e.jsx("div",{className:"py-4",children:(()=>{const F={sent:"A aguardar decisão",pending:"A aguardar decisão",draft:"Rascunho",accepted:"Proposta aceite",rejected:"Proposta rejeitada",expired:"Proposta expirada"},y=b.proposal.status,m=!["accepted","rejected","expired"].includes(y),T=y==="draft"&&m?"A aguardar decisão":F[y]||y;return e.jsx(bl,{proposal:b.proposal,template:b.template,quotes:b.quotes,quoteLines:b.quoteLines,commercial:b.commercial,company:b.company,mode:"preview",statusLabel:T,canActOnProposal:m,onDownloadPdf:ee,onDownloadQuotePdf:ae})})()}):e.jsx("p",{className:"py-8 text-center text-muted-foreground",children:"Proposta não encontrada. Guarde a proposta primeiro."})})]})})}const Zi=c=>Math.round((Number(c)||0)*100)/100,Gl=c=>{const _=c.selected_attributes||{},o=Array.isArray(_.bundle_components)?_.bundle_components:[],q=Array.isArray(_.bundle_components_data)?_.bundle_components_data:[];return(o.length>0?o:q).filter(b=>b&&typeof b=="object").map(b=>({quantity:parseFloat(String(b.quantity||0))||0,unit_price:parseFloat(String(b.unit_price||0))||0}))},Gs=c=>{const _=parseFloat(String(c.qt||0))||0,o=Gl(c),q=o.reduce((b,z)=>b+z.unit_price*(z.quantity*(_||1)),0),x=(c.bundle_id||o.length>0)&&q>0?q:parseFloat(String(c.total_sem_iva||0));return Zi(x)},ls=c=>{const _=Gs(c),o=parseFloat(String(c.total_sem_iva||0))||0,q=parseFloat(String(c.total_com_iva||0))||0;if(!(Math.abs(q-o)>.004))return _;const b=parseFloat(String(c.iva_percent||0))||0;return Zi(_*(1+b/100))},Wl=c=>{const _=[...c.quote_lines||[]].sort((q,x)=>(q.ordem||0)-(x.ordem||0));if(_.length===0){const q=c.total||0;return[{id:`${c.id}-default`,quote:c,sectionName:null,lines:[],subtotal:q,vat:0,total:q}]}const o=_.reduce((q,x)=>{var z;const b=((z=x.section_name)==null?void 0:z.trim())||"Itens";return q[b]||(q[b]=[]),q[b].push(x),q},{});return Object.entries(o).map(([q,x],b)=>{const z=x.reduce((ee,ae)=>ee+Gs(ae),0),Q=x.reduce((ee,ae)=>ee+ls(ae),0);return{id:`${c.id}-${q}-${b}`,quote:c,sectionName:q,lines:x,subtotal:z,vat:Q-z,total:Q}})};function Jl({open:c,onOpenChange:_,proposal:o,onSendProposal:q,onViewHistory:x,onAccept:b,onReject:z}){const[Q,ee]=n.useState([]),[ae,F]=n.useState([]),[y,m]=n.useState({}),[T,ie]=n.useState(null),[L,ue]=n.useState([]),[P,re]=n.useState(null),[Z,Y]=n.useState([]),[ce,j]=n.useState(!1),[v,h]=n.useState(!1),[$,G]=n.useState(!1),{toast:Me}=Ws();Ia(),n.useEffect(()=>{c&&(o!=null&&o.id)&&D()},[c,o==null?void 0:o.id]);const D=async()=>{var i,O,ne,te,Ae,je,Pe;if(o!=null&&o.id){j(!0);try{const[ze,pt,ye,$e]=await Promise.all([d.from("proposal_items").select("*").eq("proposal_id",o.id
1).order("sort_order"),d.from("quotes").select("id, quote_number, title, total, estado, client_notes, updated_at, created_at, desconto_global_percent, quote_lines(id, descricao_snapshot, qt, total_sem_iva, total_com_iva, iva_percent, ordem, section_name, custo_material_unit, custo_mao_obra_unit, margem_percent, int_percent, discount_percent, cost_price, unidade, item_description, selected_attributes, product_id, service_id, bundle_id)").eq("proposal_id",o.id),d.from("proposals").select(`
2            *,
3            proposal_templates(id, name)
4          `).eq("id",o.id).single(),d.from("proposal_sends").select("id, recipient_email, sent_at, first_opened_at, open_count").eq("proposal_id",o.id).order("sent_at",{ascending:!1}).limit(5)]);let at=ze.data||[];ee(at);let Ke=pt.data||[];if(Ke.length===0){const{data:W}=await d.from("pipeline_links").select("quote_id").eq("proposal_id",o.id).eq("status","active").maybeSingle();if(W!=null&&W.quote_id){const{data:Te}=await d.from("quotes").select("id, quote_number, title, total, estado, client_notes, updated_at, created_at, desconto_global_percent, quote_lines(id, descricao_snapshot, qt, total_sem_iva, total_com_iva, iva_percent, ordem, section_name, custo_material_unit, custo_mao_obra_unit, margem_percent, int_percent, discount_percent, cost_price, unidade, item_description, selected_attributes, product_id, service_id, bundle_id)").eq("id",W.quote_id).single();Te&&(Ke=[Te])}}F(Ke);try{const W=Ke.flatMap(Te=>Te.quote_lines||[]);if(W.length>0){const Te=await wl(W);m(Te)}else m({})}catch(W){console.error("[ProposalDetailsDialog] resolveLineDetails failed",W),m({})}re(ye.data);const Fe=(i=ye.data)==null?void 0:i.entity_id;if(Fe){const[W,Te,ct]=await Promise.all([d.from("anew_entities").select("id, display_name, first_name, last_name, type").eq("id",Fe).single(),d.from("anew_entity_emails").select("email").eq("entity_id",Fe).eq("is_primary",!0).maybeSingle(),d.from("anew_entity_phones").select("phone_number, country_code").eq("entity_id",Fe).eq("is_primary",!0).maybeSingle()]);W.data?ie({id:W.data.id,first_name:W.data.first_name,last_name:W.data.last_name,company_name:W.data.type==="organization"?W.data.display_name:null,email:((O=Te.data)==null?void 0:O.email)||null,phone:((ne=ct==null?void 0:ct.data)==null?void 0:ne.phone_number)||null}):ie(null)}else ie(null);ue($e.data||[]);const se=[];ye.data&&se.push({label:"Proposta criada",date:ye.data.created_at,icon:"file",color:"text-primary"});const{data:qe}=await d.from("pipeline_links").select("*, deals(id, title, created_at, entity_id), anew_leads(id, created_at, field_values), quotes(id, quote_number, created_at, estado)").eq("proposal_id",o.id).eq("status","active").maybeSingle();if(qe){if(qe.anew_leads){const W=qe.anew_leads.field_values||{},Te=W.nome||W.first_name||"Lead";se.unshift({label:`Lead captado: ${Te}`,date:qe.anew_leads.created_at,icon:"lead",color:"text-blue-500"})}if(qe.deals&&se.splice(se.length>1?1:0,0,{label:`Pedido criado: ${qe.deals.title}`,date:qe.deals.created_at,icon:"deal",color:"text-purple-500"}),qe.quotes){const W=qe.quotes.created_at,Te=se.findIndex(ct=>ct.icon==="file");se.splice(Te>=0?Te:se.length,0,{label:`Orçamento ${qe.quotes.quote_number||""} — ${qe.quotes.estado}`,date:W,icon:"quote",color:"text-amber-500"})}}(te=ye.data)!=null&&te.sent_at&&se.push({label:"Proposta enviada",date:ye.data.sent_at,icon:"send",color:"text-blue-600"}),(Ae=ye.data)!=null&&Ae.viewed_at&&se.push({label:"Proposta visualizada",date:ye.data.viewed_at,icon:"eye",color:"text-purple-600"}),(je=ye.data)!=null&&je.accepted_at&&se.push({label:"Proposta aceite",date:ye.data.accepted_at,icon:"check",color:"text-green-600"}),(Pe=ye.data)!=null&&Pe.rejected_at&&se.push({label:"Proposta rejeitada",date:ye.data.rejected_at,icon:"x",color:"text-red-600"}),se.sort((W,Te)=>new Date(W.date).getTime()-new Date(Te.date).getTime()),Y(se)}catch(ze){console.error("Error loading proposal details:",ze)}finally{j(!1)}}},M=()=>{if(P!=null&&P.public_token){const i=`${window.location.origin}/proposal/${P.public_token}`;navigator.clipboard.writeText(i),Me({title:"Link copiado",description:"O link público foi copiado para a área de transferência."})}},u=()=>{if(P!=null&&P.public_token){const i=`${window.location.origin}/proposal/${P.public_token}`;window.open(i,"_blank")}},Ce=()=>{const i=o==null?void 0:o.proposal_workflow_stages;return i?e.jsx(de,{style:{backgroundColor:i.color,color:"#fff"},className:"font-medium",children:i.label}):e.jsx(de,{variant:"secondary",children:o==null?void 0:o.status})},st=()=>Q.reduce((i,O)=>{const ne=O.quantity*O.unit_price,te=ne*(O.vat_rate/100);return i+ne+te},0),Je=ae.flatMap(Wl),R=Je.reduce((i,O)=>(i[O.quote.id]=(i[O.quote.id]||0)+1,i),{});return o?e.jsxs(e.Fragment,{children:[e.jsx(vt,{open:c,onOpenChange:_,children:e.jsxs(bt,{className:"max-w-2xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(Nt,{className:"pb-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(wt,{className:"flex items-center gap-2 text-xl",children:[e.jsx(xt,{className:"w-5 h-5 text-primary"}),o.proposal_number&&e.jsx("span",{className:"font-mono text-primary",children:o.proposal_number}),o.proposal_number&&e.jsx("span",{className:"text-muted-foreground",children:"·"}),e.jsx("span",{children:o.title})]}),e.jsxs(g,{variant:"outline",size:"sm",className:"gap-1 mr-6",onClick:()=>G(!0),children:[e.jsx(rt,{className:"h-4 w-4"})," Preview Portal"]})]})}),e.jsx(ds,{className:"flex-1 -mx-6 px-6 overflow-auto",style:{maxHeight:"calc(90vh - 120px)"},children:e.jsxs("div",{className:"space-y-6 pb-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[Ce(),o.probability!==null&&e.jsxs(de,{variant:"outline",className:"flex items-center gap-1",children:[e.jsx(yl,{className:"w-3 h-3"}),o.probability,"%"]})]}),e.jsx("span",{className:"text-3xl font-bold text-green-600 dark:text-green-400",children:(()=>{const i=ae.filter(ne=>ne.quote_lines&&ne.quote_lines.length>0);if(i.length===0)return H(o.value);const O=i.reduce((ne,te)=>{const Ae=(te.quote_lines||[]).reduce((Pe,ze)=>Pe+ls(ze),0),je=Number(te.desconto_global_percent)||0;return ne+Ae*(1-je/100)},0);return H(O)})()})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[(P==null?void 0:P.public_token)&&(P==null?void 0:P.public_link_enabled)&&e.jsxs(e.Fragment,{children:[e.jsxs(g,{variant:"outline",size:"sm",onClick:M,children:[e.jsx(Ca,{className:"w-4 h-4 mr-2"}),"Copiar Link"]}),e.jsxs(g,{variant:"outline",size:"sm",onClick:u,children:[e.jsx(gn,{className:"w-4 h-4 mr-2"}),"Ver Proposta"]})]}),q&&e.jsxs(g,{variant:"outline",size:"sm",onClick:q,children:[e.jsx(cs,{className:"w-4 h-4 mr-2"}),"Enviar"]}),x&&e.jsxs(g,{variant:"outline",size:"sm",onClick:x,children:[e.jsx(Bi,{className:"w-4 h-4 mr-2"}),"Histórico"]}),(T==null?void 0:T.phone)&&e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>h(!0),className:"gap-2 text-green-600 hover:text-green-700",children:[e.jsx(_n,{className:"w-4 h-4"}),"WhatsApp"]})]}),o.status!=="accepted"&&o.status!=="rejected"&&(b||z)&&e.jsxs("div",{className:"flex items-center gap-3 p-4 rounded-xl bg-gradient-to-r from-muted/50 to-muted/30 border",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Decisão sobre a proposta"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Aceitar ou recusar esta proposta comercial"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[z&&e.jsxs(g,{size:"lg",variant:"outline",className:"border-destructive/50 text-destructive hover:bg-destructive hover:text-destructive-foreground transition-all duration-200 font-semibold px-6 rounded-full",onClick:z,children:[e.jsx(Di,{className:"w-5 h-5 mr-2"}),"Recusar"]}),b&&e.jsxs(g,{size:"lg",className:"bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 text-white shadow-lg shadow-green-500/25 hover:shadow-green-500/40 transition-all duration-200 font-semibold px-6 rounded-full",onClick:b,children:[e.jsx(ka,{className:"w-5 h-5 mr-2"}),"Aceitar Proposta"]})]})]}),e.jsx(St,{}),e.jsxs(jn,{defaultValue:"info",className:"w-full",children:[e.jsxs(vn,{className:"grid w-full grid-cols-4",children:[e.jsx(qs,{value:"info",children:"Informações"}),e.jsxs(qs,{value:"items",children:["Itens ",Q.length>0&&`(${Q.length})`]}),e.jsx(qs,{value:"documentos",children:"Documentos"}),e.jsx(qs,{value:"tracking",children:"Rastreamento"})]}),e.jsxs(Is,{value:"info",className:"mt-4 space-y-4",children:[T&&e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground mb-2",children:[e.jsx(Da,{className:"w-4 h-4"}),"Cliente"]}),e.jsx("p",{className:"font-semibold",children:T.company_name||[T.first_name,T.last_name].filter(
4Boolean).join(" ")||"Cliente"}),T.email&&e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(ht,{className:"w-3 h-3"}),T.email]})]}),o.deals&&e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground mb-2",children:[e.jsx(bn,{className:"w-4 h-4"}),"Pedido de Proposta"]}),e.jsx("p",{className:"font-semibold",children:o.deals.title})]}),o.description&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(me,{className:"text-muted-foreground text-sm",children:"Descrição"}),e.jsx("p",{className:"text-sm bg-muted/30 p-3 rounded-lg",children:o.description})]}),o.notes&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(me,{className:"text-muted-foreground text-sm",children:"Notas"}),e.jsx("p",{className:"text-sm bg-muted/30 p-3 rounded-lg",children:o.notes})]}),(P==null?void 0:P.proposal_templates)&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(xt,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Template:"}),e.jsx("span",{className:"font-medium",children:P.proposal_templates.name})]}),Je.length>0&&e.jsxs("div",{className:"space-y-3 border-2 border-primary/20 rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(va,{className:"w-4 h-4 text-primary"}),"Orçamentos Associados",e.jsx(de,{variant:"secondary",className:"text-xs",children:Je.length})]}),e.jsx("div",{className:"space-y-4",children:Je.map(i=>{const O=i.quote,ne=(R[O.id]||0)>1;return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(va,{className:"w-4 h-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-sm",children:O.quote_number||"Sem número"}),ne&&i.sectionName&&e.jsx(de,{variant:"secondary",className:"text-[10px]",children:i.sectionName})]}),O.created_at&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Re(new Date(O.created_at),"dd MMM yyyy",{locale:nt})})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(de,{variant:"outline",className:"text-xs capitalize",children:O.estado}),e.jsx("span",{className:"font-bold text-green-600 dark:text-green-400",children:H(i.total)})]})]}),i.lines.length>0&&e.jsxs("div",{className:"border rounded-md overflow-hidden",children:[e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/50 text-muted-foreground uppercase tracking-wider",children:[e.jsx("th",{className:"text-left p-2 font-medium",children:"Descrição"}),e.jsx("th",{className:"text-center p-2 font-medium w-14",children:"QTD"}),e.jsx("th",{className:"text-right p-2 font-medium w-20",children:"Preço Unit."}),e.jsx("th",{className:"text-center p-2 font-medium w-12",children:"IVA"}),e.jsx("th",{className:"text-center p-2 font-medium w-12",children:"Desc."}),e.jsx("th",{className:"text-center p-2 font-medium w-16",children:"Margem"}),e.jsx("th",{className:"text-right p-2 font-medium w-24",children:"Total"})]})}),e.jsx("tbody",{children:i.lines.map(te=>{var se;const Ae=Gs(te),je=ls(te),Pe=te.qt>0?Ae/te.qt:0,ze=((se=y[te.id])==null?void 0:se.unitCost)??0,pt=te.cost_price||(te.custo_material_unit||0)+(te.custo_mao_obra_unit||0),ye=ze>0?ze:pt,$e=ye>0&&Pe>0?(Pe-ye)/Pe*100:0,at=ye>0,Ke=te.selected_attributes,Fe=Ke?Object.entries(Ke).filter(([qe,W])=>W&&W!==""):[];return e.jsxs("tr",{className:"border-t border-muted/30 align-top",children:[e.jsxs("td",{className:"p-2",children:[e.jsx("span",{className:"font-medium",children:te.descricao_snapshot||"-"}),Fe.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Fe.map(([qe,W])=>e.jsxs("span",{className:"text-[10px] text-muted-foreground bg-muted/50 px-1.5 py-0.5 rounded",children:[qe,": ",typeof W=="object"?W.label||W.value||JSON.stringify(W):String(W)]},qe))})]}),e.jsxs("td",{className:"p-2 text-center",children:[te.qt,te.unidade?` ${te.unidade}`:""]}),e.jsx("td",{className:"p-2 text-right",children:H(Pe)}),e.jsxs("td",{className:"p-2 text-center text-muted-foreground",children:[te.iva_percent||0,"%"]}),e.jsx("td",{className:"p-2 text-center",children:(te.discount_percent||0)>
40?e.jsxs("span",{className:"text-orange-600 dark:text-orange-400 font-medium",children:[te.discount_percent,"%"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"p-2 text-center",children:at?e.jsxs("span",{className:`font-medium ${$e>=30?"text-green-600 dark:text-green-400":$e>=15?"text-yellow-600 dark:text-yellow-400":"text-red-600 dark:text-red-400"}`,children:[$e.toFixed(1),"%"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"p-2 text-right",children:[e.jsx("p",{className:"font-semibold",children:H(je)}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[H(Ae)," s/IVA"]})]})]},te.id)})})]}),e.jsxs("div",{className:"border-t bg-muted/30 p-2 text-xs space-y-1",children:[e.jsxs("div",{className:"flex justify-end gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"Subtotal"}),e.jsx("span",{children:H(i.subtotal)})]}),e.jsxs("div",{className:"flex justify-end gap-6",children:[e.jsx("span",{className:"text-muted-foreground",children:"IVA"}),e.jsx("span",{children:H(i.vat)})]})]})]})]},i.id)})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(me,{className:"text-muted-foreground text-xs flex items-center gap-1",children:[e.jsx(qa,{className:"w-3 h-3"}),"Válido Até"]}),e.jsx("p",{className:"font-medium",children:o.valid_until?Re(new Date(o.valid_until),"dd/MM/yyyy",{locale:nt}):"-"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(me,{className:"text-muted-foreground text-xs flex items-center gap-1",children:[e.jsx(Ft,{className:"w-3 h-3"}),"Criado em"]}),e.jsx("p",{className:"font-medium",children:Re(new Date(o.created_at),"dd/MM/yyyy HH:mm",{locale:nt})})]}),(P==null?void 0:P.request_date)&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(me,{className:"text-muted-foreground text-xs",children:"Data Pedido"}),e.jsx("p",{className:"font-medium",children:Re(new Date(P.request_date),"dd/MM/yyyy HH:mm",{locale:nt})})]}),(P==null?void 0:P.delivered_at)&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(me,{className:"text-muted-foreground text-xs",children:"Entregue em"}),e.jsx("p",{className:"font-medium",children:Re(new Date(P.delivered_at),"dd/MM/yyyy HH:mm",{locale:nt})})]})]})]}),e.jsxs(Is,{value:"items",className:"mt-4 space-y-4",children:[Q.length>0&&e.jsxs("div",{className:"space-y-2",children:[Q.map(i=>e.jsx("div",{className:"p-3 rounded-lg bg-muted/30 space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:i.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[i.quantity,"x @ ",H(i.unit_price)," • IVA ",i.vat_rate,"%"]})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:"font-semibold",children:H(i.quantity*i.unit_price*(1+i.vat_rate/100))})})]})},i.id)),e.jsx(St,{}),e.jsxs("div",{className:"flex justify-between items-center pt-2",children:[e.jsx("span",{className:"font-medium",children:"Total Itens"}),e.jsx("span",{className:"text-lg font-bold text-green-600 dark:text-green-400",children:H(st())})]})]}),Q.length===0&&ae.some(i=>i.quote_lines&&i.quote_lines.length>0)&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Itens do orçamento associado:"}),ae.map(i=>i.quote_lines&&i.quote_lines.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-2 px-3 py-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider border-b",children:[e.jsx("div",{className:"col-span-4",children:"Descrição"}),e.jsx("div",{className:"col-span-1 text-center",children:"Qtd"}),e.jsx("div",{className:"col-span-2 text-right",children:"Preço Unit."}),e.jsx("div",{className:"col-span-1 text-center",children:"IVA"}),e.jsx("div",{className:"col-span-1 text-center",children:"Desc."}),e.jsx("div",{className:"col-span-1 text-center",children:"Margem"}),e.jsx("div",{className:"col-span-2 text-right",children:"Total"})]}),[...i.quote_lines].sort((O,ne)=>(O.ordem||0)-(ne.ordem||0)).map(O=>{var Ke;const ne=Gs(O),te=ls(O),Ae=O.qt>0?ne/O.qt:0,je=((Ke=y[O.id])==null?void 0:Ke.unitCost)??0,Pe=O.cost_price||(O.custo_material_unit||0)+(O.custo_mao_obra_unit||0),ze=je>0?je:Pe,pt=ze>0&&Ae>0?(Ae-ze)/Ae*100:0,ye=ze>
40,$e=O.selected_attributes,at=$e?Object.entries($e).filter(([Fe,se])=>se&&se!==""):[];return e.jsxs("div",{className:"space-y-0",children:[e.jsxs("div",{className:"grid grid-cols-12 gap-2 px-3 py-2.5 rounded-t-lg bg-muted/30 items-center text-sm",children:[e.jsxs("div",{className:"col-span-4",children:[e.jsx("p",{className:"font-medium text-sm leading-tight",children:O.descricao_snapshot||"-"}),O.item_description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:O.item_description})]}),e.jsxs("div",{className:"col-span-1 text-center text-muted-foreground",children:[O.qt,O.unidade?` ${O.unidade}`:"x"]}),e.jsx("div",{className:"col-span-2 text-right text-muted-foreground",children:H(Ae)}),e.jsxs("div",{className:"col-span-1 text-center text-muted-foreground",children:[O.iva_percent||0,"%"]}),e.jsx("div",{className:"col-span-1 text-center",children:(O.discount_percent||0)>0?e.jsxs("span",{className:"text-orange-600 dark:text-orange-400 font-medium",children:[O.discount_percent,"%"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("div",{className:"col-span-1 text-center",children:ye?e.jsxs("span",{className:`font-medium ${pt>=30?"text-green-600 dark:text-green-400":pt>=15?"text-yellow-600 dark:text-yellow-400":"text-red-600 dark:text-red-400"}`,children:[pt.toFixed(1),"%"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("div",{className:"col-span-2 text-right",children:[e.jsx("p",{className:"font-semibold",children:H(te)}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[H(ne)," s/ IVA"]})]})]}),at.length>0&&e.jsx("div",{className:"px-3 py-1.5 bg-muted/15 rounded-b-lg border-t border-border/30 flex flex-wrap gap-x-3 gap-y-1",children:at.map(([Fe,se])=>e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[e.jsxs("span",{className:"font-medium",children:[Fe,":"]})," ",typeof se=="object"?se.label||se.value||JSON.stringify(se):String(se)]},Fe))})]},O.id)}),e.jsx(St,{}),(()=>{const O=(i.quote_lines||[]).reduce((je,Pe)=>je+ls(Pe),0),ne=Number(i.desconto_global_percent)||0,te=O*(ne/100),Ae=O-te;return e.jsxs("div",{className:"space-y-1 pt-2",children:[ne>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Subtotal"}),e.jsx("span",{children:H(O)})]}),e.jsxs("div",{className:"flex justify-between items-center text-sm",children:[e.jsxs("span",{className:"text-orange-600 dark:text-orange-400",children:["Desconto global (",ne,"%)"]}),e.jsxs("span",{className:"text-orange-600 dark:text-orange-400",children:["-",H(te)]})]})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"font-medium",children:"Total"}),e.jsx("span",{className:"text-lg font-bold text-green-600 dark:text-green-400",children:H(Ae)})]})]})})()]},i.id))]}),Q.length===0&&!ae.some(i=>i.quote_lines&&i.quote_lines.length>0)&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Hi,{className:"w-12 h-12 mx-auto mb-2 opacity-30"}),e.jsx("p",{children:"Sem itens adicionados"})]})]}),e.jsxs(Is,{value:"tracking",className:"mt-4 space-y-4",children:[Z.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(me,{className:"text-muted-foreground text-sm",children:"Jornada do Pipeline"}),e.jsx("div",{className:"relative space-y-0",children:Z.map((i,O)=>{const ne=i.icon==="lead"?Nn:i.icon==="deal"?wn:i.icon==="quote"?va:i.icon==="file"?xt:i.icon==="send"?cs:i.icon==="eye"?rt:i.icon==="check"?ka:i.icon==="x"?Di:Ft;return e.jsxs("div",{className:"flex items-start gap-3 relative",children:[O<Z.length-1&&e.jsx("div",{className:"absolute left-[11px] top-7 w-0.5 h-[calc(100%)] bg-border"}),e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center shrink-0 z-10 bg-background border-2 border-current ${i.color}`,children:e.jsx(ne,{className:"w-3 h-3"})}),e.jsxs("div",{className:"pb-4 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:i.label}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:Re(new Date(i.date),"dd/MM/yyyy HH:mm",{locale:nt})})]})]},O)})})]}),L.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(me,{className:"text-muted-foreground text-sm",children:"Últimos Envios"}),e.jsx("div",{className:"space-y-2",children:L.map(i=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-muted/30 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ht,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{children:i.recipient_email})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsx("span",{children:Re(new Date(i.sent_at),"dd/MM HH:mm")}
4),i.first_opened_at&&e.jsxs(de,{variant:"outline",className:"text-xs bg-green-500/10",children:[e.jsx(rt,{className:"w-3 h-3 mr-1"}),i.open_count,"x"]})]})]},i.id))})]}),Z.length===0&&L.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ft,{className:"w-12 h-12 mx-auto mb-2 opacity-30"}),e.jsx("p",{children:"Sem histórico disponível"})]})]}),e.jsx(Is,{value:"documentos",className:"mt-4",children:P!=null&&P.organization_id?e.jsx(_l,{entityType:"proposal",entityId:o.id,organizationId:P.organization_id}):e.jsx("div",{className:"text-center py-8 text-muted-foreground text-sm",children:"A carregar…"})})]})]})})]})}),e.jsx(Ui,{open:v,onOpenChange:h,context:T!=null&&T.phone?{module:"proposals",recipientName:[T.first_name,T.last_name].filter(Boolean).join(" ")||T.company_name||"Cliente",recipientPhone:T.phone,proposalTitle:o==null?void 0:o.title,proposalValue:o==null?void 0:o.value,proposalLink:P!=null&&P.public_token&&(P!=null&&P.public_link_enabled)?`${window.location.origin}/proposal/${P.public_token}`:void 0,dealId:(o==null?void 0:o.deal_id)||void 0}:null}),e.jsx(Xi,{open:$,onOpenChange:G,proposalId:o.id})]}):null}const wa=c=>{const _=Math.abs(c).toFixed(2),[o,q]=_.split(".");return"€"+o.replace(/\B(?=(\d{3})+(?!\d))/g,".")+","+q};function Kl({open:c,onOpenChange:_,onApply:o}){const[q,x]=n.useState("search"),[b,z]=n.useState(""),[Q,ee]=n.useState([]),[ae,F]=n.useState(!1),[y,m]=n.useState(null),[T,ie]=n.useState(""),[L,ue]=n.useState(!1),[P,re]=n.useState(null),[Z,Y]=n.useState(new Set),[ce,j]=n.useState(null),{activeCompany:v}=Gi(),{toast:h}=Ws();Ia(),n.useEffect(()=>{c||(x("search"),z(""),ee([]),m(null),ie(""),re(null),Y(new Set),j(null))},[c]),n.useEffect(()=>{if(b.length<2){ee([]);return}const M=setTimeout(async()=>{F(!0);try{const{ids:u}=await Ji(b);if(u.length===0){ee([]),F(!1);return}const{data:Ce}=await d.from("anew_entities").select("id, display_name, type").in("id",u).eq("status","active").limit(10);if(!Ce||Ce.length===0){ee([]),F(!1);return}const st=await Promise.all(Ce.map(async Je=>{var ne;const[R,i,O]=await Promise.all([d.from("anew_entity_emails").select("email").eq("entity_id",Je.id).eq("is_primary",!0).maybeSingle(),d.from("anew_leads").select("id",{count:"exact",head:!0}).eq("entity_id",Je.id),d.from("deals").select("id",{count:"exact",head:!0}).eq("entity_id",Je.id)]);return{...Je,email:((ne=R.data)==null?void 0:ne.email)||void 0,lead_count:i.count||0,deal_count:O.count||0}}));ee(st)}catch(u){console.error("Search error:",u)}finally{F(!1)}},400);return()=>clearTimeout(M)},[b]);const $=async()=>{if(!(!y||!(v!=null&&v.id))){x("generating"),ue(!0),j(null);try{const{data:M,error:u}=await d.functions.invoke("generate-proposal-ai",{body:{entity_id:y.id,organization_id:v.id,extra_context:T||void 0}});if(u)throw u;if(M!=null&&M.error)throw new Error(M.error);re(M),Y(new Set((M.items||[]).map((Ce,st)=>st))),x("result")}catch(M){j(M.message||"Erro ao gerar proposta"),x("search"),h({title:"Erro",description:M.message,variant:"destructive"})}finally{ue(!1)}}},G=()=>{P&&(o({title:P.title,description:P.description,items:P.items.filter((M,u)=>Z.has(u))}),_(!1))},Me=M=>{Y(u=>{const Ce=new Set(u);return Ce.has(M)?Ce.delete(M):Ce.add(M),Ce})},D=P?P.items.filter((M,u)=>Z.has(u)).reduce((M,u)=>M+u.quantity*u.unit_price*(1+u.vat_rate/100),0):0;return e.jsx(vt,{open:c,onOpenChange:_,children:e.jsxs(bt,{className:"max-w-2xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(Nt,{children:e.jsxs(wt,{className:"flex items-center gap-2",children:[e.jsx(Ts,{className:"w-5 h-5 text-primary"}),"Gerar Proposta com IA"]})}),q==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(me,{children:"Pesquisar Contacto / Entidade"}),e.jsxs("div",{className:"relative",children:[e.jsx(Wi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(kt,{placeholder:"Pesquisar por nome...",value:b,onChange:M=>z(M.target.value),className:"pl-10"})]})]}),ae&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(yn,{className:"w-4 h-4 animate-spin"}),"A pesquisar..."]}),Q.length>0&&e.jsx(ds,{className:"max-h-48",children:e.jsx("div",{className:"space-y-1",children:Q.map(M=>e.jsxs("button",{onClick:()=>{m(M),ee([]),z(M.display_name)},className:`w-full flex items-center justify-between p-3 rounded-lg text-left transition-colors hover:bg-accent ${(y==null?void 0:y.id)===M.id?"bg-accent ring-2 ring-primary":"bg-muted/30"}`,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Da,{className:"w-4 h-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:M.display_name}),M.email&&e.jsx("p",{className:"text-xs text-muted-foreground",children:M.email})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[(M.lead_count||0)>0&&e.jsxs(de,{variant:"outline",className:"text-xs",children:[M.lead_count," leads"]}),(M.deal_count||0)>0&&e.jsxs(de,{variant:"outline",className:"text-xs",children:[M.deal_count," pedidos"]}),e.jsx(kn,{className:"w-4 h-4 text-muted-foreground"})]})]},M.id))})}),y&&e.jsxs(e.Fragment,{children:[e.jsx(St,{}),e.jsxs("div",{className:"p-3 rounded-lg bg-primary/5 border border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Sn,{className:"w-4 h-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Contacto selecionado"})]}),e.jsx("p",{className:"text-sm font-semibold",children:y.display_name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(me,{children:"Contexto adicional (opcional)"}),e.jsx(Rs,{placeholder:"Ex: O cliente precisa de uma proposta para renovação...",value:T,onChange:M=>ie(M.target.value),rows:3})]})]}),ce&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-destructive p-3 rounded-lg bg-destructive/10",children:[e.jsx(Cn,{className:"w-4 h-4"}),ce]}),e.jsxs(Vt,{children:[e.jsx(g,{variant:"outline",onClick:()=>_(!1),children:"Cancelar"}),e.jsxs(g,{onClick:$,disabled:!y,children:[e.jsx(Ts,{className:"w-4 h-4 mr-2"}),"Gerar Proposta"]})]})]}),q==="generating"&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 space-y-4",children:[e.jsx(Ts,{className:"w-12 h-12 text-primary animate-pulse"}),e.jsx("p",{className:"font-medium",children:"A analisar histórico do contacto..."}),e.jsx(Sl,{value:void 0,className:"w-64 [&>div]:animate-pulse"})]}),q==="result"&&P&&e.jsx(ds,{className:"flex-1 -mx-6 px-6 max-h-[60vh]",children:e.jsxs("div",{className:"space-y-4 pb-4",children:[P.analysis&&e.jsxs("div",{className:"p-3 rounded-lg bg-blue-500/10 border border-blue-500/20",children:[e.jsx("p",{className:"text-xs font-medium mb-1",children:"Análise do Contacto"}),e.jsx("p",{className:"text-sm",children:P.analysis})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(me,{className:"text-xs text-muted-foreground",children:"Título"}),e.jsx("p",{className:"font-semibold",children:P.title})]}),e.jsx(St,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx(Hi,{className:"w-4 h-4"}),"Itens Sugeridos (",P.items.length,")"]}),P.items.map((M,u)=>e.jsx("button",{onClick:()=>Me(u),className:`w-full text-left p-3 rounded-lg border transition-colors ${Z.has(u)?"bg-primary/5 border-primary/30":"bg-muted/20 border-transparent opacity-60"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:M.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[M.quantity,"x @ ",wa(M.unit_price)]})]}),e.jsx("p",{className:"font-semibold text-sm",children:wa(M.quantity*M.unit_price*(1+M.vat_rate/100))})]})},u))]}),e.jsx(St,{}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"font-medium",children:"Total"}),e.jsx("span",{className:"text-xl font-bold",children:wa(D)})]})]})}),q==="result"&&e.jsxs(Vt,{className:"pt-4 border-t",children:[e.jsx(g,{variant:"outline",onClick:()=>{x("search"),re(null)},children:"Voltar"}),e.jsxs(g,{onClick:G,disabled:Z.size===0,children:[e.jsx(zs,{className:"w-4 h-4 mr-2"}),"Aplicar (",Z.size," itens)"]})]})]})})}function Xl(){const c=[{label:"Pedido Qualificado",active:!1,highlight:!1},{label:"Orçamento Aceite",active:!1,highlight:!1},{label:"Proposta",active:!0,highlight:!0},{label:"Contrato",active:!1,highlight:!1},{label:"Cliente",active:!1,highlight:!1}];return e.jsx("div",{className:"flex-shrink-0",children:e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 rounded-lg border border-primary/20 bg-primary/5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-primary",children:[e.jsx(Pn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-semibold whitespace-nowrap",children:"Fluxo automático:"})]}),e.jsx("div",{className:"flex items-center gap-1 flex-wrap",children:c.map((_,o)=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:_.highlight?"text-xs font-bold text-primary-foreground bg-primary px-2.5 py-1 rounded-md":"text-xs text-muted-foreground",children:_.label}),o<c.length-1&&e.jsx("span",{className:"text-xs text-muted-foreground",children:o===1?"→ cria →":o===2?"â
4†’ aceite cria →":o===3?"→ assinado cria →":"→"})]},_.label))}),e.jsx("span",{className:"text-[11px] text-muted-foreground ml-auto hidden lg:block",children:"Aceitar proposta cria contrato automaticamente"})]})})}function Zl({proposals:c,onNavigateContracts:_,onSendFollowUp:o,onRenewValidity:q,onOpenProposal:x,noResponseDays:b=5,noResponseUrgentDays:z=10,noResponseEnabled:Q=!0,noResponseUrgentEnabled:ee=!0,expiredEnabled:ae=!0,noValidityEnabled:F=!0,draftStaleEnabled:y=!0,draftStaleDays:m=5}){const[T,ie]=n.useState(!1),L=new Date,ue=c.filter(u=>(u.status==="accepted"||u.stage_name==="accepted"||u.stage_name==="aceite")&&u.contract_id),P=u=>u.status==="sent"||u.stage_name==="sent"||u.stage_name==="enviada",re=u=>it(L,Ee(u.sent_at||u.updated_at||u.created_at)),Z=Q?c.filter(u=>{if(!P(u))return!1;const Ce=re(u);return Ce>=b&&Ce<z}):[],Y=ee?c.filter(u=>P(u)?re(u)>=z:!1):[],ce=F?c.filter(u=>!u.valid_until&&u.status!=="rejected"&&u.stage_name!=="rejected"&&u.stage_name!=="rejeitada"):[],j=ae?c.filter(u=>u.valid_until&&Lt(Ee(u.valid_until))&&u.status!=="accepted"&&u.stage_name!=="accepted"&&u.stage_name!=="aceite"&&u.status!=="rejected"&&u.stage_name!=="rejected"&&u.stage_name!=="rejeitada"):[],v=u=>u.status==="draft"||u.status==="rascunho"||u.stage_name==="draft"||u.stage_name==="rascunho",h=y?c.filter(u=>v(u)?it(L,Ee(u.updated_at||u.created_at))>=m:!1):[],$=ue.length+Z.length+Y.length+ce.length+j.length+h.length;if($===0)return null;const G=j.length>0||Y.length>0?"destructive":Z.length>0?"warning":ce.length>0?"info":"success",Me={destructive:"border-red-300 bg-red-50 dark:bg-red-950/30 dark:border-red-800",warning:"border-orange-300 bg-orange-50 dark:bg-orange-950/30 dark:border-orange-800",info:"border-blue-300 bg-blue-50 dark:bg-blue-950/30 dark:border-blue-800",success:"border-green-300 bg-green-50 dark:bg-green-950/30 dark:border-green-800"},D={destructive:"text-red-600",warning:"text-orange-600",info:"text-blue-600",success:"text-green-600"},M={destructive:"text-red-800 dark:text-red-300",warning:"text-orange-800 dark:text-orange-300",info:"text-blue-800 dark:text-blue-300",success:"text-green-800 dark:text-green-300"};return e.jsx(ql,{open:T,onOpenChange:ie,children:e.jsxs("div",{className:we("rounded-lg border",Me[G]),children:[e.jsx(Il,{asChild:!0,children:e.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-4 py-2.5 text-left",children:[e.jsx(qn,{
4className:we("h-4 w-4 flex-shrink-0",D[G])}),e.jsxs("span",{className:we("text-sm font-medium",M[G]),children:[$," ",$===1?"alerta activo":"alertas activos"]}),e.jsxs("div",{className:"flex items-center gap-1.5 ml-1",children:[j.length+Y.length>0&&e.jsxs(de,{variant:"outline",className:"h-5 text-[10px] border-red-400 text-red-700 bg-red-100/50 dark:bg-red-950/50 dark:text-red-300",children:[j.length+Y.length," ",j.length>0&&Y.length===0?`expirada${j.length>1?"s":""}`:"urgente"]}),Z.length>0&&e.jsxs(de,{variant:"outline",className:"h-5 text-[10px] border-orange-400 text-orange-700 bg-orange-100/50 dark:bg-orange-950/50 dark:text-orange-300",children:[Z.length," sem resposta"]}),ce.length>0&&e.jsxs(de,{variant:"outline",className:"h-5 text-[10px] border-blue-400 text-blue-700 bg-blue-100/50 dark:bg-blue-950/50 dark:text-blue-300",children:[ce.length," sem validade"]}),h.length>0&&e.jsxs(de,{variant:"outline",className:"h-5 text-[10px] border-amber-400 text-amber-700 bg-amber-100/50 dark:bg-amber-950/50 dark:text-amber-300",children:[h.length," rascunho",h.length>1?"s":""]}),ue.length>0&&e.jsxs(de,{variant:"outline",className:"h-5 text-[10px] border-green-400 text-green-700 bg-green-100/50 dark:bg-green-950/50 dark:text-green-300",children:[ue.length," aceite",ue.length>1?"s":""]})]}),e.jsx(In,{className:we("h-4 w-4 ml-auto transition-transform flex-shrink-0",D[G],T&&"rotate-180")})]})}),e.jsx(Dl,{children:e.jsxs("div",{className:"border-t border-current/10 p-2 space-y-2",children:[j.length>0&&e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 rounded-md border border-red-300 bg-red-50 dark:bg-red-950/30 dark:border-red-800",children:[e.jsx(Us,{className:"h-4 w-4 text-red-600 flex-shrink-0"}),e.jsxs("span",{className:"text-sm text-red-800 dark:text-red-300 font-medium",children:[j.length," proposta",j.length>1?"s":""," expirada",j.length>1?"s":""]}),e.jsx("span",{className:"text-sm text-red-700 dark:text-red-400 hidden md:inline",children:"— prazo de validade ultrapassado."}),e.jsx("div",{className:"ml-auto flex gap-1 flex-wrap",children:j.slice(0,3).map(u=>e.jsx(g,{size:"sm",className:"h-7 bg-red-600 hover:bg-red-700 text-white text-xs",onClick:()=>x==null?void 0:x(u.id),children:j.length===1?"Renovar validade":u.title.slice(0,15)},u.id))})]}),Y.length>0&&e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 rounded-md border border-red-300 bg-red-50 dark:bg-red-950/30 dark:border-red-800",children:[e.jsx(Us,{className:"h-4 w-4 text-red-600 flex-shrink-0"}),e.jsxs("span",{className:"text-sm text-red-800 dark:text-red-300 font-medium",children:[Y.length," proposta",Y.length>1?"s":""]}),e.jsxs("span",{className:"text-sm text-red-700 dark:text-red-400 hidden md:inline",children:["sem resposta há +",z," dias — escalar urgentemente"]}),e.jsxs("div",{className:"ml-auto flex gap-1 flex-wrap",children:[Y.slice(0,3).map(u=>e.jsx(g,{variant:"outline",size:"sm",className:"h-7 text-xs border-red-400 text-red-700 hover:bg-red-100 dark:text-red-300",onClick:()=>x==null?void 0:x(u.id),children:u.title.slice(0,15)},u.id)),e.jsx(g,{size:"sm",className:"h-7 bg-red-600 hover:bg-red-700 text-white",onClick:()=>o==null?void 0:o(Y.map(u=>u.id)),children:"Escalar"})]})]}),Z.length>0&&e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 rounded-md border border-orange-300 bg-orange-50 dark:bg-orange-950/30 dark:border-orange-800",children:[e.jsx(Ft,{className:"h-4 w-4 text-orange-600 flex-shrink-0"}),e.jsxs("span",{className:"text-sm text-orange-800 dark:text-orange-300 font-medium",children:[Z.length," proposta",Z.length>1?"s":""]}),e.jsxs("span",{className:"text-sm text-orange-700 dark:text-orange-400 hidden md:inline",children:["enviada",Z.length>1?"s":""," sem resposta há +",b," dias"]}),e.jsxs("div",{className:"ml-auto flex gap-1 flex-wrap",children:[Z.slice(0,3).map(u=>e.jsx(g,{variant:"outline",size:"sm",className:"h-7 text-xs border-orange-400 text-orange-700 hover:bg-orange-100 dark:text-orange-300",onClick:()=>x==null?void 0:x(u.id),children:u.title.slice(0,15)},u.id)),e.jsx(g,{size:"sm",className:"h-7 bg-orange-600 hover:bg-orange-700 text-white",onClick:()=>o==null?void 0:o(Z.map(u=>u.id)),children:"Enviar follow-up"})]})]}),ce.length>0&&e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 rounded-md border border-blue-300 bg-blue-50 dark:bg-blue-950/30 dark:border-blue-800",children:[e.jsx(El,{className:"h-4 w-4 text-blue-600 flex-shrink-0"}),e.jsxs("span",{className:"text-sm text-blue-800 dark:text-blue-300 font-medium",children:[ce.length," proposta",ce.length>
41?"s":""]}),e.jsx("span",{className:"text-sm text-blue-700 dark:text-blue-400 hidden md:inline",children:"sem data de validade definida"}),e.jsx("div",{className:"ml-auto flex gap-1 flex-wrap",children:ce.slice(0,3).map(u=>e.jsx(g,{size:"sm",className:"h-7 bg-blue-600 hover:bg-blue-700 text-white text-xs",onClick:()=>x==null?void 0:x(u.id),children:ce.length===1?"Definir validade":u.title.slice(0,15)},u.id))})]}),h.length>0&&e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 rounded-md border border-amber-300 bg-amber-50 dark:bg-amber-950/30 dark:border-amber-800",children:[e.jsx(Ft,{className:"h-4 w-4 text-amber-600 flex-shrink-0"}),e.jsxs("span",{className:"text-sm text-amber-800 dark:text-amber-300 font-medium",children:[h.length," rascunho",h.length>1?"s":""]}),e.jsxs("span",{className:"text-sm text-amber-700 dark:text-amber-400 hidden md:inline",children:["parado",h.length>1?"s":""," há +",m," dias — enviar ao cliente?"]}),e.jsx("div",{className:"ml-auto flex gap-1 flex-wrap",children:h.slice(0,3).map(u=>{const Ce=it(L,Ee(u.updated_at||u.created_at));return e.jsxs(g,{variant:"outline",size:"sm",className:"h-7 text-xs border-amber-400 text-amber-700 hover:bg-amber-100 dark:text-amber-300",onClick:()=>x==null?void 0:x(u.id),children:[u.title.slice(0,15)," · ",Ce,"d"]},u.id)})})]}),ue.length>0&&e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 rounded-md border border-green-300 bg-green-50 dark:bg-green-950/30 dark:border-green-800",children:[e.jsx(ka,{className:"h-4 w-4 text-green-600 flex-shrink-0"}),e.jsxs("span",{className:"text-sm text-green-800 dark:text-green-300 font-medium",children:[ue.length," proposta",ue.length>1?"s":""," aceite",ue.length>1?"s":""]}),e.jsx("span",{className:"text-sm text-green-700 dark:text-green-400 hidden md:inline",children:"— contratos criados automaticamente."}),e.jsx("div",{className:"ml-auto",children:e.jsx(g,{size:"sm",className:"h-7 bg-green-600 hover:bg-green-700 text-white",onClick:_,children:"Ver contratos"})})]})]})})]})})}function Yl(c){const _=c.replace("#","");if(_.length!==6)return"#ffffff";const o=parseInt(_.slice(0,2),16),q=parseInt(_.slice(2,4),16),x=parseInt(_.slice(4,6),16);return(o*299+q*587+x*114)/1e3>=140?"#0f172a":"#ffffff"}function eo({proposals:c,workflowStages:_,getProposalStage:o,comercialNamesMap:q,stageCounts:x,stageValues:b,isLoading:z,hasError:Q,errorMessage:ee}){const ae=n.useMemo(()=>{const j=[..._].filter(v=>!v.is_lost).sort((v,h)=>v.stage_order-h.stage_order);return j.map((v,h)=>{const $=x[v.id]||0,G=b[v.id]||0,Me=j[h+1],D=Me&&x[Me.id]||0,M=$>0&&Me?Math.round(D/$*100):null;return{stage:v,count:$,value:G,conversionRate:M}})},[_,x,b]),F=n.useMemo(()=>{const j=new Set(_.filter($=>$.is_lost).map($=>$.id));let v=0,h=0;return c.forEach($=>{var Me;const G=(Me=o($))==null?void 0:Me.id;G&&j.has(G)&&(v++,h+=Number($.value))}),{count:v,value:h}},[c,_,o]),y=n.useMemo(()=>{const j=new Set(_.filter(h=>h.is_won).map(h=>h.id)),v={};return c.forEach(h=>{const $=o(h);if(!$||!j.has($.id)||!h.accepted_at)return;const G=h.accepted_at.slice(0,7);v[G]=(v[G]||0)+Number(h.value)}),Object.entries(v).sort((h,$)=>h[0].localeCompare($[0])).slice(-6)},[c,_,o]),m=n.useMemo(()=>{const j=new Set(_.filter(h=>h.is_lost).map(h=>h.id)),v={};return c.forEach(h=>{const $=o(h);if($&&j.has($.id)){const G=h.rejection_reason||"Outro";v[G]=(v[G]||0)+1}}),Object.entries(v).sort((h,$)=>$[1]-h[1])},[c,_,o]),T=n.useMemo(()=>{const j={};return c.forEach(v=>{const h=v.assigned_to??"__unassigned__",$=v.assigned_to?q[v.assigned_to]||"...":"Não atribuído";j[h]||(j[h]={label:$,count:0,value:0}),j[h].label=$,j[h].count++,j[h].value+=Number(v.value)}),Object.entries(j).sort((v,h)=>h[1].value-v[1].value)},[c,q]),ie=n.useMemo(()=>{const j=new Set(_.filter(G=>G.is_won).map(G=>G.id)),v=new Set(_.filter(G=>G.is_lost).map(G=>G.id));let h=0,$=0;return c.forEach(G=>{var D;const Me=(D=o(G))==null?void 0:D.id;Me&&(j.has(Me)?(h++,$++):v.has(Me)&&$++)}),{won:h,terminal:$,rate:$>0?Math.round(h/$*100):null}},[c,_,o]),L=n.useMemo(()=>{const j=new Set(_.filter(h=>h.is_won||h.is_lost).map(h=>h.id)),v=Date.now();return c.filter(h=>{var G;const $=(G=o(h))==null?void 0:G.id;
4return!$||j.has($)?!1:h.valid_until?Date.parse(h.valid_until)<v:!1}).length},[c,_,o]),ue=n.useMemo(()=>{const j=new Set(_.filter(v=>v.is_won||v.is_lost).map(v=>v.id));return c.reduce((v,h)=>{var G;const $=(G=o(h))==null?void 0:G.id;return!$||j.has($)?v:v+Number(h.value)},0)},[c,_,o]);if(Q)return e.jsx("div",{className:"p-4 md:px-6",children:e.jsx(_e,{children:e.jsx(Se,{className:"p-6 text-sm text-destructive",children:ee||"Erro ao carregar dashboard."})})});if(z)return e.jsxs("div",{className:"p-4 md:px-6 space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:4}).map((j,v)=>e.jsx(os,{className:"h-20 w-full"},v))}),Array.from({length:3}).map((j,v)=>e.jsx(os,{className:"h-48 w-full"},v))]});if(c.length===0)return e.jsx("div",{className:"p-4 md:px-6",children:e.jsx(_e,{children:e.jsxs(Se,{className:"p-10 text-center space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Ainda não há propostas para mostrar."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cria a primeira proposta para começar a ver métricas neste dashboard."})]})})});const P=Math.max(...ae.map(j=>j.count),1),re=Math.max(...T.map(j=>j[1].value),1),Z=Math.max(...y.map(j=>j[1]),1),Y=m.reduce((j,v)=>j+v[1],0),ce=["#ef4444","#f97316","#eab308","#6b7280","#a855f7","#06b6d4"];return e.jsxs("div",{className:"p-4 md:px-6 space-y-6 overflow-y-auto h-full",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(_e,{children:e.jsxs(Se,{className:"p-4",children:[e.jsx("div",{className:"text-xs text-muted-foreground uppercase",children:"Taxa de Ganho"}),e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:ie.rate===null?"—":`${ie.rate}%`}),e.jsxs("div",{className:"text-[11px] text-muted-foreground mt-1",children:[ie.won," / ",ie.terminal," terminais"]})]})}),e.jsx(_e,{children:e.jsxs(Se,{className:"p-4",children:[e.jsx("div",{className:"text-xs text-muted-foreground uppercase",children:"Expiradas em Aberto"}),e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:L}),e.jsx("div",{className:"text-[11px] text-muted-foreground mt-1",children:"não terminais com validade ultrapassada"})]})}),e.jsx(_e,{children:e.jsxs(Se,{className:"p-4",children:[e.jsx("div",{className:"text-xs text-muted-foreground uppercase",children:"Aceites Totais"}),e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:ie.won})]})}),e.jsx(_e,{children:e.jsxs(Se,{className:"p-4",children:[e.jsx("div",{className:"text-xs text-muted-foreground uppercase",children:"Pipeline em Curso"}),e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:H(ue)})]})})]}),e.jsxs(_e,{children:[e.jsx(Ds,{className:"pb-3",children:e.jsx(Es,{className:"text-base",children:"Funil de Conversão"})}),e.jsxs(Se,{children:[e.jsx("div",{className:"space-y-3",children:ae.map((j,v)=>{const h=Yl(j.stage.color);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-28 text-sm font-medium truncate",children:j.stage.label}),e.jsx("div",{className:"flex-1 h-8 bg-muted rounded-md overflow-hidden relative",children:e.jsx("div",{className:"h-full rounded-md transition-all flex items-center px-3",style:{width:`${Math.max(j.count/P*100,8)}%`,backgroundColor:j.stage.color+"CC"},children:e.jsx("span",{className:"text-xs font-bold",style:{color:h},children:j.count})})}),e.jsx("div",{className:"w-24 text-right text-sm font-medium tabular-nums",children:H(j.value)})]}),j.conversionRate!==null&&v<ae.length-1&&e.jsxs("div",{className:"ml-28 pl-6 py-0.5 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"text-primary font-semibold",children:[j.conversionRate,"%"]})," face à etapa seguinte →"]})]},j.stage.id)})}),F.count>0&&e.jsxs("div",{className:"mt-4 pt-3 border-t flex items-center justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:"Fugas do funil (Perdidas)"}),e.jsxs("span",{className:"tabular-nums",children:[e.jsx("span",{className:"font-semibold text-foreground",children:F.count})," · ",H(F.value)]})]}),e.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:"O funil usa os mesmos totais dos cards por etapa. Conversão = total da etapa seguinte dividido pelo total da etapa atual."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(_e,{children:[e.jsx(Ds,{className:"pb-3",children:e.jsx(Es,{className:"text-base",children:"Propostas por Comercial"})}),e.jsx(Se,{children:e.jsx(ds,{className:"h-80 pr-2",children:e.jsxs("div",{className:"space-y-3",children:[T.map(([j,v])=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-32 text-sm truncate",children:v.label}),e.jsx("div",{className:"flex-1 h-6 bg-muted rounded overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary/70 rounded",style:{width:`${v.value/re*100}%`}})}),e.jsx(de,{variant:"secondary",className:"text-xs",children:v.count}),e.jsx("span",{className:"text-xs font-medium tabular-nums w-20 text-right",children:H(v.value)})]},j)),T.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Sem propostas atribuídas."})]})})})]}),e.jsxs(_e,{children:[e.jsx(Ds,{className:"pb-3",children:e.jsx(Es,{className:"text-base",children:"Valor Aceite por Mês"})}),e.jsx(Se,{children:e.jsxs("div",{className:"flex items-end gap-2 h-40",children:[y.map(([j,v])=>e.jsxs("div",{className:"flex-1 flex flex-col items-center gap-1",children:[e.jsx("span",{className:"text-xs font-medium tabular-nums",children:H(v)}),e.jsx("div",{className:"w-full bg-muted rounded-t overflow-hidden flex-1 flex items-end",children:e.jsx("div",{className:"w-full bg-primary/60 rounded-t transition-all",style:{height:`${v/Z*100}%`}})}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[j.slice(5),"/",j.slice(2,4)]})]},j)),y.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4 w-full",children:"Sem propostas aceites com data de aceitação registada."})]})})]})]}),m.length>0&&e.jsxs(_e,{children:[e.jsx(Ds,{className:"pb-3",children:e.jsx(Es,{className:"text-base",children:"Motivos de Rejeição"})}),e.jsx(Se,{children:e.jsx("div",{className:"space-y-2",children:m.map(([j,v],h)=>{const $=ce[h%ce.length];return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-32 text-sm truncate",children:j}),e.jsx("div",{className:"flex-1 h-5 bg-muted rounded overflow-hidden",children:e.jsx("div",{className:"h-full rounded transition-all",style:{width:`${v/Y*100}%`,backgroundColor:$}})}),e.jsxs("span",{className:"text-xs font-medium tabular-nums w-10 text-right",children:[Math.round(v/Y*100),"%"]}),e.jsx(de,{variant:"outline",className:"text-xs",children:v})]},j)})})})]})]})}function to({dealExists:c,quoteExists:_,proposalStatus:o,contractCreated:q,pipelineLabel:x}){const b=o==="accepted"||o==="aceite",z=[{label:"P",done:c,current:!1,info:c?"Pedido ✓":"Sem pedido"},{label:"O",done:_,current:!1,info:_?"Orçamento ✓":"Sem orçamento"},{label:"P",done:b,current:!b,info:`Proposta · ${o}`},{label:"C",done:q,current:!1,info:q?"Contrato ✓":"Contrato não criado"}];return e.jsx(Dn,{delayDuration:200,children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("div",{className:"flex items-center gap-0.5",children:z.map((Q,ee)=>e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(En,{children:[e.jsx(Mn,{asChild:!0,children:e.jsx("div",{className:we("w-5 h-5 rounded-full flex items-center justify-center text-[9px] font-bold border-2 transition-colors",Q.done&&"bg-green-500 border-green-500 text-white",Q.current&&!Q.done&&"bg-primary border-primary text-primary-foreground",!Q.done&&!Q.current&&"bg-muted border-muted-foreground
4/30 text-muted-foreground"),children:Q.done?"✓":Q.label})}),e.jsx(An,{side:"top",className:"text-xs",children:Q.info})]}),ee<z.length-1&&e.jsx("div",{className:we("w-3 h-0.5",Q.done?"bg-green-500":"bg-muted-foreground/20")})]},ee))}),x&&e.jsx("span",{className:"text-[9px] text-muted-foreground truncate max-w-[100px]",children:x})]})})}function so({proposals:c,workflowStages:_,getProposalStage:o,onMoveStage:q,onViewProposal:x}){const[b,z]=n.useState(null),Q=n.useMemo(()=>[..._].sort((y,m)=>y.stage_order-m.stage_order).map(y=>{const m=c.filter(ie=>{var L;return((L=o(ie))==null?void 0:L.id)===y.id}),T=m.reduce((ie,L)=>ie+Number(L.value),0);return{stage:y,proposals:m,totalValue:T}}),[c,_,o]),ee=F=>{if(!F.destination)return;const{draggableId:y,source:m,destination:T}=F;if(m.droppableId===T.droppableId)return;const ie=_.find(L=>L.id===T.droppableId);if(ie)if(ie.is_won){const L=c.find(ue=>ue.id===y);z({open:!0,proposalId:y,proposalTitle:(L==null?void 0:L.title)||"",stageId:T.droppableId,oldStageId:m.droppableId,stageName:ie.label})}else q(y,T.droppableId)},ae=()=>{b&&(q(b.proposalId,b.stageId),z(null))};return e.jsxs(e.Fragment,{children:[e.jsx(Ml,{onDragEnd:ee,children:e.jsx("div",{className:"flex gap-3 overflow-x-auto pb-4 h-full px-4 md:px-6 mt-3",children:Q.map(({stage:F,proposals:y,totalValue:m})=>e.jsx(Al,{droppableId:F.id,children:(T,ie)=>e.jsxs("div",{ref:T.innerRef,...T.droppableProps,className:we("flex-shrink-0 w-[280px] flex flex-col rounded-lg border bg-muted/30 transition-colors",ie.isDraggingOver&&"bg-primary/5 border-primary/30"),children:[e.jsxs("div",{className:"p-3 border-b flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-3 w-3 rounded-full",style:{backgroundColor:F.color}}),e.jsx("span",{className:"font-semibold text-sm",children:F.label}),e.jsx(de,{variant:"secondary",className:"text-xs h-5 px-1.5",children:y.length})]}),e.jsx("span",{className:"text-xs text-muted-foreground font-medium tabular-nums",children:H(m)})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-2 space-y-2 min-h-[200px]",children:[y.map((L,ue)=>{const P=it(new Date,new Date(L.created_at)),re=P>30;return e.jsx(Tl,{draggableId:L.id,index:ue,children:(Z,Y)=>e.jsx(_e,{ref:Z.innerRef,...Z.draggableProps,...Z.dragHandleProps,className:we("p-3 cursor-grab active:cursor-grabbing transition-shadow",Y.isDragging&&"shadow-lg ring-2 ring-primary/20",re&&"border-l-4 border-l-amber-500",L.value===0&&"border-l-4 border-l-destructive"),onClick:()=>x(L),children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-1",children:e.jsx("span",{className:"font-medium text-sm leading-tight line-clamp-2",children:L.title})}),L.entity_name&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Da,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:L.entity_name})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:we("font-semibold text-sm tabular-nums",L.value===0&&"text-destructive"),children:[H(L.value),L.value===0&&e.jsx(Us,{className:"inline h-3 w-3 ml-1"})]}),e.jsxs("span",{className:we("text-xs tabular-nums",re?"text-amber-600 font-semibold":"text-muted-foreground"),children:[P,"d"]})]}),L.assigned_to_name&&e.jsx("div",{className:"text-[11px] text-muted-foreground truncate",children:L.assigned_to_name}),e.jsxs("div",{className:"flex gap-1 pt-1 border-t border-border/50",children:[L.entity_phone&&e.jsx(g,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,onClick:ce=>ce.stopPropagation(),children:e.jsx("a",{href:`tel:${L.entity_phone}`,children:e.jsx(Xt,{className:"h-3 w-3 text-emerald-600"})})}),L.entity_email&&e.jsx(g,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,onClick:ce=>ce.stopPropagation(),children:e.jsx("a",{href:`mailto:${L.entity_email}`,children:e.jsx(ht,{className:"h-3 w-3 text-primary"})})}),e.jsx(g,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:ce=>{ce.stopPropagation(),x(L)},children:e.jsx(rt,{className:"h-3 w-3"})})]})]})})},L.id)}),T.placeholder,y.length===0&&e.jsx("div",{className:"text-center text-xs text-muted-foreground py-8 px-2",children:"Arrastar propostas para aqui"})]})]})},F.id))})}),e.jsx($s,{open:!!(b!=null&&b.open),onOpenChange:F=>{F||z(null)},children:e.jsxs(Os,{children:[e.jsxs(Ls,{children:[e.jsx(Vs,{children:"Aceitar Proposta?"}),e.jsxs(Fs,{className:"space-y-2",children:[e.jsxs("p",{children:["Está a mover ",e.jsxs("strong",{children:['"',b==null?void 0:b.proposalTitle,'"']})," para ",e.jsx("strong",{children:b==null?void 0:b.stageName}),"."]}
4),e.jsxs("p",{className:"text-amber-600 dark:text-amber-400 flex items-center gap-2",children:[e.jsx(Us,{className:"h-4 w-4 flex-shrink-0"}),"Aceitar esta proposta cria um contrato automaticamente pelo workflow. Deseja continuar?"]})]})]}),e.jsxs(Qs,{children:[e.jsx(Bs,{children:"Cancelar"}),e.jsx(Hs,{onClick:ae,children:"Aceitar e criar contrato"})]})]})})]})}const Pa=c=>Math.round((Number.isFinite(c)?c:0)*100)/100,ao=c=>{if(!c)return null;if(typeof c=="string")try{return JSON.parse(c)}catch{return null}return typeof c=="object"?c:null},Yi=c=>{const _=ao(c.selected_attributes);return Array.isArray(_==null?void 0:_.bundle_components)?_.bundle_components:Array.isArray(_==null?void 0:_.bundle_components_data)?_.bundle_components_data:[]},ya=c=>{const _=parseFloat(String(c.qt??1))||1,o=Yi(c),q=o.reduce((b,z)=>b+(Number(z==null?void 0:z.unit_price)||0)*((Number(z==null?void 0:z.quantity)||0)*_),0),x=o.length>0&&q>0?q:parseFloat(String(c.total_sem_iva||0));return Pa(x)},io=(c,_)=>{const o=_.reduce((q,x)=>(x.quote_id&&(q[x.quote_id]||(q[x.quote_id]=[]),q[x.quote_id].push(x)),q),{});return c.reduce((q,x)=>{const b=o[x.id]||[];if(b.length===0)return q;const z=1-(Number(x.desconto_global_percent)||0)/100,Q=b.reduce((F,y)=>F+ya(y),0),ee=Pa(Q*z),ae=b.reduce((F,y)=>{var re;const m=parseFloat(String(y.qt??1))||1,T=(re=y==null?void 0:y.selected_attributes)==null?void 0:re.iva_override;if(typeof T=="number"&&!Number.isNaN(T)){const Z=ya(y)*z;return F+Z*(Number(T)/100)}const L=Yi(y);if(L.length>0)return F+L.reduce((Z,Y)=>{const ce=(Number(Y==null?void 0:Y.unit_price)||0)*((Number(Y==null?void 0:Y.quantity)||0)*m)*z,j=Number((Y==null?void 0:Y.vat_rate)??y.iva_percent??23)||0;return Z+ce*j/100},0);const ue=ya(y)*z,P=Number(y.iva_percent??23)||0;return F+ue*P/100},0);return q[x.id]={subtotal:ee,total:Pa(ee+ae)},q},{})},Dd=()=>{var ki,Si;const[c,_]=n.useState([]),[o,q]=n.useState([]),[x,b]=n.useState([]),[z,Q]=n.useState(!0),[ee,ae]=n.useState(!1),[F,y]=n.useState(!1),[m,T]=n.useState(null),[ie,L]=n.useState(!1),[ue,P]=n.useState(null),[re,Z]=n.useState(null),[Y,ce]=n.useState({}),[j,v]=n.useState(!1),[h,$]=n.useState(null),[G,Me]=n.useState(!1),{toast:D}=Ws(),M=Tn(),[u]=Rn(),{hasPermission:Ce,loading:st,isSystemAdmin:Je}=zn(),{t:R}=Ia(),{activeCompany:i,userType:O,isLoading:ne}=Gi(),{comercialUsers:te}=il((i==null?void 0:i.id)||null),{getPermissionScope:Ae,anewUserId:je,teamMemberIds:Pe,loading:ze}=al(),{alerts:pt,dismissAlert:ye}=Cl("proposal",i==null?void 0:i.id),$e=jl(),[at,Ke]=n.useState([]);n.useEffect(()=>{if(!(i!=null&&i.id)){Ke([]);return}(async()=>{const t=[i.id],s=[i.id];for(;s.length>0;){const a=s.shift(),{data:r}=await d.from("anew_hierarchy").select("child_org_id").eq("parent_org_id",a);if(r)for(const l of r)t.includes(l.child_org_id)||(t.push(l.child_org_id),s.push(l.child_org_id))}Ke(t)})()},[i==null?void 0:i.id]);const Fe=u.get("stage"),[se,qe]=n.useState("lista"),[W,Te]=n.useState(""),[ct,er]=n.useState("");n.useEffect(()=>{const t=setTimeout(()=>er(W),400);return()=>clearTimeout(t)},[W]);const[Js,Ea]=n.useState(null),Ma=n.useRef(null);n.useEffect(()=>{const t=ct.trim();if(t.length<3){Ea(null);return}let s=!1;return(async()=>{const{ids:a,truncated:r}=await Ji(t);s||(r&&Ma.current!==t&&(Ma.current=t,D({title:"Demasiados resultados",description:"Mais de 1000 resultados — refine a pesquisa para ver todos."})),Ea(new Set(a)))})(),()=>{s=!0}},[ct]);const[ft,Zt]=n.useState(Fe||"all"),[lt,Ks]=n.useState(void 0),[ot,Xs]=n.useState(void 0),[ms,tr]=n.useState("created_at"),[us,Aa]=n.useState("desc"),[Yt,Ta]=n.useState(!1),[Ct,Ra]=n.useState("all"),[Zs,sr]=n.useState({}),[Pt,Ys]=n.useState(!1),[qt,ea]=n.useState(!1),[xs,za]=n.useState(!1);n.useEffect(()=>{Fe&&Zt(Fe)},[Fe]);const[I,Oe]=n.useState({title:"",description:"",value:"",deal_id:"",valid_until:"",notes:"",stage_id:"",template_id:"",assigned_to:""}),[es,ar]=n.useState([]),[ir,hs]=n.useState(!1),[ta,sa]=n.useState(null),[aa,$a]=n.useState("none"),[ia,Oa]=n.useState(!1),[ra,La]=n.useState(null),[ps,na]=n.useState({}),[rr,fs]=n.useState(""),[la,Qt]=n.useState([]),[nr,It]=n.useState(!1),[U,ts]=n.useState(null),[xe,Bt]=n.useState(null),[Va,gs]=n.useState(""),[Fa,_s]=n.useState([]),[Qa,Ba]=n.useState(!1),[Le,dt]=n.useState([]),[lr,Ha]=n.useState([]),[js,vs]=n.useState([]),[Qe,ss]=n.useState([]),[Ua,Ga]=n.useState(null);n.useEffect(()=>{const t=Le.reduce((r,l)=>r+(l.total||0),0),s=Qe.reduce((r,l)=>r+As(l),0),a=t+s;a>0&&Oe(r=>({...r,value:a.toFixed(2)}))},[Qe,Le]),n.useEffect(()=>{const t=i==null?void 0:i.id,s=(U==null?void 0:U.id)||I.deal_id||null,a=(xe==null?void 0:xe.entityId)||null;if(!t||!s&&!a){Ha([]);return}let r=!1;return(async()=>{let l=d.from("quotes").select("id, quote_number, total, estado, deal_id, entity_id").eq("organization_id",t).is("proposal_id",null).is("deleted_at",null).order("created_at",{ascending:!1}).limit(20);s?l=l.eq("deal_id",s).eq("estado","rascunho"):a&&(l=l.eq("entity_id",a));const{data:p}=await l;r||Ha((p||[]).map(w=>({id:w.id,quote_number:w.quote_number,total:w.total,estado:w.estado})))})(),()=>{r=!0}},[U==null?void 0:U.id,I.deal_id,xe==null?void 0:xe.entityId,i==null?void 0:i.id,Le.length]),n.useEffect(()=>{if(m||I.assigned_to)return;const t=i==null?void 0:i.id;if(!t)return;const s=(xe==null?void 0:xe.entityId)||null,a=(U==null?void 0:U.id)||I.deal_id||null;if(!s&&!a){je&&Oe(l=>l.assigned_to?l:{...l,assigned_to:je});return}let r=!1;return(async()=>{const{data:l,error:p}=await d.rpc("resolve_proposal_commercial",{p_entity_id:s,p_deal_id:a,p_org_id:t,p_created_by:je||null});if(!r){if(p){console.error("[Proposals] resolve_proposal_commercial error:",p);return}
4l&&Oe(w=>w.assigned_to?w:{...w,assigned_to:l})}})(),()=>{r=!0}},[m,I.assigned_to,i==null?void 0:i.id,xe==null?void 0:xe.entityId,U==null?void 0:U.id,I.deal_id,je]);const bs=n.useCallback(t=>({id:t.id,quote_number:t.quote_number,total:t.total,estado:t.estado||"rascunho"}),[]),Wa=n.useCallback(async t=>{if(!(i!=null&&i.id)||!t)return[];const{data:s,error:a}=await d.from("quotes").select("id, quote_number, total, estado, created_at").eq("organization_id",i.id).eq("entity_id",t).is("proposal_id",null).is("deleted_at",null).order("created_at",{ascending:!1}).limit(20);return a?(console.error("Error loading quotes for selected entity:",a),[]):(s||[]).map(bs)},[i==null?void 0:i.id,bs]),or=n.useCallback(async t=>{if(Bt(t),dt([]),Qt([]),It(!1),!(t!=null&&t.entityId))return;const s=await Wa(t.entityId);s.length>0&&dt(s);const a=at.length>0?at:i!=null&&i.id?[i.id]:[];if(a.length>0){const{data:r}=await d.from("deals").select("id, title, probability, value, description, expected_close_date, entity_id, deal_stages(name)").in("organization_id",a).eq("entity_id",t.entityId).order("created_at",{ascending:!1}).limit(20);r&&r.length>0&&(Qt(r.map(l=>{var p;return{id:l.id,title:l.title,probability:l.probability,value:l.value,expected_close_date:l.expected_close_date,stage_name:((p=l.deal_stages)==null?void 0:p.name)||null,lead_name:t.name||null,lead_phone:t.phone||null,lead_email:t.email||null}})),It(!0))}},[Wa,at,i==null?void 0:i.id]),dr=n.useCallback(async t=>{const s=t.trim();if(gs(t),s.length<2){_s([]);return}const a=i==null?void 0:i.id;if(!a)return;const r=`%${s}%`,l=d.from("quotes").select("id, quote_number, total, estado, title, created_at").eq("organization_id",a).or(`quote_number.ilike.${r},title.ilike.${r}`).is("proposal_id",null).is("deleted_at",null).order("created_at",{ascending:!1}).limit(10),p=Promise.all([d.from("anew_entities").select("id").or(`display_name.ilike.${r},first_name.ilike.${r},last_name.ilike.${r}`).limit(100),d.from("anew_entity_emails").select("entity_id").ilike("email",r).limit(100),d.from("anew_entity_phones").select("entity_id").ilike("phone_number",r).limit(100)]).then(([le,ve,De])=>Array.from(new Set([...(le.data||[]).map(J=>J.id),...(ve.data||[]).map(J=>J.entity_id),...(De.data||[]).map(J=>J.entity_id)].filter(Boolean)))),[{data:w,error:A},N]=await Promise.all([l,p]);A&&console.error("Error searching quotes directly:",A);let V=[];if(N.length>0){const{data:le,error:ve}=await d.from("quotes").select("id, quote_number, total, estado, title, created_at").eq("organization_id",a).in("entity_id",N).is("proposal_id",null).is("deleted_at",null).order("created_at",{ascending:!1}).limit(20);ve&&console.error("Error searching quotes by entity:",ve),V=le||[]}const he=Array.from(new Map([...w||[],...V].map(le=>[le.id,le])).values());_s(he.map(bs))},[i==null?void 0:i.id,bs]),[Xe,Dt]=n.useState([]),Ja=n.useMemo(()=>new Set(Xe),[Xe]),[cr,Ka]=n.useState(!1),[mr,Ns]=n.useState(!1),[as,Xa]=n.useState(""),[ur,oa]=n.useState(!1),[Et,da]=n.useState(null),{generatePortalAccess:ca,loading:Za}=rl({onSuccess:()=>ke()}),[xr,is]=n.useState(!1),[hr,ws]=n.useState(null),[pr,ma]=n.useState(!1),[fr,Ya]=n.useState(null),[gr,ei]=n.useState(""),[_r,ti]=n.useState(!1),[jr,ys]=n.useState(!1),[si,ai]=n.useState(null),[vr,ua]=n.useState(!1),[ks,xa]=n.useState(""),[br,ii]=n.useState(!1),[Ue,Nr]=n.useState(null),[wr,ha]=n.useState(!1),[yr,ri]=n.useState(null),[kr,Ss]=n.useState(!1),[ni,Sr]=n.useState(null),[li,oi]=n.useState(""),[rs,Cr]=n.useState({}),[Pr,qr]=n.useState(new Set),[pa,Ir]=n.useState({}),[di,Dr]=n.useState({}),[fa,Er]=n.useState({}),[Mt,ci]=n.useState({}),[mi,ui]=n.useState({}),[Ht,xi]=n.useState({}),Ut=n.useRef(!1);n.useEffect(()=>{!st&&i&&!Ce("proposals.view")&&M("/dashboard")},[st,Ce,M,i]);const hi=n.useCallback(async()=>{const{data:t}=await d.from("proposal_workflow_stages").select("id, name, label, color, stage_order, is_active, organization_id, is_final, is_won, is_lost").eq("organization_id",(i==null?void 0:i.id)||"").eq("is_active",!0).order("stage_order");if(t&&t.length>0)b(t);else{const{data:s}=await d.from("proposal_workflow_stages").select("id, name, label, color, stage_order, is_active, organization_id, is_final, is_won, is_lost").is("organization_id",null).eq("is_active",!0).order("stage_order");b(s||[])}},[i==null?void 0:i.id]),pi=n.useCallback(async()=>
4{if(!(i!=null&&i.id))return;const{data:t}=await d.from("proposal_templates").select("id, name, is_default").eq("organization_id",i.id).eq("template_type","proposal").eq("is_active",!0).order("name");ar(t||[])},[i==null?void 0:i.id]),ke=n.useCallback(async()=>{if(!(i!=null&&i.id)||st||ze){i!=null&&i.id||(_([]),q([])),Q(!!(i!=null&&i.id));return}Q(!0);try{await Promise.all([hi(),pi()]);const{data:{user:t}}=await d.auth.getUser(),s=Ae("proposals.view");let a=[],r=[];if(s==="ORG"||Je){const[p,w]=await Promise.all([d.from("proposals").select("*, deals(id, title, probability), proposal_workflow_stages(*), proposal_items(subtotal, vat_amount, total)").eq("organization_id",i.id).is("deleted_at",null).order("created_at",{ascending:!1}),d.from("deals").select("id, title, probability").eq("organization_id",i.id)]);if(p.error)throw p.error;if(w.error)throw w.error;a=p.data||[],r=w.data||[]}else if((s==="TEAM"||s==="OWNED")&&(t!=null&&t.id)){const{data:p}=await d.from("anew_users").select("id").eq("auth_user_id",t.id).maybeSingle(),w=p==null?void 0:p.id,A=new Set;if(w&&A.add(w),s==="TEAM"&&Pe.length>0&&Pe.forEach(N=>A.add(N)),A.size===0)a=[],r=[];else{const{data:N}=await d.from("anew_leads").select("id").eq("organization_id",i.id).in("assigned_to",Array.from(A)),V=(N||[]).map(f=>f.id);let he=[];if(V.length>0){const{data:f}=await d.from("deals").select("id, title, probability").eq("organization_id",i.id).in("lead_id",V);r=f||[],he=r.map(k=>k.id)}const le=Array.from(A).join(","),ve=[`created_by.in.(${le})`,`assigned_to.in.(${le})`];he.length>0&&ve.push(`deal_id.in.(${he.join(",")})`);const{data:De,error:J}=await d.from("proposals").select("*, deals(id, title, probability), proposal_workflow_stages(*), proposal_items(subtotal, vat_amount, total)").eq("organization_id",i.id).is("deleted_at",null).or(ve.join(",")).order("created_at",{ascending:!1});if(J)throw J;a=De||[]}}if(a.length>0){const p=a.map(C=>C.id),{data:w}=await d.from("pipeline_links").select("id, proposal_id, deal_id, quote_id, contract_id, status").in("proposal_id",p),A={};(w||[]).forEach(C=>{A[C.proposal_id]=C}),Cr(A);const N=Array.from(new Set((w||[]).map(C=>C.contract_id).filter(Boolean)));if(N.length>0){const C={};for(let X=0;X<N.length;X+=200){const fe=N.slice(X,X+200),{data:be}=await d.from("client_contracts").select("id, status, contract_number").in("id",fe).is("deleted_at",null);(be||[]).forEach(We=>{C[We.id]=We})}ce(C)}else ce({});const{data:V}=await d.from("quotes").select("id, proposal_id, total, subtotal, estado, created_at, desconto_global_percent").in("proposal_id",p).not("proposal_id","is",null).is("deleted_at",null),he=(V||[]).map(C=>C.id).filter(Boolean),le=[];for(let C=0;C<he.length;C+=30){const X=he.slice(C,C+30),{data:fe,error:be}=await d.from("quote_lines").select("quote_id, qt, iva_percent, total_sem_iva, selected_attributes").in("quote_id",X).limit(1e3);if(be){console.error("[Proposals] Error loading quote lines for display totals:",be);continue}le.push(...fe||[])}const ve=io(V||[],le),De=new Set,J={},f={},k={};(V||[]).forEach(C=>{if(!C.proposal_id)return;De.add(C.proposal_id),k[C.proposal_id]=(k[C.proposal_id]||0)+(Number(C.total)||0),J[C.proposal_id]||(J[C.proposal_id]=[]);const X=ve[C.id];J[C.proposal_id].push({id:C.id,total:(X==null?void 0:X.total)??C.total,subtotal:(X==null?void 0:X.subtotal)??C.subtotal,estado:C.estado}),C.created_at&&(f[C.proposal_id]||(f[C.proposal_id]=[]),f[C.proposal_id].push(C.created_at))}),qr(De),Ir(J),Dr(f);try{let C=0;for(const X of a){if(C>=20)break;const fe=J[X.id];if(!fe||fe.length===0)continue;const be=k[X.id]||0;be<=0||Math.abs(Number(X.value||0)-be)>.01&&(C++,d.from("proposals").update({value:be}).eq("id",X.id))}}catch(C){console.warn("[Proposals] auto-heal value sync skipped:",C)}const{data:oe}=await d.from("client_portal_users").select("proposal_id, portal_status").eq("organization_id",i.id).in("proposal_id",p),K={};(oe||[]).forEach(C=>{C.proposal_id&&(K[C.proposal_id]=C.portal_status)}),Er(K);const ut=a.map(C=>C.entity_id).filter(Boolean),B=a.filter(C=>!C.entity_id&&C.deal_id).map(C=>C.deal_id);let S={};if(B.length>0){const{data:C}=await d.from("deals").select("id, entity_id").in("id",B);
4(C||[]).forEach(X=>{X.entity_id&&(S[X.id]=X.entity_id)})}const Ve=[...new Set([...ut,...Object.values(S)])];if(Ve.length>0){const[C,X,fe]=await Promise.all([d.from("anew_entities").select("id, display_name").in("id",Ve),d.from("anew_entity_emails").select("entity_id, email").in("entity_id",Ve).eq("is_primary",!0),d.from("anew_entity_phones").select("entity_id, phone_number").in("entity_id",Ve).eq("is_primary",!0)]),be={},We={},Ze={};(C.data||[]).forEach(Ne=>{be[Ne.id]=Ne.display_name}),(X.data||[]).forEach(Ne=>{We[Ne.entity_id]=Ne.email}),(fe.data||[]).forEach(Ne=>{Ze[Ne.entity_id]=Ne.phone_number}),a.forEach(Ne=>{if(!Ne.entity_id&&Ne.deal_id&&S[Ne.deal_id]){const He=S[Ne.deal_id];be[He]&&(be[`deal:${Ne.id}`]=be[He]),We[He]&&(We[`deal:${Ne.id}`]=We[He]),Ze[He]&&(Ze[`deal:${Ne.id}`]=Ze[He])}}),ci(be),ui(We),xi(Ze)}else ci({}),ui({}),xi({})}const l=Array.from(new Map((a||[]).map(p=>[p.id,p])).values());_(l),q(r)}catch(t){D({title:R("proposals.toast.loadError"),description:t.message,variant:"destructive"})}finally{Q(!1)}},[hi,pi,D,R,i==null?void 0:i.id,Je,O,st,ze,Ae,Pe]);n.useEffect(()=>{!st&&!ze&&ke()},[ke,st,ze]),n.useEffect(()=>{const t=u.get("open");if(!t||h)return;(async()=>{const a=c.find(l=>l.id===t);if(a){mt(a);return}const{data:r}=await d.from("proposals").select("*").eq("id",t).maybeSingle();r&&mt(r)})()},[u,c,h]),n.useEffect(()=>{x.length>0&&!I.stage_id&&Oe(t=>({...t,stage_id:x[0].id}))},[x,I.stage_id]);const fi=n.useMemo(()=>{const t=new Set;return c.forEach(s=>{const a=s.assigned_to;a&&t.add(a)}),Array.from(t).sort()},[c]),Mr=fi.join(",");n.useEffect(()=>{const t=fi.filter(s=>!Zs[s]);t.length!==0&&(async()=>{const{data:s}=await d.from("anew_users").select("id, name").in("id",t);s&&sr(a=>{const r={...a};return s.forEach(l=>{r[l.id]=l.name||"Utilizador"}),r})})()},[Mr]);const gi=async t=>{var l,p,w,A;T(t.id);const s=t.stage_id||((l=t.proposal_workflow_stages)==null?void 0:l.id)||((p=x[0])==null?void 0:p.id)||"";if(La(s),Oe({title:t.title,description:t.description||"",value:t.value.toString(),deal_id:t.deal_id||"",valid_until:t.valid_until||"",notes:t.notes||"",stage_id:s,template_id:t.template_id||"",assigned_to:t.assigned_to||""}),t.deal_id&&t.deals)ts({id:t.deals.id,title:t.deals.title,probability:t.deals.probability||null}),Bt(null);else{ts(null);const N=t.entity_id;if(N){const[V,he,le]=await Promise.all([d.from("anew_entities").select("id, display_name, type").eq("id",N).maybeSingle(),d.from("anew_entity_emails").select("email").eq("entity_id",N).eq("is_primary",!0).maybeSingle(),d.from("anew_entity_phones").select("phone_number").eq("entity_id",N).eq("is_primary",!0).maybeSingle()]);V.data?Bt({type:"contact",id:N,entityId:N,name:V.data.display_name,email:(w=he.data)==null?void 0:w.email,phone:(A=le.data)==null?void 0:A.phone_number}):Bt(null)}else Bt(null)}fs("");const{data:a}=await d.from("quotes").select("id, quote_number, total, estado").eq("proposal_id",t.id);dt(a?a.map(N=>({id:N.id,quote_number:N.quote_number,total:N.total,estado:N.estado})):[]),gs("");const{data:r}=await d.from("proposal_items").select("id, description, quantity, unit_price, vat_rate, sort_order").eq("proposal_id",t.id).order("sort_order");vs(r?r.map(N=>({id:N.id,description:N.description,quantity:Number(N.quantity),unit_price:Number(N.unit_price),vat_rate:Number(N.vat_rate),sort_order:N.sort_order||0})):[]),y(!0)},mt=t=>{$(t),v(!0)},_i=async t=>{if(!t)return;const s=c.find(r=>r.id===t);if(s){mt(s);return}const{data:a}=await d.from("proposals").select("*").eq("id",t).maybeSingle();a&&mt(a)},ji=t=>{var a;if(!t)return null;const s=(a=rs[t])==null?void 0:a.contract_id;return s&&Y[s]||null},Ar=t=>{P(t.id),Z(t),L(!0)},Tr=async()=>{if(!ue)return;const t=ji(ue);try{const{error:s}=await d.rpc("soft_delete_business_entity",{p_kind:"proposal",p_id:ue,p_cascade_contract:!!t&&t.status!=="signed"});if(s)throw s;D({title:R("proposals.toast.deleteSuccess"),description:R("proposals.toast.movedToTrashDesc")}),ke()}catch(s){const a=String((s==null?void 0:s.message)||"");D({title:R("proposals.toast.deleteError"),description:a.includes("proposal_has_signed_contract")?"Esta proposta tem um contrato assinad
4o associado e não pode ser eliminada.":a,variant:"destructive"})}finally{L(!1),P(null),Z(null)}},Rr=t=>{sa(t),$a(t.template_id||"none"),hs(!0)},zr=async()=>{if(ta){Oa(!0);try{const t=aa==="none"?null:aa,{error:s}=await d.from("proposals").update({template_id:t,has_unpublished_changes:ta.has_unpublished_changes??!1}).eq("id",ta.id);if(s)throw s;D({title:"Layout actualizado",description:"O PDF e o portal passam a usar o novo template."}),hs(!1),sa(null),ke()}catch(t){D({title:"Erro ao alterar layout",description:(t==null?void 0:t.message)||"Tenta novamente.",variant:"destructive"})}finally{Oa(!1)}}},$r=t=>{if(t.status==="accepted"&&t.has_unpublished_changes){da(t),oa(!0);return}ca("proposal",t.id)},Or=()=>{Et&&(ca("proposal",Et.id),oa(!1),da(null))},Lr=t=>{Dt(t?Gt.map(s=>s.id):[])},Vr=(t,s)=>{Dt(s?a=>[...a,t]:a=>a.filter(r=>r!==t))},Fr=async()=>{var t;try{const a=(t=(await Promise.all(Xe.map(r=>d.rpc("soft_delete_business_entity",{p_kind:"proposal",p_id:r})))).find(r=>r.error))==null?void 0:t.error;if(a)throw a;D({title:R("common.deleteSuccess"),description:`${Xe.length} propostas movidas para o lixo.`}),Dt([]),Ka(!1),ke()}catch(s){D({title:R("proposals.toast.deleteError"),description:s.message,variant:"destructive"})}},Qr=async()=>{if(as)try{const t=x.find(a=>a.id===as),{error:s}=await d.from("proposals").update({stage_id:as,status:(t==null?void 0:t.name)||"draft"}).in("id",Xe);if(s)throw s;D({title:R("common.statusUpdated"),description:`${Xe.length} propostas atualizadas.`}),Dt([]),Ns(!1),Xa(""),ke()}catch(t){D({title:R("common.error"),description:t.message,variant:"destructive"})}},Br=async t=>{try{const{data:s,error:a}=await d.rpc("duplicate_proposal",{source_proposal_id:t,new_title:null});if(a)throw a;D({title:R("proposals.toast.duplicateSuccess"),description:R("proposals.toast.duplicateSuccessDesc")}),ke()}catch(s){D({title:R("proposals.toast.duplicateError"),description:s.message,variant:"destructive"})}},vi=async t=>{if(window.confirm(`Reverter a proposta "${t.title}" para rascunho?
5
6O acesso ao portal será revogado até voltares a publicar.`))try{const{error:a}=await d.rpc("revert_proposal_to_draft",{p_proposal_id:t.id});if(a)throw a;D({title:"Proposta revertida",description:"A proposta voltou a rascunho. Podes agora editá-la livremente."}),ke()}catch(a){const r=/proposal_accepted_immutable/i.test((a==null?void 0:a.message)||"")?"Propostas aceites não podem ser revertidas.":/proposal_not_found/i.test((a==null?void 0:a.message)||"")?"Proposta não encontrada.":a.message;D({title:"Erro ao reverter",description:r,variant:"destructive"})}},Hr=async()=>{if(!(ee||Ut.current)){if(m){y(!1),M(`/quotes?new=1&proposal_id=${m}${I.deal_id?`&deal_id=${I.deal_id}`:""}`);return}if(!I.title.trim()){D({title:"Título obrigatório",description:"Indica um título para a proposta antes de criar o orçamento.",variant:"destructive"});return}if(!(i!=null&&i.id)){D({title:"Empresa ativa não definida",variant:"destructive"});return}try{Ut.current=!0,ae(!0);const{data:{user:t}}=await d.auth.getUser();if(!t)throw new Error("User not authenticated");const s=await Ti();if(!s){D({title:"Erro de identidade",description:"Não foi possível identificar o utilizador.",variant:"destructive"});return}const a=x.find(he=>he.id===I.stage_id),r=es.find(he=>he.is_default),l=I.template_id||(r==null?void 0:r.id)||null,p=(U==null?void 0:U.probability)??50,w=I.deal_id?(U==null?void 0:U.entity_id)||null:(xe==null?void 0:xe.entityId)||null,A={title:I.title,de
6scription:I.description||null,value:0,probability:p,deal_id:I.deal_id||null,entity_id:w,valid_until:I.valid_until||null,notes:I.notes||null,stage_id:I.stage_id||null,status:(a==null?void 0:a.name)||"draft",organization_id:i.id,root_organization_id:i.parent_id||i.id,template_id:l,assigned_to:I.assigned_to||null},{data:N,error:V}=await d.from("proposals").insert({...A,created_by:s}).select("id").single();if(V)throw V;y(!1),ga(),ke(),M(`/quotes?new=1&proposal_id=${N.id}${I.deal_id?`&deal_id=${I.deal_id}`:""}`)}catch(t){D({title:R("proposals.toast.createError"),description:t.message,variant:"destructive"})}finally{Ut.current=!1,ae(!1)}}},Ur=async t=>{if(t.preventDefault(),Ut.current||ee)return;const s=Qe.map(N=>({title:N.title,totalLines:(N.lines||[]).length,invalidLines:(N.lines||[]).filter(V=>!V.qt||V.qt<=0).length})).filter(N=>N.totalLines>0&&N.invalidLines===N.totalLines);if(s.length>0){console.warn("[Proposals.submit] blocked — inline quotes with no valid lines",s),D({title:"Orçamento sem linhas válidas",description:`O orçamento "${s[0].title}" não tem nenhuma linha com quantidade > 0. Corrija ou remova antes de gravar.`,variant:"destructive"});return}const a=Le.reduce((N,V)=>N+(V.total||0),0),r=Qe.reduce((N,V)=>N+As(V),0),l=cl(js),p=a+r+l,w=Le.length>0||Qe.length>0||js.length>
60?p:parseFloat(I.value)||0,A=sl.safeParse({title:I.title,description:I.description,value:w,notes:I.notes,valid_until:I.valid_until});if(!A.success){const N={};A.error.errors.forEach(V=>{V.path[0]&&(N[V.path[0].toString()]=V.message)}),na(N),D({title:R("proposals.toast.validationError"),description:A.error.errors[0].message,variant:"destructive"});return}na({});try{Ut.current=!0,ae(!0);const{data:{user:N}}=await d.auth.getUser();if(!N)throw new Error("User not authenticated");if(!(i!=null&&i.id))throw new Error("Empresa ativa não definida");const V=x.find(oe=>oe.id===I.stage_id),he=(U==null?void 0:U.probability)??50,le=es.find(oe=>oe.is_default),ve=I.template_id||(le==null?void 0:le.id)||null,De={title:I.title,description:I.description||null,value:w,probability:he,deal_id:I.deal_id||null,entity_id:I.deal_id?null:(xe==null?void 0:xe.entityId)||null,valid_until:I.valid_until||null,notes:I.notes||null,stage_id:I.stage_id||null,status:(V==null?void 0:V.name)||"draft",organization_id:i.id,root_organization_id:i.parent_id||i.id,template_id:ve,assigned_to:I.assigned_to||null};let J=null;const f=await Ti();if(!f){D({title:"Erro de identidade",description:"Não foi possível identificar o utilizador. Faça login novamente.",variant:"destructive"});return}if(m){const{error:oe}=await d.from("proposals").update(De).eq("id",m);if(oe)throw oe;if(J=m,I.stage_id&&ra&&I.stage_id!==ra)try{await d.functions.invoke("execute-workflow",{body:{source_entity:"proposal",entity_id:m,new_stage_id:I.stage_id,old_stage_id:ra,organization_id:i==null?void 0:i.id,triggered_by:N.id}})}catch(K){console.error("Workflow execution error:",K)}D({title:R("proposals.toast.updateSuccess")})}else{const{data:oe,error:K}=await d.from("proposals").insert({...De,created_by:f}).select("id").single();if(K)throw K;J=oe.id,D({title:R("proposals.toast.createSuccess")})}if(J){const oe=(U==null?void 0:U.entity_id)||(xe==null?void 0:xe.entityId)||De.entity_id||null;await Zn(oe,i.id);const K=Le.map(B=>B.id);if(K.length>0){const{error:B}=await d.from("quotes").update({proposal_id:null}).eq("proposal_id",J).not("id","in",`(${K.join(",")})`);B&&console.error("Error unlinking quotes:",B);const{error:S}=await d.from("quotes").update({proposal_id:J}).in("id",K);S&&console.error("Error linking quotes:",S)}else await d.from("quotes").update({proposal_id:null}).eq("proposal_id",J);console.log("[Proposals.submit] inlineQuotes snapshot",{proposalId:J,count:Qe.length,quotes:Qe.map(B=>{var S;return{title:B.title,totalLines:((S=B.lines)==null?void 0:S.length)??0,validLines:(B.lines||[]).filter(Ve=>Ve.qt>0).length,linesPreview:(B.lines||[]).map(Ve=>{var C;return{qt:Ve.qt,desc:(C=Ve.descricao_snapshot)==null?void 0:C.slice(0,40)}})}})});const ut=[];for(const B of Qe){const S=(B.lines||[]).filter(E=>E.qt>0);if(S.length===0){const E=(B.lines||[]).length===0?"sem linhas":"todas as linhas com quantidade 0";console.warn("[Proposals.submit] skipping inline quote",{title:B.title,reason:E,totalLines:(B.lines||[]).length}),ut.push({title:B.title||"(sem título)",reason:E});continue}const Ve=U?U.organization_id:i==null?void 0:i.id,C=(U==null?void 0:U.entity_id)||(xe==null?void 0:xe.entityId)||null,X={deal_id:I.deal_id||null,entity_id:C,organization_id:Ve||(i==null?void 0:i.id)||null,root_organization_id:(i==null?void 0:i.parent_id)||(i==null?void 0:i.id)||null,title:B.title||null,obra_notas:B.obra_notas||null,modelo_base:B.modelo_base&&B.modelo_base!=="0"?B.modelo_base:"default",desconto_global_percent:B.desconto_global_percent,estado:"finalizado",validade_dias:B.validade_dias,iva_rate:B.iva_rate,client_notes:B.client_notes||null,conditions:B.conditions||null,proposal_id:J,created_by:f},fe=S.map(E=>{const Kt=E.custo_material_unit+E.custo_mao_obra_unit,mn=Kt===0&&E.retail_price_unit!==void 0&&E.retail_price_unit!==null,un=Ri(mn?E.retail_price_unit||0:Kt*(1+E.margem_percent/100)*(1+E.int_percent/100)),xn=Ri(un*E.qt),qi=E.discount_percent||0,ja=xn*(1-qi/100),hn=ja*(E.iva_percent/100),Ii=ja+hn,pn=Ii*(1-B.desconto_global_percent/100);return{quote_id:"",catalog_item_id:E.catalog_item_id||null,product_id:E.product_id||null,service_id:E.service_id||null,selected_attributes:E.selected_attributes||{},categoria:"",descricao_snapshot:E.descricao_snapshot,qt:E.qt,custo_material_unit:E.custo_material_unit,custo_mao_obra_unit:E.custo_mao_obra_unit,margem_percent:E.margem_percent,iva_percent:E.iva_percent,int_percent:E.int_percent,discount_percent:qi,total_sem_iva:ja,total_com_iva:Ii,total_com_desconto:pn,ordem:E.ordem,section_name:E.section_name||"Geral",unidade:E.unidade||null,item_description:E.item_description||null,cost_price:E.cost_price||0}}),be=[...new Set(fe.map(E=>
6E.product_id).filter(Boolean))],We=[...new Set(fe.map(E=>E.service_id).filter(Boolean))],Ze=[...new Set(fe.map(E=>E.catalog_item_id).filter(Boolean))],[Ne,He,Ge]=await Promise.all([be.length>0?d.from("products").select("id").in("id",be):Promise.resolve({data:[]}),We.length>0?d.from("services").select("id").in("id",We):Promise.resolve({data:[]}),Ze.length>0?d.from("catalog_items").select("id").in("id",Ze):Promise.resolve({data:[]})]),_t=new Set((Ne.data||[]).map(E=>E.id)),rn=new Set((He.data||[]).map(E=>E.id)),nn=new Set((Ge.data||[]).map(E=>E.id)),_a=fe.map(E=>({...E,product_id:E.product_id&&_t.has(E.product_id)?E.product_id:null,service_id:E.service_id&&rn.has(E.service_id)?E.service_id:null,catalog_item_id:E.catalog_item_id&&nn.has(E.catalog_item_id)?E.catalog_item_id:null})),ln=_a.reduce((E,Kt)=>E+Kt.total_sem_iva,0),on=_a.reduce((E,Kt)=>E+Kt.total_com_desconto,0),{data:dn,error:Ci}=await d.from("quotes").insert({...X,subtotal:ln,total:on}).select("id").single();if(Ci)throw Ci;const cn=_a.map(E=>({...E,quote_id:dn.id})),{error:Pi}=await d.from("quote_lines").insert(cn);if(Pi)throw Pi}await d.from("proposal_items").delete().eq("proposal_id",J),js.length>0&&await d.from("proposal_items").insert(js.map((B,S)=>({proposal_id:J,description:B.description,quantity:B.quantity,unit_price:B.unit_price,vat_rate:B.vat_rate,sort_order:S})))}const k=typeof skippedQuotes<"u"?skippedQuotes:[];if(k.length>0){const oe=k.map(K=>`• "${K.title}" — ${K.reason}`).join(`
7`);console.warn("[Proposals.submit] some inline quotes were not persisted",k),D({title:`${k.length} orçamento(s) não gravado(s)`,description:`A proposta foi gravada mas o(s) seguinte(s) orçamento(s) foi(ram) ignorado(s):
8${oe}
9
10Corrija e grave novamente.`,variant:"destructive"}),ke();return}y(!1),ga(),ke()}catch(N){D({title:R(m?"proposals.toast.updateError":"proposals.toast.createError"),description:N.message,variant:"destructive"})}finally{Ut.current=!1,ae(!1)}},ga=()=>{var t;T(null),La(null),Oe({title:"",description:"",value:"",deal_id:"",valid_until:"",notes:"",stage_id:((t=x[0])==null?void 0:t.id)||"",template_id:"",assigned_to:""}),ts(null),Bt(null),fs(""),Qt([]),dt([]),gs(""),_s([]),vs([]),ss([]),na({})},Gr=async()=>{if(!(!si||!ks))try{const{error:t}=await d.from("proposals").update({valid_until:ks}).eq("id",si);if(t)throw t;D({title:"Validade renovada com sucesso"}),ys(!1),ai(null),xa(""),ke()}catch(t){D({title:"Erro ao renovar validade",description:t.message,variant:"destructive"})}},bi=t=>{const s=new Date;s.setDate(s.getDate()+30),ai(t),xa(Re(s,"yyyy-MM-dd")),ys(!0)},Ni=async()=>{if(h)try{const{data:{user:t}}=await d.auth.getUser();if(!t)throw new Error("Not authenticated");const s=x.find(r=>r.name==="accepted"||r.name==="aceite");if(!s){D({title:"Erro",description:"Estágio 'Aceite' não encontrado",variant:"destructive"});return}const a=h.stage_id;await d.from("proposals").update({stage_id:s.id,status:"accepted",accepted_at:new Date().toISOString()}).eq("id",h.id),await d.functions.invoke("execute-workflow",{body:{source_entity:"proposal",entity_id:h.id,new_stage_id:s.id,old_stage_id:a,organization_id:i==null?void 0:i.id,triggered_by:t.id}}),D({title:"Proposta aceite com sucesso"}),v(!1),ke()}catch(t){D({title:"Erro",description:t.message,variant:"destructive"})}},wi=async t=>{if(h)try{const s=pa[h.id]||[];if(s.length>1&&s.some(A=>!["rejeitado","rejected"].includes(String(A.estado||"").toLowerCase()))){D({title:"Proposta com opções ativas",description:"Só podes rejeitar a proposta toda quando todos os orçamentos associados estiverem rejeitados.",variant:"destructive"});return}const{data:{user:r}}=await d.auth.getUser();if(!r)throw new Error("Not authenticated");const l=x.find(A=>A.name==="rejected"||A.name==="rejeitada");if(!l){D({title:"Erro",description:"Estágio 'Rejeitada' não encontrado",variant:"destructive"});return}const p=h.stage_id,w={stage_id:l.id,status:"rejected",rejected_at:new Date().toISOString()};t&&t.trim()&&(w.rejection_reason=t.trim()),await d.from("proposals").update(w).eq("id",h.id),await d.functions.invoke("execute-workflow",{body:{source_entity:"proposal",entity_id:h.id,new_stage_id:l.id,old_stage_id:p,organization_id:i==null?void 0:i.id,triggered_by:r.id}}),D({title:"Proposta recusada"}),v(!1),ke()}catch(s){D({title:"Erro",description:s.message,variant:"destructive"})}},Wr=async t=>{try{const{data:{user:s}}=await d.auth.getUser();if(!s)throw new Error("Not authenticated");const a=x.find(p=>p.name==="sent"||p.name==="enviada");if(!a){D({title:"Erro",description:"Estágio 'Enviada' não encontrado",variant:"destructive"});return}const r=t.stage_id,{error:l}=await d.from("proposals").update({stage_id:a.id,status:"sent",rejected_at:null,rejection_reason:null,rejection_reason_code:null,rejection_notes:null}).eq("id",t.id);if(l)throw l;await d.functions.invoke("execute-workflow",{body:{source_entity:"proposal",entity_id:t.id,new_stage_id:a.id,old_stage_id:r,organization_id:i==null?void 0:i.id,triggered_by:s.id}}),D({title:"Proposta marcada como enviada"}),ke()}catch(s){D({title:"Erro",description:s.message,variant:"destructive"})}},Cs=n.useCallback(async t=>{let s=t.entity_id||null;if(!s&&t.deal_id){const{data:r}=await d.from("deals").select("entity_id").eq("id",t.deal_id).maybeSingle();s=(r==null?void 0:r.entity_id)||null}if(!s)return null;const a=Mt[s]||Mt[`deal:${t.id}`]||"Cliente";return{entityId:s,entityName:a}},[Mt]),Ps=n.useCallback(async t=>{const s=await Cs(t);if(!s){D({title:"Sem cliente associado",description:"Esta proposta não tem um cliente/entidade para registar contacto.",variant:"destructive"});return}Nr({...s,proposal:t}),ii(!0)},[Cs,D]),Jr=n.useCallback(async t=>{const s=await Cs(t);if(!s){D({title:"Sem cliente associado",variant:"destructive"});return}const a=Ht[s.entityId]||Ht[`deal:${t.id}`];if(!a){D({title:"Sem telefone",description:"O cliente não tem telefone registado.",variant:"destructive"});return}ri({module:"proposals",recipientName:s.entityName,recipientPhone:a,entityId:s.entity
10Id,hasActiveDeal:!!t.deal_id,proposalTitle:t.title,proposalValue:Number(t.value)||0}),ha(!0)},[Cs,Ht,D]),Kr=n.useCallback(t=>{Sr(t),oi(""),Ss(!0)},[]),yi=n.useMemo(()=>{const t=new Map;return x.forEach(s=>t.set(s.name,s)),t},[x]),pe=n.useCallback(t=>t.proposal_workflow_stages?t.proposal_workflow_stages:yi.get(t.status)||null,[yi]),Xr=t=>{const s=pe(t);return s?e.jsx(de,{style:{backgroundColor:s.color+"20",color:s.color,borderColor:s.color},children:s.label}):e.jsx(de,{variant:"outline",children:t.status})},yt=t=>{const s=pe(t);return(s==null?void 0:s.name)||t.status||""},gt=n.useCallback(t=>{const s=Number(t.value)||0,a=pa[t.id];if(a&&a.length>0){const w=a.reduce((N,V)=>N+(Number(V.subtotal)||0),0),A=a.reduce((N,V)=>N+(Number(V.total)||0),0);if(A>0||w>0)return{subtotal:w>0?w:A>0?A:s,total:A>0?A:w>0?w:s}}const r=t.proposal_items||[],l=r.reduce((w,A)=>w+(Number(A.subtotal)||0),0),p=r.reduce((w,A)=>w+(Number(A.total)||0),0);return p>0||l>0?{subtotal:l>0?l:p,total:p>0?p:l}:{subtotal:s,total:s}},[pa]),Be=n.useMemo(()=>c.filter(t=>{if(lt||ot){const a=lt?gl(lt):null,r=ot?$n(ot):null,l=N=>{if(!N)return!1;const V=new Date(N);return!(a&&V<a||r&&V>r)},p=l(t.created_at),A=(di[t.id]||[]).some(l);if(!p&&!A)return!1}const s=t.assigned_to;return!(Ct==="none"&&s||Ct!=="all"&&Ct!=="none"&&s!==Ct||Yt&&je&&s!==je)}),[c,lt,ot,Ct,Yt,je,di]),Ie=n.useMemo(()=>{const t=new Date,s=Be.length,a=Be.reduce((f,k)=>f+gt(k).subtotal,0),r={},l={};x.forEach(f=>{r[f.id]=0,l[f.id]=0}),Be.forEach(f=>{const k=pe(f);k&&(r[k.id]=(r[k.id]||0)+1,l[k.id]=(l[k.id]||0)+gt(f).subtotal)});const p=Be.filter(f=>{const k=pe(f);return k==null?void 0:k.is_won}).reduce((f,k)=>f+gt(k).subtotal,0);Be.filter(f=>{const k=yt(f);return k==="sent"||k==="enviada"});const w=Be.filter(f=>{const k=pe(f);return k==null?void 0:k.is_won}),A=Be.filter(f=>{const k=pe(f);return k&&k.stage_order>1}).length,N=A>0?Math.round(w.length/A*100):0,V=w.map(f=>{const k=f.accepted_at;return k?it(Ee(k),Ee(f.created_at)):it(t,Ee(f.created_at))}).filter(f=>f>=0),he=V.length>0?Math.round(V.reduce((f,k)=>f+k,0)/V.length):0,le=Be.filter(f=>{const k=yt(f);return(k==="sent"||k==="enviada")&&it(t,Ee(f.created_at))>5}),ve=le.reduce((f,k)=>f+gt(k).subtotal,0),De=Be.filter(f=>{const k=pe(f);return!f.valid_until&&!(k!=null&&k.is_lost)}),J=Be.filter(f=>{const k=pe(f);return f.valid_until&&Lt(Ee(f.valid_until))&&!(k!=null&&k.is_won)&&!(k!=null&&k.is_lost)});return{total:s,totalValue:a,stageCounts:r,stageValues:l,wonValue:p,conversionRate:N,avgCloseTime:he,noResponse5d:le,noResponse5dValue:ve,noValidity:De,expired:J}},[Be,x,pe,gt]),Gt=n.useMemo(()=>{const t=new Date;return Be.filter(s=>{var p,w,A;if(ft!=="all"){const N=pe(s);if((N==null?void 0:N.id)!==ft&&s.status!==ft)return!1}if(Pt){const N=yt(s);if(!((N==="sent"||N==="enviada")&&it(t,Ee(s.created_at))>5))return!1}if(qt&&!(s.valid_until&&Lt(Ee(s.valid_until)))||xs&&s.valid_until)return!1;const a=ct.trim(),r=a.toLowerCase();let l=!0;if(a.length>=3){const N=((p=s.title)==null?void 0:p.toLowerCase().includes(r))||((A=(w=s.deals)==null?void 0:w.title)==null?void 0:A.toLowerCase().includes(r)),V=Js?s.entity_id&&Js.has(s.entity_id):!1;l=!!(N||V)}return l}).sort((s,a)=>{var p,w;let r,l;switch(ms){case"created_at":r=new Date(s.created_at).getTime(),l=new Date(a.created_at).getTime();break;case"proposal_number":r=s.proposal_number||"",l=a.proposal_number||"";break;case"title":r=s.title,l=a.title;break;case"value":r=gt(s).subtotal,l=gt(a).subtotal;break;case"status":r=((p=pe(s))==null?void 0:p.stage_order)||0,l=((w=pe(a))==null?void 0:w.stage_order)||0;break;case"valid_until":r=s.valid_until?new Date(s.valid_until).getTime():0,l=a.valid_until?new Date(a.valid_until).getTime():0;break;default:r=s.created_at,l=a.created_at}return typeof r=="string"&&typeof l=="string"?us==="asc"?r.localeCompare(l):l.localeCompare(r):us==="asc"?r-l:l-r})},[Be,ft,ct,Js,ms,us,Pt,qt,xs,pe,gt]),Wt=t=>{ms===t?Aa(s=>s==="asc"?"desc":"asc"):(tr(t),Aa("asc"))},Jt=({column:t})=>ms!==t?e.jsx(Ll,{className:"w-3 h-3 ml-1 opacity-50"}):us==="asc"?e.jsx(Vl,{className:"w-3 h-3 ml-1"}):e.jsx(Fl,{className:"w-3 h-3 ml-1"}),Zr=()=>{Te(""),Zt("all"),Ks(void 0),Xs(void 0),Ta(!1),Ys(!1),ea(!1),za(!1),Ra("all")},Yr=W||ft!=="all"||lt||ot||Yt||Pt||qt||xs||Ct!=="all",en=t=>{const s=new Date,a=yt(t),r=pe(t),l=it(s,Ee(t.created_at));if(r!=null&&r.is_won){const p=rs[t.id];return p!=null&&p.contract_id?{text:"✅ Aceite — contrato criado automaticamente",color:"text-green-600"}:{text:"✅ Aceite",color:"text-green-600"}}return r!=null&&r.is_lost?{text:"❌ Rejeitada",color:"text-red-500"}:(a==="sent"||a==="enviada")&&l>5?{text:`⏰ Enviada há ${l} dias sem resposta — follow-up urgente`,color:"text-orange-600"}:(a==="draft"||a==="rascunho")&&l>2?{text:`📝 Rascunho há ${l} dias — enviar?`,color:"text-muted-foreground"}:!t.valid_until&&!(r!=null&&r.is_lost)?{text:"⚠ Sem validade definida",color:"text-amber-600"}
10:t.valid_until&&Lt(Ee(t.valid_until))&&!(r!=null&&r.is_won)&&!(r!=null&&r.is_lost)?{text:"🔴 Expirada",color:"text-red-500"}:null},tn=t=>{const s=new Date,a=pe(t),r=yt(t);return a!=null&&a.is_won?"bg-green-50/50 dark:bg-green-950/20":a!=null&&a.is_lost?"bg-red-50/30 dark:bg-red-950/10 opacity-75":(r==="sent"||r==="enviada")&&it(s,Ee(t.created_at))>5?"bg-amber-50/50 dark:bg-amber-950/20":r==="draft"||r==="rascunho"?"bg-muted/30":""},sn=t=>{const s=yt(t),a=pe(t),l=it(new Date,Ee(t.created_at)),p=(s==="sent"||s==="enviada")&&l>5,A=!(a!=null&&a.is_won)&&!(a!=null&&a.is_lost)?e.jsx(g,{size:"icon",variant:"ghost",className:we("h-7 w-7",t.has_unpublished_changes&&"text-amber-600"),onClick:()=>gi(t),title:t.has_unpublished_changes?"Editar (tens alterações por publicar)":"Editar",children:e.jsx(ba,{className:"w-3.5 h-3.5"})}):null;return s==="draft"||s==="rascunho"?e.jsxs(e.Fragment,{children:[A,e.jsx(g,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>{ws(t),is(!0)},title:"Enviar email",children:e.jsx(ht,{className:"w-3.5 h-3.5"})}),e.jsx(g,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>mt(t),title:"Ver",children:e.jsx(rt,{className:"w-3.5 h-3.5"})})]}):s==="sent"||s==="enviada"?e.jsxs(e.Fragment,{children:[e.jsx(g,{size:"icon",variant:p?"default":"ghost",className:we("h-7 w-7",p&&"animate-pulse"),title:"Follow-up",onClick:()=>Ps(t),children:e.jsx(Xt,{className:"w-3.5 h-3.5"})}),A,e.jsx(g,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>{ws(t),is(!0)},title:"Reenviar",children:e.jsx(ht,{className:"w-3.5 h-3.5"})}),e.jsx(g,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>mt(t),title:"Ver",children:e.jsx(rt,{className:"w-3.5 h-3.5"})})]}):a!=null&&a.is_won?e.jsxs(e.Fragment,{children:[e.jsx(g,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>mt(t),title:"Ver",children:e.jsx(rt,{className:"w-3.5 h-3.5"})}),e.jsx(g,{size:"icon",variant:"ghost",className:"h-7 w-7",title:"Contrato",children:e.jsx(xt,{className:"w-3.5 h-3.5"})}),e.jsx(g,{size:"icon",variant:"ghost",className:"h-7 w-7",title:"Duplicar",children:e.jsx(Ca,{className:"w-3.5 h-3.5"})})]}):a!=null&&a.is_lost?e.jsxs(e.Fragment,{children:[e.jsx(g,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>mt(t),title:"Ver",children:e.jsx(rt,{className:"w-3.5 h-3.5"})}),e.jsx(g,{size:"icon",variant:"ghost",className:"h-7 w-7",title:"Reabrir",onClick:()=>vi(t),children:e.jsx(Na,{className:"w-3.5 h-3.5"})}),e.jsx(g,{size:"icon",variant:"ghost",className:"h-7 w-7",title:"Follow-up",onClick:()=>Ps(t),children:e.jsx(Xt,{className:"w-3.5 h-3.5"})})]}):e.jsxs(e.Fragment,{children:[A,e.jsx(g,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>mt(t),title:"Ver",children:e.jsx(rt,{className:"w-3.5 h-3.5"})}),e.jsx(g,{size:"icon",variant:"ghost",className:"h-7 w-7",title:"Ligar",onClick:()=>Ps(t),children:e.jsx(Xt,{className:"w-3.5 h-3.5"})})]})},an=t=>{const s=yt(t),a=pe(t),r=rs[t.id];return e.jsxs(Yn,{align:"end",sideOffset:4,collisionPadding:16,className:"w-56 max-h-[var(--radix-dropdown-menu-content-available-height)] overflow-y-auto",children:[e.jsx(At,{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"📨 Comunicação"}),e.jsxs(ge,{onClick:()=>{ws(t),is(!0)},children:[e.jsx(ht,{className:"w-3.5 h-3.5 mr-2"})," ",s==="sent"||s==="enviada"?"Reenviar email":"Enviar por email"]}),e.jsxs(ge,{onClick:()=>Jr(t),children:[e.jsx(Qi,{className:"w-3.5 h-3.5 mr-2"})," WhatsApp"]}),e.jsxs(ge,{onClick:async()=>{try{D({title:"A gerar PDF…",description:"Pode demorar alguns segundos."});const{blob:l,fileName:p}=await Ki(t.id);Sa(l,p)}catch(l){D({title:"Erro ao gerar PDF",description:(l==null?void 0:l.message)||"Tenta novamente.",variant:"destructive"})}},children:[e.jsx(Ql,{className:"w-3.5 h-3.5 mr-2"})," Descarregar PDF"]}),e.jsxs(ge,{onClick:()=>Ps(t),children:[e.jsx(Xt,{className:"w-3.5 h-3.5 mr-2"})," Registar atividade"]}),e.jsx(Tt,{}),e.jsx(At,{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"📊 Avançar"}),(s==="draft"||s==="rascunho")&&e.jsxs(ge,{onClick:()=>Wr(t),children:[e.jsx(cs,{className:"w-3.5 h-3.5 mr-2"})," Marcar como Enviada"]}
10),!(a!=null&&a.is_won)&&!(a!=null&&a.is_lost)&&e.jsxs(ge,{className:"text-green-600",onClick:()=>{$(t),Ni()},children:[e.jsx(Bl,{className:"w-3.5 h-3.5 mr-2"})," Aceitar",e.jsx("span",{className:"text-[10px] text-muted-foreground ml-1",children:"⚡ cria contrato"})]}),!(a!=null&&a.is_won)&&!(a!=null&&a.is_lost)&&e.jsxs(ge,{className:"text-red-500",onClick:()=>Kr(t),children:[e.jsx(ns,{className:"w-3.5 h-3.5 mr-2"})," Rejeitar (com motivo)"]}),e.jsx(Tt,{}),e.jsx(At,{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"📅 Validade"}),e.jsxs(ge,{onClick:()=>bi(t.id),children:[e.jsx(Ei,{className:"w-3.5 h-3.5 mr-2"})," ",t.valid_until?"Renovar validade":"Definir validade"]}),e.jsx(Tt,{}),e.jsxs(At,{className:"text-[10px] text-muted-foreground uppercase tracking-wider flex items-center justify-between",children:[e.jsx("span",{children:"🔗 Portal"}),t.has_unpublished_changes&&e.jsx("span",{className:"text-[10px] text-amber-600 font-semibold normal-case tracking-normal",children:"● Alterações por publicar"})]}),e.jsxs(ge,{disabled:Za,onClick:l=>{l.preventDefault(),$r(t)},children:[e.jsx(cs,{className:"w-3.5 h-3.5 mr-2 text-purple-600"}),t.published_at?"Republicar no portal":"Enviar para Portal Cliente"]}),e.jsxs(ge,{onClick:async l=>{l.preventDefault();const p=`${window.location.origin}/auth`;await navigator.clipboard.writeText(p),D({title:"Link copiado!",description:"Link do portal copiado para a área de transferência."})},children:[e.jsx(Li,{className:"w-3.5 h-3.5 mr-2"})," Copiar link do portal"]}),e.jsxs(ge,{disabled:Za,onClick:l=>{l.preventDefault(),ca("proposal",t.id,!0)},children:[e.jsx(Hl,{className:"w-3.5 h-3.5 mr-2"})," Reenviar credenciais"]}),e.jsx(Tt,{}),e.jsx(At,{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"🔗 Relacionados"}),e.jsxs(ge,{disabled:!t.deal_id,onClick:()=>t.deal_id&&M(`/deals?open=${t.deal_id}`),children:[e.jsx(xt,{className:"w-3.5 h-3.5 mr-2"})," Ver pedido ",!t.deal_id&&e.jsx("span",{className:"text-[10px] text-muted-foreground ml-1",children:"(não existe)"})]}),e.jsxs(ge,{disabled:!(r!=null&&r.contract_id),onClick:()=>(r==null?void 0:r.contract_id)&&M(`/contracts?open=${r.contract_id}`),children:[e.jsx(xt,{className:"w-3.5 h-3.5 mr-2"})," Ver contrato ",!(r!=null&&r.contract_id)&&e.jsx("span",{className:"text-[10px] text-muted-foreground ml-1",children:"(não criado)"})]}),e.jsx(Tt,{}),e.jsx(At,{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"📋 Acções"}),!(a!=null&&a.is_won)&&!(a!=null&&a.is_lost)&&e.jsx(jt,{permission:"proposals.edit",children:e.jsxs(ge,{onClick:()=>gi(t),children:[e.jsx(ba,{className:"w-3.5 h-3.5 mr-2"})," Editar proposta"]})}),!(a!=null&&a.is_won)&&!(a!=null&&a.is_lost)&&s!=="draft"&&s!=="rascunho"&&e.jsx(jt,{permission:"proposals.edit",children:e.jsxs(ge,{onClick:()=>vi(t),children:[e.jsx(Na,{className:"w-3.5 h-3.5 mr-2 text-amber-600"})," Reverter para rascunho"]})}),e.jsx(jt,{permission:"proposals.edit",children:e.jsxs(ge,{onClick:()=>Rr(t),children:[e.jsx($i,{className:"w-3.5 h-3.5 mr-2 text-purple-600"})," Alterar layout do documento"]})}),e.jsxs(ge,{onClick:()=>{Ga(t.id),ua(!0)},children:[e.jsx(rt,{className:"w-3.5 h-3.5 mr-2"})," Preview Portal"]}),e.jsxs(ge,{onClick:()=>Br(t.id),children:[e.jsx(Ca,{className:"w-3.5 h-3.5 mr-2"})," Duplicar"]}),e.jsxs(ge,{onClick:()=>{Ya(t.id),ei(t.title),ma(!0)},children:[e.jsx(Bi,{className:"w-3.5 h-3.5 mr-2"})," Histórico"]}),(a==null?void 0:a.is_lost)&&e.jsxs(e.Fragment,{children:[e.jsx(Tt,{}),e.jsx(At,{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"🔄 Recuperação"}),e.jsxs(ge,{children:[e.jsx(Na,{className:"w-3.5 h-3.5 mr-2"})," Reabrir com desconto (v2)"]}),e.jsxs(ge,{children:[e.jsx(Xt,{className:"w-3.5 h-3.5 mr-2"})," Contactar cliente"]})]}),e.jsx(Tt,{}),e.jsx(jt,{permission:"proposals.delete",children:(()=>{const l=r!=null&&r.contract_id?Y[r.contract_id]:null,p=(l==null?void 0:l.status)==="signed";return e.jsxs(ge,{className:"text-destructive focus:text-destructive",title:p?"A proposta vai para o Lixo;
10 o contrato assinado é preservado.":void 0,onClick:()=>Ar(t),children:[e.jsx(el,{className:"w-3.5 h-3.5 mr-2"})," Eliminar",p&&e.jsx("span",{className:"text-[10px] text-muted-foreground ml-1",children:"(contrato preservado)"})]})})()})]})};return z?e.jsx(Ms,{children:e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold",children:R("proposals.title")}),e.jsx("p",{className:"text-muted-foreground",children:R("proposals.subtitle")})]})}),e.jsx("div",{className:"flex gap-3 overflow-x-auto pb-2",children:Array.from({length:5}).map((t,s)=>e.jsx(_e,{className:"animate-pulse min-w-[130px]",children:e.jsxs(Se,{className:"p-3",children:[e.jsx("div",{className:"h-8 bg-muted rounded w-1/2 mb-2"}),e.jsx("div",{className:"h-4 bg-muted rounded w-3/4"})]})},s))})]})}):ne?e.jsx(Ms,{children:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx(Fi,{size:40})})}):i?e.jsxs(Ms,{children:[e.jsxs("div",{className:"flex flex-col h-[calc(100vh-4rem)] overflow-hidden",children:[e.jsxs("div",{className:"flex-shrink-0 px-4 md:px-6 pt-2 pb-1",children:[e.jsx(Pl,{alerts:pt,maxVisible:1,onDismiss:ye,onAction:t=>{var a,r;const s=(a=t.action_config)==null?void 0:a.entity_ids;_i(((r=t.action_config)==null?void 0:r.proposal_id)||t.entity_id||((s==null?void 0:s.length)===1?s[0]:null))},onAlertClick:t=>{var a,r;const s=(a=t.action_config)==null?void 0:a.entity_ids;_i(((r=t.action_config)==null?void 0:r.proposal_id)||t.entity_id||((s==null?void 0:s.length)===1?s[0]:null))}}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-2 mt-1",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl sm:text-2xl font-bold leading-tight",title:"Gestão de propostas comerciais — do envio à aceitação",children:R("proposals.title")}),e.jsx("p",{className:"hidden lg:block text-sm text-muted-foreground",children:"Gestão de propostas comerciais — do envio à aceitação"})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(tl,{pageKey:"acquisition.proposals"}),e.jsx(g,{variant:"outline",size:"icon",onClick:ke,title:"Atualizar",children:e.jsx(Ei,{className:we("w-4 h-4",z&&"animate-spin")})}),e.jsx(jt,{permission:"proposals.manage",children:e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>M("/proposal-templates"),children:[e.jsx(xt,{className:"w-4 h-4 mr-2"})," Templates"]})}),e.jsx(jt,{permission:"proposals.manage",children:e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>Me(!0),children:[e.jsx(zl,{className:"w-4 h-4 mr-2"})," Workflow"]})}),e.jsx(jt,{permission:"proposals.create",children:e.jsxs(g,{variant:"outline",onClick:()=>ti(!0),children:[e.jsx(Ts,{className:"w-4 h-4 mr-2"})," Gerar com IA"]})}),e.jsxs(vt,{open:F,onOpenChange:t=>{y(t),t||ga()},children:[e.jsx(jt,{permission:"proposals.create",children:e.jsx(Ln,{asChild:!0,children:e.jsxs(g,{children:[e.jsx(zs,{className:"w-4 h-4 mr-2"})," Nova Proposta"]})})}),e.jsxs(bt,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Nt,{children:e.jsx(wt,{children:R(m?"proposals.editProposal":"proposals.newProposal")})}),m&&e.jsx("div",{className:"px-1 mb-4",children:e.jsx(kl,{entityType:"proposal",entityId:m})}),e.jsxs("form",{onSubmit:Ur,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsxs(me,{htmlFor:"title",children:[R("proposals.form.title")," *"]}),e.jsx(kt,{id:"title",value:I.title,onChange:t=>Oe({...I,title:t.target.value}),required:!0,className:ps.title?"border-destructive":""}),ps.title&&e.jsx("p",{className:"text-sm text-destructive",children:ps.title})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(me,{htmlFor:"value",children:[R("proposals.form.value")," *"]}),e.jsx(kt,{id:"value",type:"number",step:"0.01",value:I.value,onChange:t=>Oe({...I,value:t.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(me,{htmlFor:"valid_until",children:R("proposals.form.validUntil")}),e.jsx(kt,{id:"valid_until",type:"date",value:I.valid_until,onCh
10ange:t=>Oe({...I,valid_until:t.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(me,{htmlFor:"assigned_to",children:"Comercial"}),e.jsxs(Rt,{value:I.assigned_to||"__none__",onValueChange:t=>Oe({...I,assigned_to:t==="__none__"?"":t}),children:[e.jsx(zt,{children:e.jsx($t,{placeholder:"Sem comercial"})}),e.jsxs(Ot,{children:[e.jsx(tt,{value:"__none__",children:"Sem comercial"}),te.map(t=>e.jsx(tt,{value:t.id,children:t.name},t.id))]})]})]}),e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsxs(me,{htmlFor:"stage_id",children:[R("proposals.form.status")," *"]}),e.jsxs(Rt,{value:I.stage_id,onValueChange:t=>Oe({...I,stage_id:t}),children:[e.jsx(zt,{children:e.jsx($t,{placeholder:R("proposals.form.selectStatus")})}),e.jsx(Ot,{children:x.map(t=>e.jsx(tt,{value:t.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:t.color}}),t.label]})},t.id))})]})]}),es.length>0&&e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsxs(me,{className:"flex items-center gap-2",children:[e.jsx($i,{className:"h-4 w-4"}),"Template de Proposta"]}),e.jsxs(Rt,{value:I.template_id,onValueChange:t=>Oe({...I,template_id:t==="none"?"":t}),children:[e.jsx(zt,{children:e.jsx($t,{placeholder:"Template default"})}),e.jsxs(Ot,{children:[e.jsx(tt,{value:"none",children:"Nenhum (usa default)"}),es.map(t=>e.jsx(tt,{value:t.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[t.name,t.is_default&&e.jsx(de,{variant:"secondary",className:"text-xs ml-1",children:"Default"})]})},t.id))]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Define o design da proposta no portal e no PDF"})]}),e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsx(me,{children:R("proposals.form.deal")}),e.jsx("div",{className:"relative",children:U?e.jsxs("div",{className:"flex items-start gap-2 p-3 border rounded-md bg-muted/30",children:[e.jsx(de,{variant:"secondary",className:"shrink-0 mt-0.5",children:"Pedido"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium",children:U.title}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 mt-1",children:[U.lead_name&&e.jsx("span",{className:"text-xs text-muted-foreground",children:U.lead_name}),U.lead_phone&&e.jsx("span",{className:"text-xs text-muted-foreground",children:U.lead_phone}),U.lead_email&&e.jsx("span",{className:"text-xs text-muted-foreground",children:U.lead_email})]})]}),e.jsx(g,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0",onClick:()=>{ts(null),Oe({...I,deal_id:""}),dt([])},children:e.jsx(ns,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(kt,{placeholder:R("proposals.form.searchDealPlaceholder")||"Pesquisar pedidos de proposta...",value:rr,onChange:async t=>{const s=t.target.value;if(fs(s),s.trim().length>=1){const r=`%${s.trim().replace(/^@/,"").toLowerCase()}%`,{data:{user:l}}=await d.auth.getUser(),p=Ae("proposals.view"),w=at.length>0?at:i!=null&&i.id?[i.id]:[],[A,N,V]=await Promise.all([d.from("anew_entities").select("id").or(`display_name.ilike.${r},first_name.ilike.${r},last_name.ilike.${r}`).limit(100),d.from("anew_entity_emails").select("entity_id").ilike("email",r).limit(100),d.from("anew_entity_phones").select("entity_id").ilike("phone_number",r).limit(100)]),he=Array.from(new Set([...(A.data||[]).map(f=>f.id),...(N.data||[]).map(f=>f.entity_id),...(V.data||[]).map(f=>f.entity_id)].filter(Boolean))),le="id, title, probability, value, description, expected_close_date, entity_id, deal_stages(name)";let ve=[];if(p==="ORG"||Je){const f=[d.from("deals").select(le).in("organization_id",w).ilike("title",r).limit(10)];he.length>0&&f.push(d.from("deals").select(le).in("organization_id",w).in("entity_id",he).limit(20));const k=await Promise.all(f),oe=new Map;
10k.forEach(K=>(K.data||[]).forEach(ut=>oe.set(ut.id,ut))),ve=Array.from(oe.values())}else if(l!=null&&l.id){const f=new Set;je&&f.add(je),p==="TEAM"&&Pe.length>0&&Pe.forEach(K=>f.add(K));const{data:k}=await d.from("anew_leads").select("id").in("organization_id",w).in("assigned_to",Array.from(f)),oe=(k||[]).map(K=>K.id);if(oe.length>0){const K=[d.from("deals").select(le).in("organization_id",w).in("lead_id",oe).ilike("title",r).limit(10)];he.length>0&&K.push(d.from("deals").select(le).in("organization_id",w).in("lead_id",oe).in("entity_id",he).limit(20));const ut=await Promise.all(K),B=new Map;ut.forEach(S=>(S.data||[]).forEach(Ve=>B.set(Ve.id,Ve))),ve=Array.from(B.values())}}const De=ve.map(f=>f.entity_id).filter(Boolean);let J={};if(De.length>0){const[f,k,oe]=await Promise.all([d.from("anew_entities").select("id, display_name").in("id",De),d.from("anew_entity_emails").select("entity_id, email").in("entity_id",De).eq("is_primary",!0),d.from("anew_entity_phones").select("entity_id, phone_number").in("entity_id",De).eq("is_primary",!0)]);(f.data||[]).forEach(K=>{J[K.id]={name:K.display_name}}),(k.data||[]).forEach(K=>{J[K.entity_id]&&(J[K.entity_id].email=K.email)}),(oe.data||[]).forEach(K=>{J[K.entity_id]&&(J[K.entity_id].phone=K.phone_number)})}Qt(ve.map(f=>{var oe;const k=J[f.entity_id]||{};return{id:f.id,title:f.title,probability:f.probability,value:f.value,expected_close_date:f.expected_close_date,stage_name:((oe=f.deal_stages)==null?void 0:oe.name)||null,lead_name:k.name||null,lead_phone:k.phone||null,lead_email:k.email||null}})),It(ve.length>0)}else Qt([]),It(!1)},onFocus:()=>{la.length>0&&It(!0)},onBlur:()=>{setTimeout(()=>It(!1),200)},className:ps.deal_id?"border-destructive":""}),nr&&la.length>0&&e.jsx("div",{className:"absolute top-full left-0 right-0 mt-1 bg-popover border rounded-md shadow-lg z-50 max-h-[280px] overflow-y-auto",children:la.map(t=>e.jsxs("button",{type:"button",className:"w-full px-3 py-3 text-left hover:bg-muted border-b last:border-b-0",onMouseDown:s=>s.preventDefault(),onClick:async()=>{ts(t),Oe({...I,deal_id:t.id}),fs(""),It(!1),Qt([]);const{data:s}=await d.from("quotes").select("id, quote_number, total, estado").eq("deal_id",t.id).neq("estado","rascunho").order("created_at",{ascending:!1});if(s&&s.length>0)dt(s.map(a=>({id:a.id,quote_number:a.quote_number,total:a.total,estado:a.estado})));else{dt([]);let a=!1;try{const{data:r}=await d.from("deal_needs").select("id, title").eq("deal_id",t.id);if(r&&r.length>0){const l=r.map(w=>w.id),{data:p}=await d.from("deal_need_items").select("*").in("deal_need_id",l).order("sort_order");if(p&&p.length>0){const w=p.filter(S=>S.product_id).map(S=>S.product_id),A=p.filter(S=>S.service_id).map(S=>S.service_id),[N,V,he,le,ve,De]=await Promise.all([w.length>0?d.from("product_prices").select("product_id, price, vat_rate").eq("price_type","retail").in("product_id",w):Promise.resolve({data:[]}),w.length>0?d.from("product_prices").select("product_id, price").eq("price_type","purchase").in("product_id",w):Promise.resolve({data:[]}),A.length>0?d.from("service_prices").select("service_id, price, vat_rate").eq("price_type","retail").in("service_id",A):Promise.resolve({data:[]}),A.length>0?d.from("service_prices").select("service_id, price").eq("price_type","purchase").in("service_id",A):Promise.resolve({data:[]}),w.length>0?d.from("products").select("id, name, sku").in("id",w):Promise.resolve({data:[]}),A.length>0?d.from("services").select("id, name, sku").in("id",A):Promise.resolve({data:[]})]),J=new Map((N.data||[]).map(S=>[S.product_id,S])),f=new Map((V.data||[]).map(S=>[S.product_id,S])),k=new Map((he.data||[]).map(S=>[S.service_id,S])),oe=new Map((le.data||[]).map(S=>[S.service_id,S])),K=new Map((ve.data||[]).map(S=>[S.id,S])),ut=new Map((De.data||[]).map(S=>[S.id,S])),B=p.map((S,Ve)=>{let C=S.notes||"Item",X=0,fe=0,be=23,We=null;const Ze=S.unit_price?parseFloat(S.unit_price):null;if(S.item_type==="product"&&S.product_id){const He=K.get(S.product_id),Ge=J.get(S.product_id),_t=f.get(S.product_id);He&&(C=He.name,We=He.sku),X=Ze??((Ge==null?void 0:Ge.price)||0),fe=(_t==null?void 0:_t.price)||0,be=(Ge==null?void 0:Ge.vat_rate)||23}else if(S.item_type==="service"&&S.service_id){const He=ut.get(S.service_id),Ge=k.get(S.service_id),_t=oe.get(S.service_id);He&&(C=He.name,We=He.sku),X=Ze??((Ge==null?void 0:Ge.price)||0),fe=(_t==null?void 0:_t.price)||0,be=(Ge==null?void 0:Ge.vat_rate)||23}else Ze&&(X=Ze);const Ne=fe>0&&X>0?(X-fe)/fe*100:30;return{id:`temp_deal_${Date.now()}_${Ve}`,section_name:"Geral",descricao_snapshot:C,item_description:"",qt:S.quantity||1,unidade:void 0,custo_material_unit:fe>0?fe:X>0?X/(1+Ne/100):0,custo_mao_obra_unit:0,margem_percent:Math.round(Ne*100)/100,iva_percent:be,int_percent:0,discount_percent:0,ordem:Ve+1,product_id:S.item_type==="product"?S.product_id:null,
10service_id:S.item_type==="service"?S.service_id:null,retail_price_unit:X,cost_price:fe}});if(B.length>0){const S=zi(t.title);S.lines=B,ss([S]),a=!0}}}if(!a){const l=t.value?parseFloat(String(t.value)):0;if(l>0){const w=l/1.3,A=zi(t.title);A.lines=[{id:`temp_deal_fallback_${Date.now()}`,section_name:"Geral",descricao_snapshot:t.title||"Pedido de Proposta",item_description:"",qt:1,unidade:void 0,custo_material_unit:w,custo_mao_obra_unit:0,margem_percent:30,iva_percent:23,int_percent:0,discount_percent:0,ordem:1,product_id:null,service_id:null,retail_price_unit:l,cost_price:w}],ss([A])}}}catch(r){console.error("Error loading deal items for inline quote:",r)}}},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(de,{variant:"secondary",className:"text-xs shrink-0",children:"Pedido"}),e.jsx("span",{className:"text-sm font-medium truncate",children:t.title})]}),t.lead_name&&e.jsx("div",{className:"text-xs text-muted-foreground mt-1 ml-[52px]",children:t.lead_name})]},t.id))})]})})]}),!U&&!I.deal_id&&e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsx(me,{children:"Lead ou Cliente"}),e.jsx(ll,{value:xe,onChange:or,searchTypes:["lead","client"],placeholder:"Pesquisar lead ou cliente para associar...",hint:"Escreva pelo menos 2 caracteres (nome, email, telefone ou NIF) para pesquisar em leads e clientes"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Opcional — associe uma lead ou cliente diretamente quando não existe Pedido de Proposta."})]}),e.jsxs("div",{className:"col-span-2 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(me,{className:"text-base font-semibold",children:"Orçamentos"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(g,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs gap-1",onClick:()=>Ba(!Qa),children:"🔗 Associar existente"}),Qa&&e.jsxs("div",{className:"absolute z-50 top-8 left-0 w-80 bg-popover border rounded-lg shadow-lg p-2",children:[e.jsx(kt,{placeholder:"Pesquisar orçamentos...",value:Va,autoFocus:!0,onChange:t=>dr(t.target.value),className:"h-8 text-xs mb-2"}),Fa.length>0?e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:Fa.filter(t=>!Le.some(s=>s.id===t.id)).map(t=>e.jsxs("button",{type:"button",className:"w-full text-left px-2 py-1.5 rounded text-xs hover:bg-accent flex justify-between items-center",onClick:()=>{dt([...Le,t]),Ba(!1),gs(""),_s([])},children:[e.jsx("span",{className:"font-medium",children:t.quote_number||`#${t.id.slice(0,8)}`}),e.jsx("span",{className:"text-muted-foreground",children:t.total?H(t.total):"—"})]},t.id))}):Va.length>=2?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Nenhum orçamento encontrado"}):e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Digite para pesquisar..."})]})]}),e.jsx(g,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs gap-1",disabled:ee,onClick:Hr,children:"📝 Criar orçamento aqui"})]})]}),Le.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:Le.map(t=>e.jsxs(de,{variant:"secondary",className:"flex items-center gap-1 px-2 py-1",children:[e.jsxs("span",{children:["🔗 ",t.quote_number||`#${t.id.slice(0,8)}`]}),t.total&&e.jsx("span",{className:"text-xs",children:H(t.total)}),e.jsx(g,{type:"button",variant:"ghost",size:"icon",className:"h-4 w-4 ml-1 p-0",title:"Editar orçamento",onClick:()=>{y(!1),M(`/quotes?edit=${t.id}`)},children:e.jsx(ba,{className:"h-3 w-3"})}),e.jsx(g,{type:"button",variant:"ghost",size:"icon",className:"h-4 w-4 p-0",title:"Remover associação",onClick:()=>dt(Le.filter(s=>s.id!==t.id)),children:e.jsx(ns,{className:"h-3 w-3"})})]},t.id))}),(()=>{const t=lr.filter(s=>
10!Le.some(a=>a.id===s.id));return t.length===0?null:e.jsxs("div",{className:"rounded-md border border-dashed bg-muted/20 p-2 space-y-1.5",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Orçamentos em rascunho disponíveis ",U?"para este Pedido":"deste contacto/cliente",":"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.map(s=>e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 px-2 py-1 rounded border bg-background hover:bg-accent text-xs",onClick:()=>dt([...Le,s]),children:[e.jsx(zs,{className:"h-3 w-3"}),e.jsx("span",{className:"font-medium",children:s.quote_number||`#${s.id.slice(0,8)}`}),s.estado==="rascunho"&&e.jsx(de,{variant:"outline",className:"text-[10px] h-4 px-1",children:"Rascunho"}),s.total!=null&&e.jsx("span",{className:"text-muted-foreground",children:H(s.total)})]},s.id))})]})})(),Qe.map((t,s)=>e.jsx(Rl,{quote:t,onChange:a=>{const r=[...Qe];r[s]=a,ss(r)},onRemove:()=>ss(Qe.filter((a,r)=>r!==s)),proposalTitle:I.title,organizationId:i==null?void 0:i.id},t.tempId))]}),e.jsxs("div",{className:"col-span-2",children:[m&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx("div",{className:"flex items-center justify-between mb-4",children:e.jsx(me,{className:"text-base font-semibold",children:"Itens Manuais"})}),e.jsx(dl,{proposalId:m})]}),(Le.length>0||Qe.length>0)&&e.jsx("div",{className:"mt-3 p-3 bg-muted/50 rounded-lg",children:e.jsxs("div",{className:"text-sm space-y-1",children:[Le.length>0&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Orçamentos associados:"}),e.jsx("span",{className:"font-medium",children:H(Le.reduce((t,s)=>t+(s.total||0),0))})]}),Qe.length>0&&e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Orçamentos inline (",Qe.length,"):"]}),e.jsx("span",{className:"font-medium",children:H(Qe.reduce((t,s)=>t+As(s),0))})]}),e.jsx(St,{className:"my-2"}),e.jsxs("div",{className:"flex justify-between font-semibold",children:[e.jsx("span",{children:"Total:"}),e.jsx("span",{className:"text-primary",children:H(Le.reduce((t,s)=>t+(s.total||0),0)+Qe.reduce((t,s)=>t+As(s),0))})]})]})})]}),e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsx(me,{htmlFor:"description",children:R("proposals.form.description")}),e.jsx(Rs,{id:"description",value:I.description,onChange:t=>Oe({...I,description:t.target.value}),rows:3})]}),e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsx(me,{htmlFor:"notes",children:R("proposals.form.notes")}),e.jsx(Rs,{id:"notes",value:I.notes,onChange:t=>Oe({...I,notes:t.target.value}),rows:2})]})]}),e.jsxs(Vt,{className:"flex justify-between sm:justify-between",children:[e.jsx("div",{children:m&&e.jsxs(g,{type:"button",variant:"outline",size:"sm",className:"gap-1",onClick:()=>ua(!0),children:[e.jsx(rt,{className:"h-4 w-4"})," Preview Portal"]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{type:"button",variant:"outline",onClick:()=>y(!1),children:R("proposals.form.cancel")}),e.jsx(g,{type:"submit",disabled:ee,children:R(m?"proposals.form.update":"proposals.form.create")})]})]})]})]})]})]})]})]}),e.jsx("div",{className:"flex-shrink-0 px-4 md:px-6",children:e.jsx(Xl,{})}),e.jsx("div",{className:"flex-shrink-0 px-4 md:px-6 mt-2",children:e.jsx(Zl,{proposals:Be.map(t=>{var s,a;return{id:t.id,title:t.title,value:Number(t.value),status:t.status,stage_name:(s=pe(t))==null?void 0:s.name,valid_until:t.valid_until,created_at:t.created_at,sent_at:t.sent_at??null,updated_at:t.updated_at,contract_id:(a=rs[t.id])==null?void 0:a.contract_id}}),noResponseDays:$e.get("proposal_no_response",5).days_threshold,noResponseUrgentDays:$e.get("proposal_no_response_urgent",10).days_threshold,noResponseEnabled:$e.get("proposal_no_response",5).is_active,noResponseUrgentEnabled:$e.get("proposal_no_response_urgent",10).is_active,expiredEnabled:$e.get("proposal_expired").is_active,noValidityEnabled:$e.get("proposal_no_validity").is_active,draftStaleEnabled:$e.get("proposal_draft_stale",5).is_active,draftStaleDays:$e.get("proposal_draft_stale",5).days_threshold,onNavigateContracts:()=>M("/client-contracts"),onRenewValidity:bi,onOpenProposal:t=>{const s=c.find(a=>a.id===t);s&&mt(s)}})}),e.jsxs("div",{className:"flex-shrink-0 px-4 md:px-6 mt-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1 bg-muted/50 rounded-lg p-1",children:[e.jsxs(g,{variant:se==="lista"?"default":"ghost",size:"sm",className:"h-8 gap-1.5",onClick:()=>qe("lista"),children:[e.jsx($l,{className:"h-3.5 w-3.5"})," Lista"]}),e.jsxs(g,{variant:se==="kanban"?"default":"ghost",size:"sm",className:"h-8 gap-1.5",onClick:()=>qe("kanban"),children:[e.jsx(Oi,{className:"h-3.5 w-3.5"})," Kanban"]}),e.jsxs(g,{variant:se==="dashboard"?"default":"ghost",size:"sm",className:"h-8 gap-1.5",onClick:()=>
10qe("dashboard"),children:[e.jsx(Vn,{className:"h-3.5 w-3.5"})," Dashboard"]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Total: ",Ie.total," · Pipeline: ",e.jsx("span",{className:"font-semibold text-foreground",children:H(Ie.totalValue)})," · Aceite: ",e.jsx("span",{className:"font-bold text-green-600",children:H(Ie.wonValue)})]})]}),e.jsx("div",{className:"flex-shrink-0 px-4 md:px-6 mt-1",children:e.jsxs("div",{className:"flex gap-2 overflow-x-auto pb-1",children:[e.jsx(_e,{className:we("cursor-pointer hover:shadow-md transition-all min-w-[110px] flex-shrink-0",ft==="all"&&"ring-2 ring-primary shadow-md"),onClick:()=>Zt("all"),children:e.jsxs(Se,{className:"p-2",children:[e.jsx("div",{className:"text-[10px] text-muted-foreground font-medium uppercase leading-tight",children:"Total"}),e.jsx("div",{className:"text-base font-bold leading-tight",children:Ie.total}),e.jsx("div",{className:"text-[10px] text-muted-foreground leading-tight",children:H(Ie.totalValue)})]})}),x.map(t=>e.jsx(_e,{className:we("cursor-pointer hover:shadow-md transition-all min-w-[110px] flex-shrink-0",ft===t.id&&"ring-2 ring-primary shadow-md"),onClick:()=>Zt(t.id===ft?"all":t.id),children:e.jsxs(Se,{className:"p-2",children:[e.jsx("div",{className:"text-[10px] font-medium uppercase leading-tight truncate",style:{color:t.color},children:t.label}),e.jsx("div",{className:"text-base font-bold leading-tight",style:{color:t.color},children:Ie.stageCounts[t.id]||0}),e.jsx("div",{className:"text-[10px] text-muted-foreground leading-tight",children:H(Ie.stageValues[t.id]||0)})]})},t.id)),e.jsx(_e,{className:"min-w-[130px] flex-shrink-0 bg-gradient-to-br from-green-500/10 to-green-500/5",children:e.jsxs(Se,{className:"p-2",children:[e.jsx("div",{className:"text-[10px] text-muted-foreground font-medium uppercase leading-tight",children:"Valor Aceite"}),e.jsx("div",{className:"text-base font-bold text-green-600 leading-tight",children:H(Ie.wonValue)})]})}),e.jsx(_e,{className:"min-w-[110px] flex-shrink-0",children:e.jsxs(Se,{className:"p-2",children:[e.jsx("div",{className:"text-[10px] text-muted-foreground font-medium uppercase leading-tight",children:"Taxa Conv."}),e.jsxs("div",{className:"text-base font-bold text-primary leading-tight",children:[Ie.conversionRate,"%"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground leading-tight",children:[Be.filter(t=>{var s;return(s=pe(t))==null?void 0:s.is_won}).length," aceites"]})]})}),e.jsx(_e,{className:"min-w-[110px] flex-shrink-0",children:e.jsxs(Se,{className:"p-2",children:[e.jsx("div",{className:"text-[10px] text-muted-foreground font-medium uppercase leading-tight",children:"T. Médio"}),e.jsxs("div",{className:"text-base font-bold text-primary leading-tight",children:[Ie.avgCloseTime,"d"]})]})}),Ie.noResponse5d.length>0&&e.jsx(_e,{className:"min-w-[130px] flex-shrink-0 border-orange-200 bg-orange-50/50 dark:bg-orange-950/20 cursor-pointer",onClick:()=>Ys(!Pt),children:e.jsxs(Se,{className:"p-2",children:[e.jsx("div",{className:"text-[10px] text-orange-600 font-medium uppercase leading-tight",children:"S/ Resp. +5d"}),e.jsx("div",{className:"text-base font-bold text-orange-600 leading-tight",children:Ie.noResponse5d.length}),e.jsx("div",{className:"text-[10px] text-orange-500 leading-tight",children:H(Ie.noResponse5dValue)})]})}),Ie.noValidity.length>0&&e.jsx(_e,{className:"min-w-[110px] flex-shrink-0 border-amber-200 bg-amber-50/50 dark:bg-amber-950/20 cursor-pointer",onClick:()=>za(!xs),children:e.jsxs(Se,{className:"p-2",children:[e.jsx("div",{className:"text-[10px] text-amber-600 font-medium uppercase leading-tight",children:"S/ Validade"}),e.jsx("div",{className:"text-base font-bold text-amber-600 leading-tight",children:Ie.noValidity.length})]})}),Ie.expired.length>0&&e.jsx(_e,{className:"min-w-[110px] flex-shrink-0 border-red-200 bg-red-50/50 dark:bg-red-950/20 cursor-pointer",onClick:()=>ea(!qt),children:e.jsxs(Se,{className:"p-2",children:[e.jsx("div",{className:"text-[10px] text-red-600 font-medium uppercase leading-tight",children:"Expiradas"}),e.jsx("div",{className:"text-base font-bold text-red-600 leading-tight",children:Ie.expired.length})]})})]})}),se==="dashboard"?e.jsx(eo,{proposals:Be,workflowStages:x,getProposalStage:pe,comercialNamesMap:Zs,stageCounts:Ie.stageCounts,stageValues:Ie.stageValues,isLoading:z}):se==="kanban"?e.jsx(so,{proposals:Gt.map(t=>{const s=t.entity_id;return s||`${t.id}`,{...t,entity_name:Mt[s]||Mt[`deal:${t.id}`]||null,entity_email:mi[s]||mi[`deal:${t.id}`]||null,entity_phone:Ht[s]||Ht[`deal:${t.id}`]||null}}),workflowStages:x,getProposalStage:pe,onMoveStage:async(t,s)=>{const{error:a}=await d.from("proposals").update({stage_id:s}).eq("id",t);a?D({title:"Erro",description:a.message,variant:"destructive"}):(D({title:"Proposta movida"}),ke())},onViewProposal:t=>{$(t),v(!0)}}):e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col px-4 md:px-6 mt-2 pb-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(Wi,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(kt,{placeholder:"Procurar por título, cliente, pedido, valor...",value:W,onChange:t=>Te(t.target.value),className:"pl-10"})]}),e.jsx(g,{variant:Yt?"default":"outline",size:"sm",className:"gap-1.5",onClick:()=>Ta(!Yt),children:"👤 Só as minhas"}),e.jsxs(Rt,{value:ft,onValueChange:Zt,children:[e.jsx(zt,{className:"w-[140px]",children:e.jsx($t,{placeholder:"Estado"})}),e.jsxs(Ot,{children:[e.jsx(tt,{value:"all",children:"Todos"}),x.map(t=>e.jsx(tt,{value:t.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:t.color}}),t.label]})},t.id))]})]}),e.jsxs(Rt,{value:Ct,onValueChange:Ra,children:[e.jsx(zt,{className:"w-[160px]",children:e.jsx($t,{placeholder:"Comercial"})}),e.jsxs(Ot,{children:[e.jsx(tt,{value:"all",children:"Todos os comerciais"}),e.jsx(tt,{value:"none",children:"Sem comercial"}),te.map(t=>e.jsx(tt,{value:t.id,children:t.name},t.id))]})]}),e.jsxs(Fn,{children:[e.jsx(Qn,{asChild:!0,children:e.jsxs(g,{variant:"outline",size:"sm",className:"h-9 gap-1.5 font-normal",children:[e.jsx(qa,{className:"h-4 w-4"}),lt&&ot?`${Re(lt,"dd/MM/yy")} - ${Re(ot,"dd/MM/yy")}`:lt?`Desde ${Re(lt,"dd/MM/yy")}`:ot?`Até ${Re(ot,"dd/MM/yy")}`:"Data"]})}),e.jsxs(Bn,{className:"w-auto p-0",align:"start",children:[e.jsx("div",{className:"px-3 pt-3 pb-1 text-xs text-muted-foreground max-w-[420px]",children:"Inclui propostas criadas no período ou com orçamentos criados no período."}),e.jsx(ol,{mode:"range",selected:{from:lt,to:ot},onSelect:t=>{Ks(t==null?void 0:t.from),Xs(t==null?void 0:t.to)},numberOfMonths:2,locale:nt}),(lt||ot)&&e.jsx("div",{className:"p-2 border-t flex justify-end",children:e.jsx(g,{variant:"ghost",size:"sm",onClick:()=>{Ks(void 0),Xs(void 0)},children:"Limpar datas"})})]})]}),e.jsx(g,{variant:Pt?"default":"outline",size:"sm",className:we("gap-1",Pt&&"bg-orange-600 hover:bg-orange-700"),onClick:()=>Ys(!Pt),children:"⏰ Sem resposta +5d"}),e.jsx(g,{variant:qt?"default":"outline",size:"sm",className:we("gap-1",qt&&"bg-red-600 hover:bg-red-700"),onClick:()=>ea(!qt),children:"⏳ Expiradas"}),Yr&&e.jsxs(g,{variant:"ghost",size:"sm",onClick:Zr,children:[e.jsx(ns,{className:"w-4 h-4 mr-1"})," Limpar"]})]}),Xe.length>0&&e.jsxs("div",{className:"mb-4 flex items-center gap-3 px-4 py-2.5 rounded-lg border border-primary/30 bg-primary/5",children:[e.jsxs("span",{className:"text-sm font-medium text-primary",children:[Xe.length," proposta",Xe.length>
101?"s":""," seleccionada",Xe.length>1?"s":""]}),e.jsxs("div",{className:"flex gap-2 ml-auto",children:[e.jsxs(g,{variant:"outline",size:"sm",children:[e.jsx(ht,{className:"w-3.5 h-3.5 mr-1"})," Enviar email"]}),e.jsxs(g,{variant:"outline",size:"sm",onClick:()=>Ns(!0),children:[e.jsx(Oi,{className:"w-3.5 h-3.5 mr-1"})," Mover estado"]}),e.jsxs(g,{variant:"outline",size:"sm",children:[e.jsx(xt,{className:"w-3.5 h-3.5 mr-1"})," Exportar PDF"]}),e.jsxs(g,{variant:"outline",size:"sm",children:[e.jsx(Li,{className:"w-3.5 h-3.5 mr-1"})," Gerar links públicos"]}),e.jsx(g,{variant:"ghost",size:"sm",onClick:()=>Dt([]),children:e.jsx(ns,{className:"w-4 h-4"})})]})]}),Gt.length===0?e.jsx(_e,{children:e.jsxs(Se,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(xt,{className:"w-12 h-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:c.length===0?R("proposals.noProposals"):"Nenhum resultado encontrado"}),c.length===0&&e.jsx(jt,{permission:"proposals.create",children:e.jsxs(g,{onClick:()=>y(!0),children:[e.jsx(zs,{className:"w-4 h-4 mr-2"})," ",R("proposals.createFirst")]})})]})}):e.jsx(_e,{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:e.jsx("div",{className:"flex-1 min-h-0 overflow-auto quotes-table-scroll",children:e.jsxs(Hn,{density:"compact",containerClassName:"overflow-visible",className:"min-w-[1400px]",children:[e.jsx(Un,{className:"sticky top-0 bg-card z-10",children:e.jsxs(Mi,{children:[e.jsx(Ye,{className:"w-[40px]",children:e.jsx(Ai,{checked:Gt.length>0&&Xe.length===Gt.length,onCheckedChange:t=>Lr(!!t)})}),e.jsx(Ye,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>Wt("proposal_number"),children:e.jsxs("div",{className:"flex items-center",children:["Número ",e.jsx(Jt,{column:"proposal_number"})]})}),e.jsx(Ye,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>Wt("title"),children:e.jsxs("div",{className:"flex items-center",children:["Título ",e.jsx(Jt,{column:"title"})]})}),e.jsx(Ye,{children:"Cliente"}),e.jsx(Ye,{children:"Comercial"}),e.jsx(Ye,{children:"Pedido"}),e.jsx(Ye,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>Wt("value"),children:e.jsxs("div",{className:"flex items-center",children:["Valor ",e.jsx(Jt,{column:"value"})]})}),e.jsx(Ye,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>Wt("status"),children:e.jsxs("div",{className:"flex items-center",children:["Estado ",e.jsx(Jt,{column:"status"})]})}),e.jsx(Ye,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>Wt("valid_until"),children:e.jsxs("div",{className:"flex items-center",children:["Válida até ",e.jsx(Jt,{column:"valid_until"})]})}),e.jsx(Ye,{children:"Pipeline"}),e.jsx(Ye,{children:"Portal"}),e.jsx(Ye,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>Wt("created_at"),children:e.jsxs("div",{className:"flex items-center",children:["Criada ",e.jsx(Jt,{column:"created_at"})]})}),e.jsx(Ye,{className:"text-right",children:"Acções"})]})}),e.jsx(Gn,{children:Gt.map(t=>{const s=en(t),a=pe(t),r=rs[t.id];return e.jsxs(Mi,{className:we("hover:bg-muted/50 transition-colors",tn(t),Ja.has(t.id)&&"ring-1 ring-primary/30"),children:[e.jsx(et,{children:e.jsx("span",{className:"font-mono font-semibold text-sm text-primary whitespace-nowrap",children:t.proposal_number||"-"})}),e.jsx(et,{children:e.jsx(Ai,{checked:Ja.has(t.id),onCheckedChange:l=>Vr(t.id,!!l)})}),e.jsx(et,{children:e.jsx("div",{className:"min-w-[160px]",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-1 h-8 rounded-full flex-shrink-0",style:{backgroundColor:(a==null?void 0:a.color)||"transparent"}}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-sm",children:t.title}),s&&e.jsx("div",{className:we("text-[11px] mt-0.5",s.color),children:s.text})]})]})})}),e.jsx(et,{children:(()=>{const l=t.entity_id,p=l?Mt[l]:Mt[`deal:${t.id}`];return p?e.jsx("span",{className:"text-sm",children:p}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})})()}),e.jsx(et,{children:t.assigned_to?e.jsx("span",{className:"text-xs",children:Zs[t.assigned_to]||"..."}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}
10),e.jsx(et,{children:t.deals?e.jsx(g,{variant:"link",size:"sm",className:"h-auto p-0 text-xs text-primary",onClick:()=>M(`/deals?open=${t.deal_id}`),children:t.deals.title}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),e.jsx(et,{children:e.jsx("span",{className:we("font-bold text-base",a!=null&&a.is_lost?"line-through text-muted-foreground":"text-foreground"),children:(()=>{const{subtotal:l,total:p}=gt(t);return e.jsxs(e.Fragment,{children:[H(l),p>0&&p!==l&&e.jsxs("span",{className:"block text-[10px] text-muted-foreground tabular-nums",children:["c/ IVA: ",H(p)]})]})})()})}),e.jsx(et,{children:Xr(t)}),e.jsx(et,{children:t.valid_until?e.jsxs("span",{className:we("text-sm",Lt(Ee(t.valid_until))&&!(a!=null&&a.is_won)?"text-red-500 font-medium":"text-muted-foreground"),children:[Lt(Ee(t.valid_until))&&!(a!=null&&a.is_won)&&"⚠ ",Re(new Date(t.valid_until),"dd/MM/yyyy",{locale:nt}),Lt(Ee(t.valid_until))&&!(a!=null&&a.is_won)&&e.jsxs("span",{className:"text-[10px] block",children:["(",it(new Date,Ee(t.valid_until))," dias)"]})]}):e.jsx("span",{className:"text-xs text-amber-500",children:"⚠ Não definida"})}),e.jsx(et,{children:e.jsx(to,{dealExists:!!t.deal_id,quoteExists:!!(r!=null&&r.quote_id)||Pr.has(t.id),proposalStatus:(a==null?void 0:a.name)||t.status,contractCreated:!!(r!=null&&r.contract_id),pipelineLabel:r!=null&&r.contract_id?"Contrato ✅":a!=null&&a.is_won?"A criar contrato...":a!=null&&a.is_lost?"Pipeline parado":"A aguardar"})}),e.jsx(et,{children:e.jsx(nl,{status:(fa==null?void 0:fa[t.id])||null})}),e.jsx(et,{className:"text-sm text-muted-foreground",children:Re(new Date(t.created_at),"dd/MM/yyyy",{locale:nt})}),e.jsx(et,{children:e.jsxs("div",{className:"flex justify-end gap-0.5",children:[sn(t),e.jsxs(Wn,{children:[e.jsx(Jn,{asChild:!0,children:e.jsx(g,{variant:"ghost",size:"icon",className:"h-7 w-7",children:e.jsx(Ol,{className:"w-3.5 h-3.5"})})}),an(t)]})]})})]},t.id)})})]})})})]})]}),e.jsx(Jl,{open:j,onOpenChange:v,proposal:h,onSendProposal:()=>{h&&(ws(h),is(!0),v(!1))},onViewHistory:()=>{h&&(Ya(h.id),ei(h.title),ma(!0),v(!1))},onAccept:Ni,onReject:wi}),e.jsx($s,{open:ie,onOpenChange:L,children:e.jsxs(Os,{children:[e.jsxs(Ls,{children:[e.jsx(Vs,{children:"Tem a certeza que quer eliminar esta proposta?"}),e.jsx(Fs,{asChild:!0,children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{children:"Esta acção envia a proposta para o Lixo e pode ser revertida a partir de lá."}),re&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[re.proposal_number?`${re.proposal_number} — `:"",re.title," · ",((ki=pe(re))==null?void 0:ki.label)||yt(re)," · ",H(Number(re.value??0))]}),re&&((Si=pe(re))==null?void 0:Si.is_won)&&e.jsx("p",{className:"text-xs font-medium text-destructive",children:"Esta proposta está aceite — ao eliminar, o seu valor deixa de contar no pipeline."}),(()=>{const t=ji(re==null?void 0:re.id);return t?t.status==="signed"?e.jsxs("p",{className:"text-xs font-medium text-amber-600",children:["O contrato assinado ",t.contract_number?`${t.contract_number} `:"","NÃO será eliminado — permanece intacto e acessível no módulo de Contratos. Apenas a proposta vai para o Lixo."]}):e.jsxs("p",{className:"text-xs font-medium text-amber-600",children:["O contrato em rascunho ",t.contract_number?`${t.contract_number} `:"","associado a esta proposta será também enviado para o lixo."]}):null})()]})})]}),e.jsxs(Qs,{children:[e.jsx(Bs,{children:R("proposals.form.cancel")}),e.jsx(Hs,{onClick:Tr,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:R("proposals.actions.delete")})]})]})}),e.jsx(vt,{open:ir,onOpenChange:t=>{hs(t),t||sa(null)},children:e.jsxs(bt,{className:"max-w-md",children:[e.jsxs(Nt,{children:[e.jsx(wt,{children:"Alterar layout do documento"}),e.jsx(Kn,{children:"Só altera o aspecto do documento (PDF e portal). Valores, itens, aceitação e contratos assinados mantêm-se inalterados."})]}),e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(me,{children:"Template de proposta"}),e.jsxs(Rt,{value:aa,onValueChange:$a,children:[e.jsx(zt,{children:e.jsx($t,{placeholder:"Selecionar template"})}),e.jsxs(Ot,{children:[e.jsx(tt,{value:"none",children:"Sem template (predefinido)"}),es.map(t=>e.jsxs(tt,{value:t.id,children:[t.name,t.is_default?" (padrão)":""]},t.id))]})]})]}),e.jsxs(Vt,{children:[e.jsx(g,{variant:"outline",onClick:()=>hs(!1),disabled:ia,children:"Cancelar"}),e.jsx(g,{onClick:zr,disabled:ia,children:ia?"A guardar...":"Aplicar layout"})]})]})}),e.jsx($s,{open:ur,onOpenChange:oa,children:e.jsxs(Os,{children:[e.jsxs(Ls,{children:[e.jsx(Vs,{children:"Republicar proposta aceite?"}),e.jsx(Fs,{asChild:!0,children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{children:"Esta proposta já foi aceite. Foram detetadas alterações nos orçamentos após a aceitação."}),e.jsx("p",{children:"Ao republicar, a assinatura anterior deixa de ser válida e o cliente terá de aceitar e assinar novamente com os novos valores."}),Et&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Et.proposal_number?`${Et.proposal_number} — `:"",Et.title," · ",H(Number(Et.value??0))]}),e.jsx("p",{className:"text-xs font-medium text-amber-600",children:"Nota: se já existir um contrato assinad
10o, a republicação será bloqueada. Se existir apenas um rascunho, ele será removido e regenerado após a nova aceitação."})]})})]}),e.jsxs(Qs,{children:[e.jsx(Bs,{onClick:()=>da(null),children:"Cancelar"}),e.jsx(Hs,{onClick:Or,className:"bg-purple-600 text-white hover:bg-purple-700",children:"Republicar"})]})]})}),e.jsx(Xn,{open:xr,onOpenChange:is,proposal:hr,onSent:()=>ke()}),e.jsx(ml,{open:br,onOpenChange:ii,entityId:(Ue==null?void 0:Ue.entityId)||"",entityName:(Ue==null?void 0:Ue.entityName)||"",organizationId:(i==null?void 0:i.id)||"",contactId:"",onCallRegistered:()=>ke(),onOpenWhatsApp:(t,s,a)=>{const r=Ht[t];if(!r){D({title:"Sem telefone",variant:"destructive"});return}const l=a==null?void 0:a.dealOrProposal;ri({module:(l==null?void 0:l.type)==="quote"?"quotes":"proposals",recipientName:s,recipientPhone:r,entityId:t,hasActiveDeal:!!(Ue!=null&&Ue.proposal.deal_id),proposalTitle:(l==null?void 0:l.type)==="proposal"?l.title:Ue==null?void 0:Ue.proposal.title,proposalValue:(l==null?void 0:l.type)==="proposal"?l.value||0:Number(Ue==null?void 0:Ue.proposal.value)||0,quoteTitle:(l==null?void 0:l.type)==="quote"?l.title:void 0,quoteValue:(l==null?void 0:l.type)==="quote"?l.value||0:void 0}),ha(!0)}}),e.jsx(Ui,{open:wr,onOpenChange:ha,context:yr}),e.jsx(vt,{open:kr,onOpenChange:Ss,children:e.jsxs(bt,{className:"max-w-md",children:[e.jsx(Nt,{children:e.jsx(wt,{children:"Rejeitar proposta"})}),e.jsxs("div",{className:"space-y-3 py-2",children:[e.jsx(me,{children:"Motivo da rejeição"}),e.jsx(Rs,{value:li,onChange:t=>oi(t.target.value),placeholder:"Descreve o motivo (opcional)",rows:4})]}),e.jsxs(Vt,{children:[e.jsx(g,{variant:"outline",onClick:()=>Ss(!1),children:"Cancelar"}),e.jsx(g,{variant:"destructive",onClick:async()=>{ni&&($(ni),await wi(li),Ss(!1))},children:"Rejeitar"})]})]})}),e.jsx(Ul,{open:pr,onOpenChange:ma,proposalId:fr,proposalTitle:gr}),(Ua||m)&&e.jsx(Xi,{open:vr,onOpenChange:t=>{ua(t),t||Ga(null)},proposalId:Ua||m}),e.jsx($s,{open:cr,onOpenChange:Ka,children:e.jsxs(Os,{children:[e.jsxs(Ls,{children:[e.jsx(Vs,{children:R("common.confirmDelete")}),e.jsx(Fs,{children:`Tem a certeza que deseja eliminar ${Xe.length} propostas?`})]}),e.jsxs(Qs,{children:[e.jsx(Bs,{children:R("common.cancel")}),e.jsx(Hs,{onClick:Fr,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:R("common.delete")})]})]})}),e.jsx(vt,{open:mr,onOpenChange:Ns,children:e.jsxs(bt,{children:[e.jsx(Nt,{children:e.jsx(wt,{children:R("common.changeStatus")})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Alterar estado de ",Xe.length," propostas selecionadas."]}),e.jsxs(Rt,{value:as,onValueChange:Xa,children:[e.jsx(zt,{children:e.jsx($t,{placeholder:R("common.newStatus")})}),e.jsx(Ot,{children:x.map(t=>e.jsx(tt,{value:t.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:t.color}}),t.label]})},t.id))})]})]}),e.jsxs(Vt,{children:[e.jsx(g,{variant:"outline",onClick:()=>Ns(!1),children:R("common.cancel")}),e.jsx(g,{onClick:Qr,disabled:!as,children:R("common.save")})]})]})}),e.jsx(Kl,{open:_r,onOpenChange:ti,onApply:t=>{var s;T(null),Oe({title:t.title,description:t.description,value:"",deal_id:"",valid_until:"",notes:"",stage_id:((s=x[0])==null?void 0:s.id)||"",template_id:"",assigned_to:""}),vs(t.items.map((a,r)=>({id:crypto.randomUUID(),description:a.description,quantity:a.quantity,unit_price:a.unit_price,vat_rate:a.vat_rate,sort_order:r}))),y(!0)}}),e.jsx(vt,{open:jr,onOpenChange:ys,children:e.jsxs(bt,{className:"max-w-sm",children:[e.jsx(Nt,{children:e.jsx(wt,{children:"Renovar validade da proposta"})}),e.jsx("div",{className:"space-y-4 py-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(me,{children:"Nova data de validade"}),e.jsx(kt,{type:"date",value:ks,onChange:t=>xa(t.target.value),min:Re(new Date,"yyyy-MM-dd")})]})}),e.jsxs(Vt,{children:[e.jsx(g,{variant:"outline",onClick:()=>ys(!1),children:"Cancelar"}),e.jsx(g,{onClick:Gr,disabled:!ks,children:"Renovar"})]})]})})]}):e.jsx(Ms,{children:e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold",children:R("proposals.title")}),e.jsx("p",{className:"text-muted-foreground",children:R("proposals.subtitle")})]}
10),e.jsx(On,{inline:!0})]})})};export{Dd 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.