1var as=Object.defineProperty;var ts=(t,r,s)=>r in t?as(t,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[r]=s;var Gt=(t,r,s)=>ts(t,typeof r!="symbol"?r+"":r,s);import{p as mt,s as v,r as _,f as ue,c as a,C as K,j as e,q as _e,i as te,k as ne,m as ee,o as ae,l as Se,F as Ee,L as ba,B as j,w as Wa,X as rs,g as ss,D as et,M as Ja,N as ns,az as Ka,n as os,e as is,bv as ls,ag as Ht,ah as Xt,ai as Yt}from"./main-WBJUeER2.js";import{f as Mt,g as La,a as Wt,E as cs,b as ds,c as ms,d as ut,e as us,l as Ot,r as ps,s as Nr,h as Qt,i as _r,j as Rt,k as wt,m as Jt,D as gs,n as hs,p as bs,o as wr,q as Kt,t as fs,u as xs}from"./prolaboreService-nvwhwi11.js";import{T as pt,a as gt,b as qe,c as Je}from"./tabs-CTFLd9G7.js";import{a as Ze,n as ra,g as Va,p as tt,j as Zt,c as er,e as vs,f as ar}from"./dateHelpers-CRc8Egvw.js";import{M as rt}from"./mini-day-picker-Croq5Z1S.js";import{a as wa,c as ys,b as Ua}from"./activeCashConsolidation-DF_oC1jf.js";import{_ as Ct}from"./preload-helper-BxaVoaJg.js";import{T as Oe}from"./trending-up-C2EwRYQE.js";import{T as Qa}from"./trending-down-eskoO55j.js";import{M as Cr}from"./minus-DY7nr7OH.js";import{P as Ia}from"./progress-CWoKheZ7.js";import{T as pa}from"./target-B9HivrzC.js";import{D as aa}from"./dollar-sign-D1d4GDdf.js";import{C as sa}from"./clock-DYPZOXy_.js";import{W as ea}from"./wallet-Svw1gt7W.js";import{R as ta}from"./receipt-CjwKu_BF.js";import{A as ma}from"./activity-BlJDpNDg.js";import{T as na}from"./triangle-alert-iAXFxMAH.js";import{C as $e}from"./circle-check-Bs368NmB.js";import{S as He}from"./separator-BV0J_WOH.js";import{C as je}from"./calendar-BWGSt_Dz.js";import{D as Ea,a as Sa,b as Pa,c as Ma,d as Oa,e as Tt,f as kr}from"./dialog-DFpN7EMj.js";import{I as Ce}from"./input-BLqqkK6e.js";import{L as be}from"./label-NWWEjw9U.js";import{C as st}from"./checkbox-DpZo8Eqm.js";import{A as Fe,a as Ie,b as Ar}from"./alert-Cw7JezC-.js";import{f as ve}from"./financial-D6w2HscO.js";import{C as Ga}from"./calculator-DHmU1d6N.js";import{U as Aa}from"./users-BRCZEtHr.js";import{I as Dt}from"./info-ipT0AR-D.js";import{T as ya}from"./trash-2-CEhUq0QO.js";import{P as ga}from"./plus-B6bc_aKB.js";import{P as va}from"./package-CUE12fwk.js";import{S as oa}from"./sparkles-DBPQUSvz.js";import{f as de}from"./format-D2ynJLjf.js";import{s as tr,a as rr,g as sr}from"./calendar-CpL5Inpa.js";import{C as Me}from"./circle-alert-Dh-W21ab.js";import{C as nt}from"./circle-check-big-C3kE59lj.js";import{R as ha}from"./refresh-cw-CeOM8if5.js";import{C as Ns}from"./chevron-up-fth9-Z__.js";import{C as _s}from"./chevron-down-CYA6Q4p2.js";import{F as da}from"./file-text-DgROvEGV.js";import{A as Er}from"./arrow-right-bcEzTZCt.js";import{a as Ha}from"./addMonths-BzMa7IYj.js";import{B as ot}from"./building-2-Ba__4qN_.js";import{S as $t}from"./square-pen-DBsZYRDq.js";import{d as ws}from"./differenceInDays-D6erbRd8.js";import{S as Ve,a as Le,b as Be,c as ze,d as fe}from"./select-1uZFFbj6.js";import{T as Cs}from"./textarea-BRSFpt35.js";import{S as Sr}from"./scroll-area-MetunAe7.js";import{L as ht}from"./landmark-_bYkDRz8.js";import{C as Ba}from"./credit-card-PS7N63_K.js";import{U as qt}from"./upload-BtDroln0.js";import{A as bt,a as ft,b as xt,c as vt,d as yt,e as Nt,f as _t,g as Ta}from"./alert-dialog-CCXu3Uc5.js";import{P as Pr}from"./pen-line-Bfjlr5PS.js";import{t as ks}from"./en-US-UHYFB6YK.js";import{p as Fa}from"./pt-BR-BWLuK4Ds.js";import{s as qa}from"./startOfMonth-CsPoWCyv.js";import{T as Vt,a as Lt,b as _a,c as We,d as Bt,e as De}from"./table-Zl2zer5o.js";import{e as Xa}from"./endOfMonth-C5ZYEg4f.js";import{p as As}from"./parseISO-CMVrCGvT.js";import{L as Mr}from"./layout-grid-CNYQ4ru_.js";import{L as Rr}from"./list-BsHCIGNe.js";import{H as za}from"./house-uCduJntS.js";import{Z as zt}from"./zap-BVZ3oraD.js";import{D as Es}from"./droplets-Bf0HrMip.js";import{W as Dr}from"./wifi-BquYSnff.js";import{P as $r}from"./phone-DKPgU-KA.js";import{W as it}from"./wrench-DTI7vE6d.js";import{M as Ss}from"./megaphone-ClhL43LF.js";import{T as Fr}from"./truck-CgZxZLkk.js";import{R as Ps}from"./repeat-Cb2UNDIi.js";import{S as Ir}from"./shield-DRUKsB5S.js";import{U as at}from"./user-9-XaRHL8.js";import{P as Ms}from"./PaymentDialog-CqxiAuCK.js";import{C as Ca}from"./chart-column-LAGQ_Df0.js";import{L as ca}from"./lightbulb-Dl4czG_P.js";import{C as Rs}from"./chevron-left-DKStOSjC.js";import{C as Ds}from"./chevron-right-ViuRtoQB.js";import{C as $s}from"./calendar-days-CF0FFBoQ.js";import{T as Fs}from"./tag-CW6jNZLY.js";import{U as nr}from"./undo-2-DBpKWigI.js";import{F as or}from"./file-down-JBgHAT8s.js";import{s as Is}from"./subMonths-CgbjkLyX.js";import{c as ir}from"./aiGateway-D4Qm1uAA.js";import{p as Or}from"./pdfmake-C7qk6TXX.js";import{a as kt}from"./vfs_fonts-0v8Cj4P1.js";import{B as $a}from"./brain-drzuD21G.js";import{H as Os}from"./history-no24q07d.js";import{M as Ts}from"./index-BYmCn_Hx.js";import{M as Ft}from"./message-square-CVe96gLi.js";import{S as qs}from"./send-D_cDWd4G.js";import{a as lr,A as Vs}from"./arrow-up-right-OYM3HMK7.js";import{C as jt}from"./circle-x-DHP392-i.js";import{P as Tr}from"./pencil-DiWWu1pX.js";import{S as qr}from"./save-YA7hjpUh.js";import{B as lt}from"./bot-BhiklI8m.js";import{B as cr}from"./briefcase-DMp0pphc.js";import{S as dr}from"./shopping-cart-DPjTyRTn.js";import{L as Ls}
1from"./layers-BaxXttNk.js";import{V as At}from"./video-C5C8l84s.js";import{F as Bs}from"./film--dGRseRn.js";import{S as zs}from"./smartphone-ChaWo3lN.js";import{S as js}from"./scissors-DHbTBzHc.js";import{C as mr}from"./camera-CB1sD47Z.js";import{I as ur}from"./image-Dd8sFZjf.js";import{M as Us}from"./mail-jFql7U1f.js";import{C as Gs}from"./cloud-R7_O-BVv.js";import{C as Hs}from"./clipboard-list-BLK0WHx6.js";import{S as Xs}from"./shopping-bag-DcHcuq2_.js";import{S as Ys}from"./star-CAOGK4VZ.js";import{T as Ws}from"./timer-DwOjeRP1.js";import{S as Qs}from"./scale-8pg6DzPf.js";import{D as Js}from"./droplet-3DXGule8.js";import{S as Ks,a as Zs,b as en,c as an,d as tn}from"./sheet-DSDa1DfJ.js";import{C as Vr}from"./circle-help-BhzJ25xg.js";import{D as rn}from"./database-Jtm7flby.js";import{E as sn}from"./external-link-Di9hIVup.js";import{S as nn,r as pr,C as on,a as ln,b as cn,g as dn,m as mn,s as un,d as gr}from"./bankPaymentRoutingService-Dkyx18Cz.js";import{A as pn}from"./arrow-right-left-CEHNr43Y.js";import{E as Lr}from"./eye-DrEQbBLD.js";import{E as Br}from"./eye-off-C4T-tUEa.js";import{r as gn,u as hn}from"./xlsx-CKN5doRT.js";import{S as bn}from"./smile-BcFSB4K3.js";import{G as fn}from"./graduation-cap-BxzdmTtS.js";import{U as Na}from"./UpgradePrompt-BKCkHV_2.js";import{u as xn}from"./useLicense-B-OanmIu.js";import"./index-C6omAwXH.js";import"./index-DbXx9bUk.js";import"./popover-ykZrxRaU.js";import"./index-Dab39HQC.js";import"./index-Dmb49cMn.js";import"./index-D9LsUG_D.js";import"./check-C9VL1YF8.js";import"./differenceInCalendarMonths-CVxHxMVA.js";import"./endOfWeek-DqrjwSA5.js";import"./index-BdQq_4o_.js";import"./use-payment-methods-DPWA4M3C.js";import"./switch-DICV0CzG.js";import"./message-circle-W-ylwqB8.js";import"./ticket-DTeI-PC4.js";import"./crown-Zf2rVwBq.js";import"./LicenseService-BMWotS9y.js";import"./funnelTelemetry-pOivtfZb.js";/** 2 * @license lucide-react v0.462.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const Ke=mt("HandCoins",[["path",{d:"M11 15h2a2 2 0 1 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 17",key:"geh8rc"}],["path",{d:"m7 21 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a2 2 0 0 0-2.75-2.91l-4.2 3.9",key:"1fto5m"}],["path",{d:"m2 16 6 6",key:"1pfhp9"}],["circle",{cx:"16",cy:"9",r:"2.9",key:"1n0dlu"}],["circle",{cx:"6",cy:"5",r:"3",key:"151irh"}]]);/** 7 * @license lucide-react v0.462.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const vn=mt("Library",[["path",{d:"m16 6 4 14",key:"ji33uf"}],["path",{d:"M12 6v14",key:"1n7gus"}],["path",{d:"M8 8v12",key:"1gg7y9"}],["path",{d:"M4 4v16",key:"6qkkli"}]]);/** 12 * @license lucide-react v0.462.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const yn=mt("ListChecks",[["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/** 17 * @license lucide-react v0.462.0 - ISC 18 * 19 * This source code is licensed under the ISC license. 20 * See the LICENSE file in the root directory of this source tree. 21 */const Nn=mt("Music2",[["circle",{cx:"8",cy:"18",r:"4",key:"1fc0mg"}],["path",{d:"M12 18V2l7 4",key:"g04rme"}]]);function zr(t){return ks(t).getDay()}async function _n(){const{data:t,error:r}=await v.from("variable_cost_config").select("tax_percentage").order("updated_at",{ascending:!1}).limit(1).maybeSingle();if(r||(t==null?void 0:t.tax_percentage)==null)return null;const s=Number(t.tax_percentage);return Number.isFinite(s)&&s>=0?s:null}async function wn(){const{data:t,error:r}=await v.from("settings").select("company_type, annual_revenue_range, document_type").limit(1).maybeSingle();if(r||!t)return 6;const s=t.company_type||"mei",n=t.annual_revenue_range||"ate_180k";return s==="mei"||t.document_type==="cpf"?0:s==="simples_comercio"?{ate_180k:4,ate_360k:5.47,ate_720k:6.84,ate_1800k:7.54,ate_3600k:7.6,ate_4800k:8.28,acima_4800k:13.33}[n]??6:s==="simples_industria"?{ate_180k:4.5,ate_360k:5.97,ate_720k:7.34,ate_1800k:8.04,ate_3600k:8.1,ate_4800k:8.78,acima_4800k:13.33}[n]??6.5:s==="simples_servicos"?{ate_180k:6,ate_360k:8.21,ate_720k:10.26,ate_1800k:11.31,ate_3600k:11.4,ate_4800k:12.42,acima_4800k:16.33}[n]??8:s==="lucro_presumido"?13.33:s==="lucro_real"?25:6}async function Cn(){const t=await _n();if(t!==null)return{ratePercent:t,source:"manual_config",label:`Configurado em Ponto de EquilÃbrio (${t.toFixed(2)}%)`};const r=await wn();
21return{ratePercent:r,source:"company_settings",label:`Estimativa pelo tipo de empresa em Configurações (${r.toFixed(2)}%)`}}class kn{async generateDRE(r){const{data:{user:s}}=await v.auth.getUser();if(!s)throw new Error("Usuário não autenticado");const[n,o,m,u,i,d]=await Promise.all([this.fetchSalesData(s.id,r),this.fetchOrderItemsProfitData(s.id,r),Mt(s.id,r),this.fetchFixedCosts(s.id),this.fetchProlabore(s.id),Cn()]);return this.calculateDRE(n,o,m,u,i,r,d)}async fetchSalesData(r,s){const n=s.startDate.toISOString(),o=s.endDate.toISOString(),{data:m,error:u}=await wa(v.from("sales").select(` 22 id, 23 total_amount, 24 subtotal, 25 payment_method, 26 created_at, 27 deleted_at, 28 sale_items ( 29 id, 30 quantity, 31 unit_price, 32 subtotal, 33 products ( 34 id, 35 name, 36 material_cost, 37 other_costs, 38 labor_cost, 39 depreciation_cost 40 ) 41 ) 42 `).eq("user_id",r).gte("created_at",n).lte("created_at",o));if(u)throw new Error(`Erro ao buscar vendas: ${u.message}`);return m||[]}async fetchOrderItemsProfitData(r,s){const n=s.startDate.toISOString(),o=s.endDate.toISOString(),{data:m,error:u}=await v.from("order_items").select(` 43 quantity, 44 unit_price, 45 unit_cost, 46 marketplace_fee, 47 order:orders!inner( 48 created_at, 49 user_id, 50 cancelled_at 51 ) 52 `).eq("order.user_id",r).is("order.cancelled_at",null).gte("order.created_at",n).lte("order.created_at",o);return u?(console.warn("â ï¸ Não foi possÃvel buscar order_items (custos reais):",u),[]):m||[]}async fetchFixedCosts(r){const{data:s,error:n}=await v.from("fixed_costs").select("*").eq("user_id",r).eq("is_active",!0);return n?(console.warn("Tabela fixed_costs não encontrada ou erro:",n),[]):s||[]}async fetchProlabore(r){const{data:s,error:n}=await v.from("prolabore_partners").select("*").eq("user_id",r).eq("active",!0);return n?(console.warn("Tabela prolabore_partners não encontrada ou erro:",n),[]):s||[]}calculateDRE(r,s,n,o,m,u,i){const d=r.reduce((D,re)=>D+Number(re.subtotal||0),0),g=(s||[]).reduce((D,re)=>D+Number(re.quantity||0)*Number(re.marketplace_fee||0),0),x=i.ratePercent/100,y=d*x,M=0,E=0,h={impostos:y,taxasMarketplace:g,devolucoes:M,descontos:E,total:y+g+M+E},c=d-h.total,b=Array.isArray(s)&&s.length>0;let N=0,C=0,A=0,f=0;b&&(f=(s||[]).reduce((D,re)=>D+Number(re.quantity||0)*Number(re.unit_cost||0),0)),b||r.forEach(D=>{var re;(re=D.sale_items)==null||re.forEach(k=>{const ke=k.products;if(ke){const Q=Number(k.quantity||0);N+=(Number(ke.material_cost||0)+Number(ke.other_costs||0))*Q,C+=Number(ke.labor_cost||0)*Q,A+=Number(ke.depreciation_cost||0)*Q}})});const $={materiaPrima:N,maoDeObraDireta:C,custosProducaoDiretos:A,total:b?f:N+C+A},S=c-$.total,Z=c>0?S/c*100:0;let z=0,X=0,me=0;n.forEach(D=>{const re=D.expense_category,k=La(D);switch(Wt(re).dreCategory){case"SALES":z+=k;break;case"ADMINISTRATIVE":X+=k;break;case"OPERATIONAL":me+=k;break}}),o.forEach(D=>{me+=Number(D.amount||0)}),m.forEach(D=>{const re=Number(D.amount||0);let k=re;D.frequency==="weekly"&&(k=re*4.33),D.frequency==="biweekly"&&(k=re*2),X+=k});const we={despesasVendas:z,despesasAdministrativas:X,despesasGerais:me,total:z+X+me},Y=S-we.total,P=c>0?Y/c*100:0;let w=0,O=0,H=0;n.forEach(D=>{const re=D.expense_category,k=La(D);Wt(re).dreCategory==="FINANCIAL"&&(O+=k)});const I={juros:w,taxasBancarias:O,outrasFinanceiras:H,total:w+O+H},U=0,se=Y-I.total+U;let le=0;n.forEach(D=>{const re=D.expense_category,k=La(D);re==="taxes"&&(le+=k)});const ce=se-le,R=c>0?ce/c*100:0,pe=$.custosProducaoDiretos,F=Y+pe+0,W=c>0?F/c*100:0;return{period:{startDate:u.startDate.toISOString(),endDate:u.endDate.toISOString()},receitaBruta:d,deducoes:h,receitaLiquida:c,cmv:$,lucroBruto:S,margemBruta:Z,despesasOperacionais:we,ebit:Y,margemEBIT:P,despesasFinanceiras:I,receitasFinanceiras:U,ebt:se,impostosLucro:le,lucroLiquido:ce,margemLiquida:R,ebitda:F,margemEBITDA:W,meta:{regime:"competencia",salesTaxRatePercent:i.ratePercent,salesTaxSource:i.source,salesTaxLabel:i.label}}}async getSalesDetail(r){const{data:{user:s}}=await v.auth.getUser();if(!s)throw new Error("Usuário não autenticado");const n=await this.fetchSalesData(s.id,r),o=n.reduce((d,g)=>d+Number(g.subtotal||0),0),m=n.length,u=m>0?o/m:0,i={cash:0,pix:0,debitCard:0,creditCard:0,customerAccount:0};
52return n.forEach(d=>{const g=Number(d.subtotal||0),x=d.payment_method;x==="cash"?i.cash+=g:x==="pix"?i.pix+=g:x==="debit_card"?i.debitCard+=g:x==="credit_card"?i.creditCard+=g:x==="customer_account"&&(i.customerAccount+=g)}),{totalSales:o,salesCount:m,averageTicket:u,cancelledSales:0,cancelledAmount:0,byPaymentMethod:i}}async getCMVDetail(r){const{data:{user:s}}=await v.auth.getUser();if(!s)throw new Error("Usuário não autenticado");const n=await this.fetchSalesData(s.id,r);let o=0,m=0,u=0,i=0,d=0,g=0;n.forEach(y=>{var M;(M=y.sale_items)==null||M.forEach(E=>{const h=E.products;if(h){const c=Number(E.quantity||0);m+=(Number(h.material_cost||0)+Number(h.other_costs||0))*c,u+=Number(h.labor_cost||0)*c,d+=Number(h.depreciation_cost||0)*c,g++}})}),o=m+u+i+d;const x=g>0?o/g:0;return{totalCMV:o,materiaPrima:m,maoDeObra:u,custosIndiretos:i,depreciacao:d,productsCount:g,averageCMVPerProduct:x}}}const ja=new kn;class jr{async analyzeCosts(r){const{data:{user:s}}=await v.auth.getUser();if(!s)throw new Error("Usuário não autenticado");const o=(await Mt(s.id,r)).map(M=>{const E=this.classifyCost(M);return E.amount=La(M),E}),m=o.reduce((M,E)=>M+E.amount,0),u=o.filter(M=>M.paid).reduce((M,E)=>M+E.amount,0),i=m-u,d=this.analyzeByVariability(o),g=this.analyzeByTraceability(o),x=this.analyzeByDRECategory(o),y=this.getTopCategories(o);return{totalCosts:m,totalPaidCosts:u,totalUnpaidCosts:i,byVariability:d,byTraceability:g,byDRECategory:x,topCategories:y}}classifyCost(r){const s=r.expense_category||"DIVERSOS",n=cs[s];return n?{id:r.id,description:r.description,amount:Number(r.amount||0),category:s,variability:n.variability,traceability:n.traceability,dreCategory:n.dreCategory,dueDate:r.due_date,paid:r.paid||!1,paidAt:r.paid_at}:{id:r.id,description:r.description,amount:Number(r.amount||0),category:s,variability:"FIXED",traceability:"INDIRECT",dreCategory:"OPERATIONAL",dueDate:r.due_date,paid:r.paid||!1,paidAt:r.paid_at}}async getRealVariableCosts(r){const{data:{user:s}}=await v.auth.getUser();if(!s)throw new Error("Usuário não autenticado");const{data:n,error:o}=await v.from("order_items").select(` 53 quantity, 54 unit_price, 55 unit_cost, 56 gross_profit, 57 net_profit, 58 order:orders!inner( 59 created_at, 60 user_id, 61 cancelled_at 62 ) 63 `).eq("order.user_id",s.id).is("order.cancelled_at",null).gte("order.created_at",r.startDate.toISOString()).lte("order.created_at",r.endDate.toISOString());if(o)return console.error("Erro ao buscar order_items:",o),{totalVariableCosts:0,totalRevenue:0,realContributionMargin:0,realContributionMarginPercent:0,itemsCount:0,unitsCount:0};const m=(n==null?void 0:n.length)||0,u=(n==null?void 0:n.reduce((y,M)=>y+Number(M.quantity||0),0))||0,i=(n==null?void 0:n.reduce((y,M)=>y+Number(M.quantity||0)*Number(M.unit_price||0),0))||0,d=(n==null?void 0:n.reduce((y,M)=>y+Number(M.quantity||0)*Number(M.unit_cost||0),0))||0,g=i-d,x=i>0?g/i*100:0;return{totalVariableCosts:d,totalRevenue:i,realContributionMargin:g,realContributionMarginPercent:x,itemsCount:m,unitsCount:u}}analyzeByVariability(r){const s=r.filter(i=>i.variability==="FIXED"),n=r.filter(i=>i.variability==="VARIABLE"),o=s.reduce((i,d)=>i+d.amount,0),m=n.reduce((i,d)=>i+d.amount,0),u=o+m;return{fixed:s,variable:n,totalFixed:o,totalVariable:m,fixedPercentage:u>0?o/u*100:0,variablePercentage:u>0?m/u*100:0}}analyzeByTraceability(r){const s=r.filter(i=>i.traceability==="DIRECT"),n=r.filter(i=>i.traceability==="INDIRECT"),o=s.reduce((i,d)=>i+d.amount,0),m=n.reduce((i,d)=>i+d.amount,0),u=o+m;return{direct:s,indirect:n,totalDirect:o,totalIndirect:m,directPercentage:u>0?o/u*100:0,indirectPercentage:u>0?m/u*100:0}}analyzeByDRECategory(r){const s=r.filter(i=>i.dreCategory==="CMV"),n=r.filter(i=>i.dreCategory==="OPERATIONAL"),o=r.filter(i=>i.dreCategory==="ADMINISTRATIVE"),m=r.filter(i=>i.dreCategory==="SALES"),u=r.filter(i=>i.dreCategory==="FINANCIAL");return{cmv:{costs:s,total:s.reduce((i,d)=>i+d.amount,0)},operational:{costs:n,total:n.reduce((i,d)=>i+d.amount,0)},administrative:{costs:o,total:o.reduce((i,d)=>i+d.amount,0)},sales:{costs:m,total:m.reduce((i,d)=>i+d.amount,0)},financial:{costs:u,total:u.reduce((i,d)=>i+d.amount,0)}}}getTopCategories(r){const s=r.reduce((o,m)=>(o[m.category]||(o[m.category]={amount:0,count:0}),o[m.category].amount+=m.amount,o[m.category].count++,o),{}),n=Object.values(s).reduce((o,m)=>o+m.amount,0);return Object.entries(s).map(([o,m])=>({category:o,amount:m.amount,percentage:n>0?m.amount/n*100:0,count:m.count})).sort((o,m)=>m.amount-o.amount).slice(0,5)}async separateCostsByVariability(r){const{data:{user:s}}=await v.auth.getUser();if(!s)throw new Error("Usuário não autenticado");const o=(await Mt(s.id,r)).map(x=>{const y=this.classifyCost(x);return y.amount=La(x),y}),m=o.filter(x=>x.variability==="FIXED"),u=m.reduce((x,y)=>x+y.amount,0),i=await this.getRealVariableCosts(r);let d=i.totalVariableCosts,g=o.filter(x=>x.variability==="VARIABLE");return i.itemsCount===0?d=g.reduce((x,y)=>x+y.amount,0):g=[],{fixed:m,variable:g,totalFixed:u,totalVariable:d,realData:i.itemsCount>0?{revenue:i.totalRevenue,contributionMargin:i.realContributionMargin,contributionMarginPercent:i.realContributionMarginPercent,itemsCount:i.itemsCount,unitsCount:i.unitsCount}:null}}}const Ur=new jr,Et=Object.freeze(Object.defineProperty({__proto__:null,CostService:jr,costService:Ur},Symbol.toStringTag,{value:"Module"}));class An{async calculateMargins(r){const s=await ja.generateDRE(r),n=(o,m,u)=>o>=m?"excellent":o>=u?"good":"critical";return{period:{startDate:r.startDate.toISOString(),endDate:r.endDate.toISOString()},revenue:s.receitaLiquida,gross:{value:s.lucroBruto,percentage:s.margemBruta,benchmark:n(s.margemBruta,40,30),revenue:s.receitaLiquida,cmv:s.cmv.total},contribution:{value:await this.calculateContributionMarginValue(r),percentage:await this.calculateContributionMarginPercentage(r),benchmark:await this.getContributionBenchmark(r),revenue:s.receitaLiquida,variableCosts:await this.getTotalVariableCosts(r)},ebit:{value:s.ebit,percentage:s.margemEBIT,benchmark:n(s.margemEBIT,20,10),revenue:s.receitaLiquida,cmv:s.cmv.total,operationalExpenses:s.despesasOperacionais.total},ebitda:{value:s.ebitda,percentage:s.margemEBITDA,benchmark:n(s.margemEBITDA,25,15),ebit:s.ebit,depreciation:s.cmv.custosProducaoDiretos,amortization:0},net:{value:s.lucroLiquido,percentage:s.margemLiquida,benchmark:n(s.margemLiquida,15,10),revenue:s.receitaLiquida,netProfit:s.lucroLiquido}}}async calculateContributionMarginValue(r){const{costService:s}=await Ct(async()=>{const{costService:d}=await Promise.resolve().then(()=>Et);return{costService:d}},void 0),n=await s.getRealVariableCosts({startDate:r.startDate,endD
63ate:r.endDate});if(n.itemsCount>0)return n.realContributionMargin;const{data:{user:o}}=await v.auth.getUser();if(!o)throw new Error("Usuário não autenticado");const{data:m}=await ys(v.from("orders").select("total_amount").eq("user_id",o.id).gte("created_at",r.startDate.toISOString()).lte("created_at",r.endDate.toISOString())),u=(m||[]).reduce((d,g)=>d+Number(g.total_amount||0),0),i=await this.getTotalVariableCosts(r);return u-i}async calculateContributionMarginPercentage(r){const{costService:s}=await Ct(async()=>{const{costService:d}=await Promise.resolve().then(()=>Et);return{costService:d}},void 0),n=await s.getRealVariableCosts({startDate:r.startDate,endDate:r.endDate});if(n.itemsCount>0&&n.totalRevenue>0)return n.realContributionMarginPercent;const{data:{user:o}}=await v.auth.getUser();if(!o)throw new Error("Usuário não autenticado");const{data:m}=await wa(v.from("sales").select("subtotal").eq("user_id",o.id).gte("created_at",r.startDate.toISOString()).lte("created_at",r.endDate.toISOString())),u=(m||[]).reduce((d,g)=>d+Number(g.subtotal||0),0),i=await this.calculateContributionMarginValue(r);return u>0?i/u*100:0}async getTotalVariableCosts(r){const{costService:s}=await Ct(async()=>{const{costService:o}=await Promise.resolve().then(()=>Et);return{costService:o}},void 0);return(await s.analyzeCosts(r)).byVariability.totalVariable}async getContributionBenchmark(r){const s=await this.calculateContributionMarginPercentage(r);return s>=50?"excellent":s>=35?"good":"critical"}}const Gr=new An;class En{async analyzeDemandProducts(r=30,s=7){try{const{data:{user:n}}=await v.auth.getUser();if(!n)throw new Error("Usuário não autenticado");const{data:o,error:m}=await v.from("products").select("id, name, material_cost, labor_cost, other_costs, stock_control_enabled").eq("user_id",n.id).eq("stock_control_enabled",!1);if(m)throw m;if(!o||o.length===0)return{totalProducts:0,totalAverageDailySales:0,totalSuggestedInventoryValue:0,products:[],workingCapitalNeeded:0};const u=new Date;u.setDate(u.getDate()-r);const i=[];for(const y of o){const{data:M,error:E}=await v.from("sale_items").select(` 64 quantity, 65 sales!inner( 66 created_at, 67 user_id 68 ) 69 `).eq("product_id",y.id).eq("sales.user_id",n.id).gte("sales.created_at",u.toISOString());if(E){console.error(`Erro ao buscar vendas do produto ${y.name}:`,E);continue}const h=(M||[]).reduce((Z,z)=>Z+Number(z.quantity||0),0);if(h===0)continue;const c=h/r,b=c*7,N=Number(y.material_cost||0),C=Number(y.labor_cost||0),A=Number(y.other_costs||0),f=N+C+A,$=c*s,S=$*N;i.push({productId:y.id,productName:y.name,totalSold30Days:h,avgDailySales:c,avgWeeklySales:b,materialCostPerUnit:N,laborCostPerUnit:C,otherCostsPerUnit:A,totalCostPerUnit:f,suggestedInventoryDays:s,suggestedInventoryQuantity:$,suggestedInventoryValue:S})}const d=i.reduce((y,M)=>y+M.avgDailySales,0),g=i.reduce((y,M)=>y+M.suggestedInventoryValue,0),x=g;return{totalProducts:i.length,totalAverageDailySales:d,totalSuggestedInventoryValue:g,products:i.sort((y,M)=>M.suggestedInventoryValue-y.suggestedInventoryValue),workingCapitalNeeded:x}}catch(n){throw console.error("Erro ao analisar produtos sob demanda:",n),n}}async getTotalInventoryValue(){try{const{data:{user:r}}=await v.auth.getUser();if(!r)throw new Error("Usuário não autenticado");const{data:s}=await v.from("products").select("stock_quantity, material_cost, stock_control_enabled").eq("user_id",r.id).eq("stock_control_enabled",!0),n=(s||[]).reduce((u,i)=>{const d=Number(i.stock_quantity||0),g=Number(i.material_cost||0);return u+d*g},0),m=(await this.analyzeDemandProducts(30,7)).totalSuggestedInventoryValue;return{physicalInventory:n,demandInventory:m,total:n+m}}catch(r){return console.error("Erro ao calcular valor total de estoque:",r),{physicalInventory:0,demandInventory:0,total:0}}}async getTopCapitalConsumers(){return(await this.analyzeDemandProducts(30,7)).products.slice(0,5)}}const Sn=new En;var ua=(t=>(t[t.IMMEDIATE=30]="IMMEDIATE",t[t.SHORT_TERM=90]="SHORT_TERM",t[t.MEDIUM_TERM=365]="MEDIUM_TERM",t[t.LONG_TERM=0]="LONG_TERM",t))(ua||{});const Pn={30:"Mês Corrente (30 dias)",90:"Curto Prazo (90 dias)",365:"Médio Prazo (1 ano)",0:"Visão Geral (Total)"},Mn={30:"Contas que vencem este mês - liquidez imediata",90:"Próximos 3 meses - capital de giro operacional",365:"Próximo ano - planejamento de médio prazo",0:"Todas as obrigações - endividamento total"},Rn={currentLiquidityExcellent:2,currentLiquidityGood:1.5,grossMarginExcellent:40,grossMarginGood:30,netMarginExcellent:15,netMarginGood:10,roiExcellent:25,roiGood:15,receivingPeriodExcellent:15,receivingPeriodGood:30,financialCycleExcellent:0,financialCycleGood:30};class Dn{constructor(r){Gt(this,"benchmarks");this.benchmarks={...Rn,...r}}async calculateIndicators(r){const{data:{user:s}}=await v.auth.getUser();if(!s)throw new Error("Usuário não autenticado");const n=await ja.generateDRE(r),[o,m,u,i,d]=await Promise.all([this.calculateLiquidityIndicators(s.id),this.calculateProfitabilityIndicators(n),this.calculateDebtIndicators(s.id),this.calculateActivityIndicators(s.id,r),this.calculateWorkingCapital(s.id)]),g=this.calculateHealthScore(o,m,u,i,d);return{period:{startDate:r.startDate.toISOString(),endDate:r.endDate.toISOString()},liquidity:o,profitability:m,debt:u,activity:i,workingCapital:d,healthScore:g,meta:{regime:"competencia",dreAligned:!0}}}async calculateIndicatorsByHorizon(r,s){const{data:{user:n}}=await v.auth.getUser();if(!n)throw new Error("Usuário não autenticado");const o=await ja.generateDRE(r),m=await this.calculateLiquidityIndicatorsByHorizon(n.id,s),[u,i,d,g]=await Promise.all([this.calculateProfitabilityIndicators(o),this.calculateDebtIndicatorsByHorizon(n.id,s),this.calculateActivityIndicators(n.id,r),this.calculateWorkingCapitalByHorizon(n.id,s)]),x=this.calculateHealthScore(m,u,i,d,g);return{period:{startDate:r.startDate.toISOString(),endDate:r.endDate.toISOString()},liquidity:m,profitability:u,debt:i,activity:d,workingCapital:g,healthScore:x,meta:{regime:"competencia",dreAligned:!0}}}async analyzeByHorizons(){const{data:{user:r}}=await v.auth.getUser();if(!r)throw new Error("Usuário não autenticado");const s=await this.getAvailableCash(r.id),n=await this.getAccountsReceivable(r.id),o=await this.getInventoryValue(r.id),m=s+n+o,u=[ua.IMMEDIATE,ua.SHORT_TERM,ua.MEDIUM_TERM,ua.LONG_TERM],i=[];for(const d of u){const g=await this.getCurrentLiabilities(r.id,d),x=g,y=m-x,M=x>0?m/x:0;let E,h;y>0&&M>=1.5?(E="excellent",h=` Situação excelente! Você tem R$ ${y.toFixed(2)} de capital disponÃvel e liquidez de ${M.toFixed(2)}x.`):y>0&&M>=1?(E="good",h=` Situação boa. Capital disponÃvel: R$ ${y.toFixed(2)}. Consegue pagar as contas do perÃodo.`):y<0&&Math.abs(y)<s?(E="attention",h=` Atenção. Faltam R$ ${Math.abs(y).toFixed(2)}, mas você tem dinheiro em caixa (R$ ${s.toFixed(2)}) para cobrir.`):(E="critical",h=` Situação crÃtica. Faltam R$ ${Math.abs(y).toFixed(2)} para cobrir as obrigações deste perÃodo.`),i.push({horizon:d,label:Pn[d],description:Mn[d],disponivel:s,
69contasReceber:n,estoque:o,ativoCirculante:m,contasPagar:g,passivoCirculante:x,capitalDeGiro:y,liquidez:M,status:E,message:h})}return i}async calculateLiquidityIndicators(r){const s=await this.getAvailableCash(r),n=await this.getAccountsReceivable(r),o=await this.getInventoryValue(r),m=s+n+o,u=await this.getCurrentLiabilities(r),i=u>0?m/u:0,d=i>=this.benchmarks.currentLiquidityExcellent?"excellent":i>=this.benchmarks.currentLiquidityGood?"good":"critical",g=u>0?s/u:0,x=g>=1?"excellent":g>=.5?"good":"critical";return{currentLiquidity:i,currentLiquidityBenchmark:d,immediateLiquidity:g,immediateLiquidityBenchmark:x,ativoCirculante:m,passivoCirculante:u,disponivel:s,availableCash:s,accountsReceivable:n}}async calculateLiquidityIndicatorsByHorizon(r,s){const n=await this.getAvailableCash(r),o=await this.getAccountsReceivable(r),m=await this.getInventoryValue(r),u=n+o+m,i=await this.getCurrentLiabilities(r,s),d=i>0?u/i:0,g=d>=this.benchmarks.currentLiquidityExcellent?"excellent":d>=this.benchmarks.currentLiquidityGood?"good":"critical",x=i>0?n/i:0,y=x>=1?"excellent":x>=.5?"good":"critical";return{currentLiquidity:d,currentLiquidityBenchmark:g,immediateLiquidity:x,immediateLiquidityBenchmark:y,ativoCirculante:u,passivoCirculante:i,disponivel:n,availableCash:n,accountsReceivable:o}}calculateProfitabilityIndicators(r){const s=r.margemBruta,n=s>=this.benchmarks.grossMarginExcellent?"excellent":s>=this.benchmarks.grossMarginGood?"good":"critical",o=r.margemEBIT,m=o>=20?"excellent":o>=10?"good":"critical",u=r.margemLiquida,i=u>=this.benchmarks.netMarginExcellent?"excellent":u>=this.benchmarks.netMarginGood?"good":"critical",d=5e4,g=r.lucroLiquido/d*100,x=g>=this.benchmarks.roiExcellent?"excellent":g>=this.benchmarks.roiGood?"good":"critical";return{grossMargin:s,grossMarginBenchmark:n,operatingMargin:o,operatingMarginBenchmark:m,netMargin:u,netMarginBenchmark:i,roi:g,roiBenchmark:x,receita:r.receitaLiquida,cmv:r.cmv.total,lucroBruto:r.lucroBruto,ebit:r.ebit,lucroLiquido:r.lucroLiquido,investimentoTotal:d}}async calculateDebtIndicators(r){const s=await this.getCurrentLiabilities(r),n=s,o=await this.getAvailableCash(r),m=await this.getAccountsReceivable(r),u=await this.getInventoryValue(r),i=o+m+u,d=i>0?n/i*100:0,g=d<50?"excellent":d<=70?"good":"critical",x=n>0?s/n*100:0;return{debtRatio:d,debtRatioBenchmark:g,shortTermDebtRatio:x,passivoTotal:n,ativoTotal:i,passivoCirculante:s,totalDebt:n,shortTermPercent:x,longTermPercent:100-x}}async calculateDebtIndicatorsByHorizon(r,s){const n=await this.getCurrentLiabilities(r,s),o=n,m=await this.getAvailableCash(r),u=await this.getAccountsReceivable(r),i=await this.getInventoryValue(r),d=m+u+i,g=d>0?o/d*100:0,x=g<50?"excellent":g<=70?"good":"critical",y=o>0?n/o*100:0;return{debtRatio:g,debtRatioBenchmark:x,shortTermDebtRatio:y,passivoTotal:o,ativoTotal:d,passivoCirculante:n,totalDebt:o,shortTermPercent:y,longTermPercent:100-y}}async calculateActivityIndicators(r,s){const n=await this.getAccountsReceivable(r),o=await ds(r,s),m=await this.getCurrentLiabilities(r),{data:u}=await wa(v.from("sales").select("subtotal").eq("user_id",r).gte("created_at",s.startDate.toISOString()).lte("created_at",s.endDate.toISOString())),i=(u||[]).reduce((N,C)=>N+Number(C.subtotal||0),0),d=Math.ceil((s.endDate.getTime()-s.startDate.getTime())/(1e3*60*60*24)),g=d>0?i/d:0;let x=d>0?i*.6/d:0;try{const N=await ja.generateDRE(s);x=d>0?N.cmv.total/d:0}catch{}const y=g>0?n/g:0,M=y<=this.benchmarks.receivingPeriodExcellent?"excellent":y<=this.benchmarks.receivingPeriodGood?"good":"critical",E=x>0?o/x:0,h=E>=45?"excellent":E>=30?"good":"critical",c=y-E,b=c<=this.benchmarks.financialCycleExcellent?"excellent":c<=this.benchmarks.financialCycleGood?"good":"critical";return{averageReceivingPeriod:y,receivingPeriodBenchmark:M,averagePaymentPeriod:E,paymentPeriodBenchmark:h,financialCycle:c,financialCycleBenchmark:b,contasReceber:n,contasPagar:o,contasPagarAberto:m,receitaDiaria:g,cmvDiario:x}}async calculateWorkingCapital(r){const s=await this.getAvailableCash(r),n=await this.getAccountsReceivable(r),o=await this.getInventoryValue(r),m=s+n+o,u=await this.getCurrentLiabilities(r),i=u,d=m-i,g=n+o-u,x=d-g,y=u,M=y>0?d/y:0,E=M>=3?"excellent":M>=1?"good":"critical";return{amount:d,amountBenchmark:E,need:g,treasuryBalance:x,ativoCirculante:m,passivoCirculante:i,contasReceber:n,estoque:o,contasPagar:u,monthsOfOperation:M}}async calculateWorkingCapitalByHorizon(r,s){const n=await this.getAvailableCash(r),o=await this.getAccountsReceivable(r),m=await this.getInventoryValue(r),u=n+o+m,i=await this.getCurrentLiabilities(r,s),d=i,g=u-d,x=o+m-i,y=g-x,M=i,E=M>0?g/M:0,h=E>=3?"excellent":E>=1?"good":"critical";return{amount:g,amountBenchmark:h,need:x,treasuryBalance:y,ativoCirculante:u,passivoCirculante:d,contasReceber:o,estoque:m,contasPagar:i,monthsOfOperation:E}}calculateHealthScore(r,s,n,o,m){const u=this.calculateCategoryScore(r.currentLiquidityBenchmark,r.immediateLiquidityBenchmark),i=this.calculateCategoryScore(s.grossMarginBenchmark,s.netMarginBenchmark,s.roiBenchmark),d=this.calculateCategoryScore(n.debtRatioBenchmark),g=this.calculateCategoryScore(o.receivingPeriodBenchmark,o.financialCycleBenchmark),x=this.calculateCategoryScore(m.amountBenchmark),y=Math.round(u*.25+i*.3+d*.15+g*.15+x*.15),M=y>=80?"excellent":y>=60?"good":y>=40?"attention":"critical";return{overall:y,classification:M,liquidityScore:u,profitabilityScore:i,debtScore:d,activityScore:g,workingCapitalScore:x,score:y,recommendations:this.generateRecommendations(y,M,r,s,n,o,m)}}calculateCategoryScore(...r){const s=r.map(n=>n==="excellent"?100:n==="good"?70:30);return s.reduce((n,o)=>n+o,0)/s.length}generateRecommendations(r,s,n,o,m,u,i){const d=[];return n.currentLiquidityBenchmark==="critical"&&d.push(" Liquidez crÃtica: Priorize recebimentos e negocie prazos com fornecedores."),o.grossMarginBenchmark==="critical"&&d.push(" Margem bruta baixa: Revise precificação ou reduza custos de produção."),o.netMarginBenchmark==="critical"&&d.push(" Margem lÃquida baixa: Controle despesas operacionais."),m.debtRatioBenchmark==="critical"&&d.push(" Endividamento alto: Priorize quitação de dÃvidas."),u.receivingPeriodBenchmark==="critical"&&d.push(" PMR alto: Reduza prazos de recebimento ou antecipe recebÃveis."),i.amountBenchmark==="critical"&&d.push(" Capital de giro insuficiente: Busque linhas de crédito ou aporte de capital."),s==="excellent"&&d.push(" Excelente saúde financeira! Mantenha o foco e considere investir em crescimento."),d}async getAvailableCash(r){const{data:s}=await v.from("bank_accounts").select("current_balance").eq("user_id",r).eq("is_active",!0),n=(s||[]).reduce((i,d)=>i+Number(d.current_balance||0),0),{data:o}=await Ua(v.from("cash_register").select("type, amount").eq("user_id",r)),m=(o||[]).reduce((i,d)=>{const g=Number(d.amount||0);return d.type==="entry"?i+g:i-g},0);return n+m}async getAccountsReceivable(r){const{data:s}=await v.from("customers").select("balance").eq("user_id",r).lt("balance",0);return Math.abs((s||[]).reduce((o,m)=>o+Number(m.balance||0),0))}async getInventoryValue(r){return(await Sn.getTotalInventoryValue()).total}async getCurrentLiabilities(r,s=ua.SHORT_TERM){const{data:n,error:o}=await v.from("accounts_payable").select("amount, due_date, payment_date, description").eq("user_id",r).eq("paid",!1);if(o)return console.error(" Erro ao buscar contas a pagar:",o),0;let m=n||[];if(s===ua.IMMEDIATE){const i=new Date,d=new Date(i.getFullYear(),i.getMonth(),1),g=new Date(i.getFullYear(),i.getMonth()+1,0);g.setHours(23,59,59,999),m=m.filter(x=>{if(!x.due_date)return!1;const y=new Date(x.due_date);return y>=d&&y<=g}),`${String(i.getMonth()+1).padStart(2,"0")}${g.getDate()}${String(i.getMonth()+1).padStart(2,"0")}`}else if(s>0){const i=new Date,d=new Date;d.setDate(i.getDate()+s),d.setHours(23,59,59,999),m=m.filter(g=>g.due_date?new Date(g.due_date)<=d:!1),`${d.toISOString().split("T")[0]}`}return m.reduce((i,d)=>i+Number(d.amount||0),0)}}
69const hr=new Dn;class $n{async calculateBreakEven(r){const{data:{user:s}}=await v.auth.getUser();if(!s)throw new Error("Usuário não autenticado");const[n,o,m]=await Promise.all([Ur.separateCostsByVariability(r),Gr.calculateMargins(r),this.getSalesData(s.id,r)]),u=n.totalFixed,i=o.contribution.value/(m.unitsSold||1),d=o.contribution.percentage,g=m.totalRevenue/(m.unitsSold||1),x=g-i,y=d>0?u/(d/100):0,M=i>0?Math.ceil(u/i):0,E=y/22,h=Math.ceil(M/22),c=m.totalRevenue,b=m.unitsSold,N=c>0?Math.min(c/y*100,100):0,C=c>y*1.05?"above":c<y*.95?"below":"at",A=c>0?(c-y)/c*100:0,f=c-y,$=A>=35?"excellent":A>=20?"good":"critical",S=c-y,Z=c-n.totalFixed-n.totalVariable,z=o.contribution.value,X=Z!==0?z/Z:0,me=X>2?` Alta alavancagem: cada 1% de vendas aumenta o lucro em ${X.toFixed(2)}%`:X>1?` Alavancagem moderada: cada 1% de vendas aumenta o lucro em ${X.toFixed(2)}%`:X>.5?` Baixa alavancagem: custos variáveis são ${(n.totalVariable/c*100).toFixed(0)}% da receita`:" Alavancagem muito baixa ou negativa: empresa está com prejuÃzo ou margens muito apertadas",we={margemContribuicao:z,lucroOperacional:Z,custosFixos:n.totalFixed,custosVariaveis:n.totalVariable,receita:c},Y=A>20,P=A>=35?"low":A>=20?"medium":"high",w=[];if(C==="below"){const H=y-c,I=H/22,U=((y/c-1)*100).toFixed(1);w.push(` CRÃTICO: Você está R$ ${H.toFixed(2)} abaixo do ponto de equilÃbrio. Precisa aumentar o faturamento em ${U}% (mais R$ ${I.toFixed(2)}/dia) OU reduzir custos fixos de R$ ${u.toFixed(2)} para R$ ${(c*d/100).toFixed(2)}.`)}if(A<20&&C!=="below"){const I=y*1.35-c,U=I/22,se=(I/c*100).toFixed(1);w.push(` Margem de segurança baixa (${A.toFixed(1)}%). Para atingir 35% ideal, aumente vendas em R$ ${I.toFixed(2)} (${se}% ou +R$ ${U.toFixed(2)}/dia) OU reduza custos fixos em R$ ${(u*.2).toFixed(2)}.`)}if(N<100){const H=u-c*d/100,I=Math.ceil(H/(E*d/100));w.push(` Custos fixos descobertos: faltam R$ ${H.toFixed(2)} (${(100-N).toFixed(1)}%). AÃÃES: 1) Renegocie contratos (aluguel, fornecedores) para economizar pelo menos R$ ${(H*.5).toFixed(2)}; 2) Aumente vendas em R$ ${E.toFixed(2)}/dia; 3) Você precisa de ${I} dias para cobrir este déficit.`)}if(d<30){const I=g*(40/d-1),U=x*(1-d/40);w.push(` Margem de contribuição baixa (${d.toFixed(1)}%). OPÃÃES: 1) Aumente preço médio de R$ ${g.toFixed(2)} para R$ ${(g+I).toFixed(2)} (+${(I/g*100).toFixed(1)}%); 2) Reduza custo variável de R$ ${x.toFixed(2)} para R$ ${(x-U).toFixed(2)} (negocie com fornecedores);
69 3) Combine as duas estratégias para atingir 40% de margem.`)}if(A>=35&&A<50){const H=S,I=H*.3;w.push(` Boa margem de segurança (${A.toFixed(1)}%)! Você tem R$ ${H.toFixed(2)} de folga acima do PE. SUGESTÃES: 1) Invista R$ ${I.toFixed(2)} em marketing para crescer; 2) Reserve R$ ${(H*.4).toFixed(2)} como fundo de emergência; 3) Use R$ ${(H*.3).toFixed(2)} para melhorar estrutura/equipamentos.`)}if(A>=50){const H=S;w.push(` EXCELENTE! Margem de segurança de ${A.toFixed(1)}% - Você está ${(H/y*100).toFixed(0)}% acima do PE! ESTRATÃGIAS: 1) Expanda o negócio (nova loja, filial, franquia); 2) Diversifique produtos/serviços usando R$ ${(H*.3).toFixed(2)}; 3) Aumente pró-labore ou distribua lucros; 4) Invista em automação para reduzir custos variáveis.`)}X>3&&C==="above"&&w.push(` Alta alavancagem (${X.toFixed(2)}x): Cada 10% de aumento nas vendas gera ${(X*10).toFixed(0)}% mais lucro! FOCO: Investir R$ ${(c*.05).toFixed(2)} em marketing pode gerar R$ ${(c*.1*d/100).toFixed(2)} de lucro adicional.`),X<1.5&&C==="above"&&w.push(` Baixa alavancagem (${X.toFixed(2)}x): Seus custos fixos são baixos relativamente. OPORTUNIDADE: Considere investir em estrutura fixa (equipamentos, equipe) para escalar. Um investimento de R$ ${(u*.5).toFixed(2)} em custos fixos pode melhorar eficiência operacional.`);const O={optimistic:{revenue:c*1.2,safetyMargin:(c*1.2-y)/(c*1.2)*100,profit:c*1.2-n.totalFixed-n.totalVariable*1.2},pessimistic:{revenue:c*.8,safetyMargin:(c*.8-y)/(c*.8)*100,profit:c*.8-n.totalFixed-n.totalVariable*.8},realistic:{revenue:c,safetyMargin:A,profit:Z}};return{period:{startDate:r.startDate.toISOString(),endDate:r.endDate.toISOString()},components:{fixedCosts:u,averageContributionMargin:i,averageContributionMarginPercent:d,averageSellingPrice:g,averageVariableCost:x},breakEven:{revenueValue:y,unitsQuantity:M,dailyRevenue:E,dailyUnits:h},current:{currentRevenue:c,unitsSold:b,fixedCostsCoverage:N,status:C},safetyMargin:{percentage:A,value:f,benchmark:$,revenueBuffer:S},operatingLeverage:{degree:X,interpretation:me,details:we},viability:{isViable:Y,riskLevel:P,recommendations:w},scenarios:O}}async getSalesData(r,s){const{data:n}=await wa(v.from("sales").select("subtotal, sale_items(quantity)").eq("user_id",r).gte("created_at",s.startDate.toISOString()).lte("created_at",s.endDate.toISOString())),o=(n||[]).reduce((u,i)=>u+Number(i.subtotal||0),0);let m=0;return(n||[]).forEach(u=>{(u.sale_items||[]).forEach(i=>{m+=Number(i.quantity||0)})}),{totalRevenue:o,unitsSold:m}}}const Fn=new $n;function In(t){const[r,s]=_.useState(null),[n,o]=_.useState(!0),[m,u]=_.useState(null),i=_.useCallback(async()=>{try{o(!0),u(null);const d=await ja.generateDRE(t);s(d)}catch(d){const g=d instanceof Error?d.message:"Erro ao carregar DRE";u(g),ue.error(g),console.error("Erro ao buscar DRE:",d)}finally{o(!1)}},[t.startDate.getTime(),t.endDate.getTime()]);return _.useEffect(()=>{i()},[i]),{dreData:r,isLoading:n,error:m,refetch:i}}function On(t,r){const[s,n]=_.useState(null),[o,m]=_.useState(!0),[u,i]=_.useState(null),d=_.useCallback(async()=>{try{m(!0),i(null);const g=r!==void 0?await hr.calculateIndicatorsByHorizon(t,r):await hr.calculateIndicators(t);n(g)}catch(g){const x=g instanceof Error?g.message:"Erro ao carregar indicadores";i(x),ue.error(x),console.error("Erro ao buscar indicadores:",g)}finally{m(!1)}},[t.startDate.getTime(),t.endDate.getTime(),r]);return _.useEffect(()=>{d()},[d]),{indicators:s,isLoading:o,error:u,refetch:d}}function Tn(t){const[r,s]=_.useState(null),[n,o]=_.useState(!0),[m,u]=_.useState(null),i=_.useCallback(async()=>{try{o(!0),u(null);const d=await Gr.calculateMargins(t);s(d)}catch(d){const g=d instanceof Error?d.message:"Erro ao carregar margens";u(g),ue.error(g),console.error("Erro ao buscar margens:",d)}finally{o(!1)}},[t.startDate.getTime(),t.endDate.getTime()]);return _.useEffect(()=>{i()},[i]),{margins:r,isLoading:n,error:m,refetch:i}}function qn(t){const[r,s]=_.useState(null),[n,o]=_.useState(!0),[m,u]=_.useState(null),i=_.useCallback(async()=>{try{o(!0),u(null);const d=await Fn.calculateBreakEven(t);s(d)}catch(d){const g=d instanceof Error?d.message:"Erro ao carregar ponto de equilÃbrio";u(g),ue.error(g),console.error("Erro ao buscar ponto de equilÃbrio:",d)}finally{o(!1)}},[t.startDate.getTime(),t.endDate.getTime()]);return _.useEffect(()=>{i()},[i]),{breakEven:r,isLoading:n,error:m,refetch:i}}function Vn(t){const[r,s]=_.useState(null),[n,o]=_.useState(!0),[m,u]=_.useState(null),i=_.useCallback(async()=>{try{o(!0),u(null);const d=await ms(t.startDate,t.endDate);s({...d,impactoAtual:{...d.impactoAtual,lucroOperacional:d.impactoAtual.lucroAposRetirada},impactoSaudavel:{...d.impactoSaudavel,lucroOperacional:d.impactoSaudavel.lucroAposRetirada}})}catch(d){const g=d instanceof Error?d.message:"Erro ao analisar pró-labore";u(g),console.error("Erro ao carregar análise de pró-labore:",d)}finally{o(!1)}},[t.startDate,t.endDate]);return _.useEffect(()=>{i()},[i]),_.useEffect(()=>{const d=()=>i();return window.addEventListener("prolabore-updated",d),()=>window.removeEventListener("prolabore-updated",d)},[i]),{analysis:r,isLoading:n,error:m,refetch:i}}function Ln(){const[t,r]=_.useState([]),[s,n]=_.useState(!0),o=_.useCallback(async()=>{try{n(!0);const{data:{user:m}}=await v.auth.getUser();if(!m){r([]);return}const{data:u,error:i}=await v.from("bank_accounts").select("id, name, bank_name, current_balance, is_main").eq("user_id",m.id).eq("is_active",!0).order("is_main",{ascending:!1}).order("name");if(i)throw i;r(u||[])}catch(m){console.error("Erro ao carregar contas bancárias:",m),r([])}finally{n(!1)}},[]);return _.useEffect(()=>{o()},[o]),{accounts:t,loading:s,reload:o}}function Ye({title:t,value:r,benchmark:s,description:n,icon:o,trend:m,className:u}){const i={excellent:"text-green-600 bg-green-50 border-green-200",good:"text-blue-600 bg-blue-50 border-blue-200",critical:"text-red-600 bg-red-50 border-red-200"},d={excellent:"text-green-600",good:"text-blue-600",critical:"text-red-600"},g=m==="up"?Oe:m==="down"?Qa:Cr;return a(K,{className:_e("transition-all hover:shadow-md",s&&i[s],u),children:[e(te,{className:"pb-2",children:a(ne,{className:"flex items-center justify-between text-sm font-medium",children:[a("span",{className:"flex items-center gap-2",children:[o,t]}),m&&e(g,{className:_e("h-4 w-4",m==="up"&&"text-green-600",m==="down"&&"text-red-600",m==="neutral"&&"text-gray-400")})]})}),a(ee,{children:[e("div",{className:_e("text-2xl font-bold",s&&d[s]),children:r}),n&&e("p",{className:"text-xs text-muted-foreground mt-1",children:n})]})]})}function ie(t){return new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format(t)}function Te(t,r=2){return`${t.toFixed(r)}%`}function It(t,r=2){return new Intl.NumberFormat("pt-BR",{minimumFractionDigits:r,maximumFractionDigits:r}).format(t)}function Bn({margins:t}){const r=[{name:"Margem Bruta",data:t.gross,description:"Receita - CMV"},{name:"Margem de Contribuição",data:t.contribution,description:"Receita - Custos Variáveis"},{name:"EBITDA",data:t.ebitda,description:"Lucro antes de juros, impostos, depreciação"},{name:"EBIT",data:t.ebit,description:"Lucro antes de juros e impostos"},{name:"Margem LÃquida",data:t.net,description:"Lucro LÃquido / Receita"}],s=o=>({excellent:"bg-green-500",good:"bg-blue-500",critical:"bg-red-500"})[o],n=o=>({excellent:"text-green-600",good:"text-blue-600",critical:"text-red-600"})[o];return a(K,{children:[e(te,{children:e(ne,{children:"Análise de Margens"})}),e(ee,{className:"space-y-4",children:r.map(o=>a("div",{className:"space-y-2",children:[a("div",{className:"flex items-center justify-between",children:[a("div",{children:[e("p",{className:"font-medium text-sm",children:o.name}),e("p",{className:"text-xs text-muted-foreground",children:o.description})]}),a("div",{className:"text-right",children:[e("p",{className:`font-bold ${n(o.data.benchmark)}`,children:Te(o.data.percentage)}),e("p",{className:"text-xs text-muted-foreground",children:ie(o.data.value)})]})]}),e(Ia,{value:Math.min(o.data.percentage,100),className:`h-2 ${s(o.data.benchmark)}`})]},o.name))})]})}const zn={current:ua.IMMEDIATE,"90days":ua.SHORT_TERM,"1year":ua.MEDIUM_TERM};function jn({period:t}){var h;const[r,s]=_.useState("current"),n=zn[r],{indicators:o,isLoading:m,error:u}=On(t,n),{margins:i}=Tn(t);if(m)return e("div",{className:"flex items-center justify-center p-8",children:"Carregando indicadores..."});if(u||!o)return a("div",{className:"text-red-600 p-4",children:["Erro ao carregar indicadores: ",u]});const d=o.healthScore.overall>=60?"up":o.healthScore.overall>=40?"stable":"down",g=o.workingCapital.need>0?o.workingCapital.amount/o.workingCapital.need*100:100,x=o.workingCapital.amount>=o.workingCapital.need,y=o.activity.averageReceivingPeriod,M=o.activity.averagePaymentPeriod,E=y-M;return a("div",{className:"space-y-6 p-6",children:[((h=o.meta)==null?void 0:h.dreAligned)&&a("div",{className:"flex flex-wrap gap-2",children:[e(ae,{variant:"secondary",children:"Rentabilidade: regime de competência (igual à DRE)"}),e(ae,{variant:"outline",children:"PMP usa despesas do perÃodo · Liquidez usa contas em aberto por vencimento"})]}),a(K,{children:[a(te,{className:"pb-3",children:[e(ne,{className:"text-base",children:"Horizonte de Análise"}),e(Se,{children:"Filtre as contas a pagar e veja a saúde financeira em diferentes perÃodos"})]}),a(ee,{children:[e(pt,{value:r,onValueChange:c=>s(c),children:a(gt,{className:"grid w-full grid-cols-3",children:[e(qe,{value:"current",children:a("div",{className:"text-center",children:[e("div",{children:"Mês"}),e("div",{className:"text-[10px] text-muted-foreground",children:"30 dias"})]})}),e(qe,{value:"90days",children:a("div",{className:"text-center",children:[e("div",{children:"Trimestre"}),e("div",{className:"text-[10px] text-muted-foreground",children:"90 dias"})]})}),e(qe,{value:"1year",children:a("div",{className:"text-center",children:[e("div",{children:"Ano"}),e("div",{className:"text-[10px] text-muted-foreground",children:"365 dias"})]})})]})}),e("div",{className:"mt-3 p-3 bg-blue-50 dark:bg-blue-950 border-l-4 border-blue-500 rounded",children:a("p",{className:"text-sm",children:[r==="current"&&a(Ee,{children:[e("strong",{children:" Mês Corrente:"})," Mostra apenas contas que vencem ",e("strong",{children:"neste m
69ês"})," (01 a 30 de Novembro). Ideal para análise de liquidez imediata e gestão do fluxo mensal."]}),r==="90days"&&a(Ee,{children:[e("strong",{children:" Próximos 3 Meses:"})," Inclui todas as contas que vencem ",e("strong",{children:"nos próximos 90 dias"}),". Visão de curto prazo para planejamento trimestral."]}),r==="1year"&&a(Ee,{children:[e("strong",{children:" Próximo Ano:"})," Considera todas as dÃvidas que vencem ",e("strong",{children:"nos próximos 365 dias"}),". Permite planejamento financeiro de médio prazo."]})]})})]})]}),a(K,{className:"bg-gradient-to-r from-blue-50 to-purple-50 dark:from-blue-950 dark:to-purple-950",children:[e(te,{children:a(ne,{className:"flex items-center gap-2",children:[e(pa,{className:"h-5 w-5"}),"Saúde Financeira Geral"]})}),e(ee,{children:a("div",{className:"space-y-2",children:[a("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[a("div",{className:"flex items-center gap-3",children:[a("span",{className:"text-4xl font-bold",children:[o.healthScore.overall.toFixed(0),"/100"]}),d==="up"&&a(ae,{variant:"outline",className:"text-green-600 bg-green-50 border-green-200",children:[e(Oe,{className:"w-3 h-3 mr-1"})," Tendência Positiva"]}),d==="stable"&&a(ae,{variant:"outline",className:"text-yellow-600 bg-yellow-50 border-yellow-200",children:[e(Cr,{className:"w-3 h-3 mr-1"})," Estável"]}),d==="down"&&a(ae,{variant:"outline",className:"text-red-600 bg-red-50 border-red-200",children:[e(Qa,{className:"w-3 h-3 mr-1"})," Atenção Necessária"]})]}),e("span",{className:`text-lg font-semibold ${o.healthScore.classification==="excellent"?"text-green-600":o.healthScore.classification==="good"?"text-blue-600":o.healthScore.classification==="critical"?"text-red-600":"text-yellow-600"}`,children:o.healthScore.classification==="excellent"?"Excelente":o.healthScore.classification==="good"?"Bom":o.healthScore.classification==="critical"?"CrÃtico":"Atenção"})]}),e(Ia,{value:o.healthScore.overall,className:"h-3"}),o.healthScore.recommendations&&o.healthScore.recommendations.length>0&&a("div",{className:"mt-4 space-y-1",children:[e("p",{className:"font-medium text-sm",children:"Recomendações:"}),o.healthScore.recommendations.map((c,b)=>a("p",{className:"text-sm text-muted-foreground",children:["⢠",c]},b))]})]})})]}),a("div",{children:[a("div",{className:"flex items-center gap-2 mb-3",children:[a("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e(aa,{className:"h-5 w-5"}),"Liquidez"]}),a(ae,{variant:"outline",className:"text-green-600 bg-green-50 border-green-200",children:[e(sa,{className:"w-3 h-3 mr-1"})," Filtrado por horizonte"]})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e(Ye,{title:"Liquidez Corrente",value:It(o.liquidity.currentLiquidity),benchmark:o.liquidity.currentLiquidityBenchmark,description:"Ativo Circulante / Passivo Circulante",icon:e(aa,{className:"h-4 w-4"})}),e(Ye,{title:"DisponÃvel",value:ie(o.liquidity.disponivel),description:"Caixa + Bancos",icon:e(ea,{className:"h-4 w-4"})}),e(Ye,{title:"Ativo Circulante",value:ie(o.liquidity.ativoCirculante),description:"DisponÃvel + Estoque + RecebÃveis",icon:e(Oe,{className:"h-4 w-4"})}),e(Ye,{title:"Total de Contas a Pagar",value:ie(o.liquidity.passivoCirculante),description:"Obrigações de curto prazo",icon:e(ta,{className:"h-4 w-4 text-red-600"})})]})]}),i&&a("div",{children:[a("div",{className:"flex items-center gap-2 mb-3",children:[e("h3",{className:"text-lg font-semibold",children:"Análise de Margens"}),a(ae,{variant:"outline",className:"text-blue-600 bg-blue-50 border-blue-200",children:[e(ma,{className:"w-3 h-3 mr-1"})," Dados históricos"]})]}),e(Bn,{margins:i})]}),a("div",{children:[a("div",{className:"flex items-center gap-2 mb-3",children:[a("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e(Oe,{className:"h-5 w-5"}),"Rentabilidade"]}),a(ae,{variant:"outline",className:"text-blue-600 bg-blue-50 border-blue-200",children:[e(ma,{className:"w-3 h-3 mr-1"})," Dados históricos"]})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e(Ye,{title:"ROI",value:Te(o.profitability.roi),benchmark:o.profitability.roiBenchmark,description:"Retorno sobre Investimento",icon:e(Oe,{className:"h-4 w-4"})}),e(Ye,{title:"Margem Bruta",value:Te(o.profitability.grossMargin),benchmark:o.profitability.grossMarginBenchmark,description:"% da Receita",icon:e(ma,{className:"h-4 w-4"})}),e(Ye,{title:"Margem Operacional",value:Te(o.profitability.operatingMargin),benchmark:o.profitability.operatingMarginBenchmark,description:"% da Receita",icon:e(ma,{className:"h-4 w-4"})}),e(Ye,{title:"Margem LÃquida",value:Te(o.profitability.netMargin),benchmark:o.profitability.netMarginBenchmark,description:"% da Receita",icon:e(ma,{className:"h-4 w-4"})})]})]}),a("div",{children:[a("div",{className:"flex items-center gap-2 mb-3",children:[a("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e(na,{className:"h-5 w-5"}),"Endividamento"]}),a(ae,{variant:"outline",className:"text-green-600 bg-green-50 border-green-200",children:[e(sa,{className:"w-3 h-3 mr-1"})," Filtrado por horizonte"]})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e(Ye,{title:"Ãndice de Endividamento",value:Te(o.debt.debtRatio),benchmark:o.debt.debtRatioBenchmark,description:"Passivo Total / Ativo Total",icon:e(na,{className:"h-4 w-4"})}),e(Ye,{title:"DÃvidas Totais",value:ie(o.debt.passivoTotal),description:"Todas as obrigações"}),e(Ye,{title:"Composição",value:`${Te(o.debt.shortTermDebtRatio)} CP`,description:"Endividamento de Curto Prazo"})]})]}),a("div",{children:[a("div",{className:"flex items-center gap-2 mb-3",children:[a("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e(sa,{className:"h-5 w-5"}),"Prazos e Ciclo de Caixa"]}),a(ae,{variant:"outline",className:"text-blue-600 bg-blue-50 border-blue-200",children:[e(ma,{className:"w-3 h-3 mr-1"})," Médias históricas"]})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-4",children:[e(Ye,{title:"Prazo Médio Recebimento",value:`${y.toFixed(0)} dias`,benchmark:o.activity.receivingPeriodBenchmark,description:"Tempo para receber vendas",icon:e(sa,{className:"h-4 w-4"})}),e(Ye,{title:"Prazo Médio Pagamento",value:`${M.toFixed(0)} dias`,benchmark:o.activity.paymentPeriodBenchmark,description:"Tempo para pagar fornecedores",icon:e(sa,{className:"h-4 w-4"})}),e(Ye,{title:"Ciclo Financeiro",value:`${o.activity.financialCycle.toFixed(0)} dias`,benchmark:o.activity.financialCycleBenchmark,description:"PMR - PMP",icon:e(sa,{className:"h-4 w-4"})})]}),a(K,{children:[a(te,{className:"pb-3",children:[e(ne,{className:"text-sm",children:"Visualização do Ciclo de Caixa"}),e(Se,{children:"Análise do intervalo entre pagar e receber"})]}),e(ee,{children:a("div",{className:"space-y-4",children:[a("div",{children:[a("div",{className:"flex justify-between text-xs mb-1",children:[e("span",{className:"text-muted-foreground",children:"Prazo de Pagamento"}),a("span",{className:"font-medium",children:[M.toFixed(0)," dias"]})]}),e("div",{className:"h-3 bg-red-100 rounded-full overflow-hidden",children:e("div",{className:"h-full bg-red-500",style:{width:`${Math.min(M/Math.max(y,M,30)*100,100)}%`}})})]}),a("div",{children:[a("div",{className:"flex justify-between text-xs mb-1",children:[e("span",{className:"text-muted-foreground",children:"Prazo de Recebimento"}),a("span",{className:"font-medium",children:[y.toFixed(0)," dias"]})]}),e("div",{className:"h-3 bg-green-100 rounded-full overflow-hidden",children:e("div",{className:"h-full bg-green-500",style:{width:`${Math.min(y/Math.max(y,M,30)*100,100)}%`}})})]}),a("div",{className:`p-3 rounded-lg border-l-4 ${E>0?"bg-yellow-50 border-yellow-500 dark:bg-yellow-950":"bg-green-50 border-green-500 dark:bg-green-950"}`,children:[e("p",{className:"text-sm font-medium",children:E>0?a(Ee,{children:[e(na,{className:"inline h-4 w-4 mr-1"}),"Necessidade de Capital: ",E.toFixed(0)," dias de vendas"]}):a(Ee,{children:[e($e,{className:"inline h-4 w-4 mr-1"}),"Folga Financeira: ",Math.abs(E).toFixed(0)," dias"]})}),e("p",{className:"text-xs text-muted-foreground mt-1",children:E>0?"Você recebe depois de pagar. Precisa de capital para cobrir este intervalo.":"Você paga depois de receber. Situação financeira favorável."})]})]})})]})]}),a("div",{children:[a("div",{className:"flex items-center gap-2 mb-3",children:[a("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e(ea,{className:"h-5 w-5"}),"Capital de Giro"]}),a(ae,{variant:"outline",className:"text-green-600 bg-green-50 border-green-200",children:[e(sa,{className:"w-3 h-3 mr-1"})," Filtrado por horizonte"]})]}),a(K,{className:"mb-4",children:[a(te,{className:"pb-2",children:[e(ne,{className:"text-sm font-medium",children:"Cobertura de Capital de Giro"}),e(Se,{children:"Comparação entre capital disponÃvel e necessário"})]}),e(ee,{children:a("div",{className:"space-y-3",children:[a("div",{className:"flex justify-between text-sm",children:[a("span",{className:"text-muted-foreground",children:["DisponÃvel: ",e("span",{className:"font-medium text-foreground",children:ie(o.workingCapital.amount)})]}),a("span",{className:"text-muted-foreground",children:["Necessário: ",e("span",{className:"font-medium text-foreground",children:ie(o.workingCapital.need)})]})]}),a("div",{className:"space-y-1",children:[e(Ia,{value:Math.min(g,100),className:`h-3 ${x?"bg-green-100 [&>div]:bg-green-600 dark:bg-green-950":"bg-red-100 [&>div]:bg-red-600 dark:bg-red-950"}`}),a("p",{className:"text-xs text-right text-muted-foreground",children:[g.toFixed(0),"% de cobertura"]})]}),x?a("div",{className:"bg-green-50 dark:bg-green-950 border-l-4 border-green-500 p-3 rounded",children:[a("p",{className:"text-sm text-green-800 dark:text-green-200 font-medium flex items-center gap-2",children:[e($e,{className:"h-4 w-4"}),"Operação Saudável"]}),e("p",{className:"text-xs text-green-700 dark:text-green-300 mt-1",children:"Você tem capital próprio suficiente para girar o negócio sem depender de terceiros."})]}):a("div",{className:"bg-red-50 dark:bg-red-950 border-l-4 border-red-500 p-3 rounded",children:[a("p",{className:"text-sm text-red-800 dark:text-red-200 font-medium flex items-center gap-2",children:[e(na,{className:"h-4 w-4"}),"Alerta: Capital Insuficiente"]}),a("p",{className:"text-xs text-red-700 dark:text-red-300 mt-1",children:["Sua operação consome mais caixa do que você tem. Risco de insolvência em 90 dias se as vendas caÃrem.",o.workingCapital.need>0&&a(Ee,{children:[" Faltam: ",e("strong",{children:ie(o.workingCapital.need-o.workingCapital.amount)})]})]})]})]})})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e(Ye,{title:"Capital de Giro",value:ie(o.workingCapital.amount),benchmark:o.workingCapital.amountBenchmark,description:"Ativo Circulante - Passivo Circulante",icon:e(ea,{className:"h-4 w-4"})}),e(Ye,{title:"NCG (Necessidade)",value:ie(o.workingCapital.need),description:"Capital necessário para operação",icon:e(ea,{className:"h-4 w-4"})})]})]})]})}function Un({period:t}){const{dreData:r,isLoading:s,error:n}=In(t);if(s)return e("div",{className:"flex items-center justify-center p-8",children:"Carregando DRE..."});if(n||!r)return a("div",{className:"text-red-600 p-4",children:["Erro ao carregar DRE: ",n]});const o=[{label:"1. Receita Bruta",value:r.receitaBruta,isSubtotal:!1},{label:"2. (-) Deduções",value:r.deducoes.total,isSubtotal:!1,isNegative:!0},{label:"3. = Receita LÃquida",value:r.receitaLiquida,isSubtotal:!0,highlight:!0},{label:"4. (-) CMV",value:r.cmv.total,isSubtotal:!1,isNegative:!0},{label:"5. = Lucro Bruto",value:r.lucroBruto,isSubtotal:!0,highlight:!0},{label:"6. (-) Despesas Operacionais",value:r.despesasOperacionais.total,isSubtotal:!1,isNegative:!0},{label:"7. = EBITDA",value:r.ebitda,isSubtotal:!0,highlight:!0},{label:"8. = EBIT (Lucro Operacional)",value:r.ebit,isSubtotal:!0,highlight:!0},{label:"9. (-) Despesas Financeiras",value:r.despesasFinanceiras.total,isSubtotal:!1,isNegative:!0},{label:"10. (+) Receitas Financeiras",value:r.receitasFinanceiras,isSubtotal:!1},{label:"11. = EBT (Antes Impostos)",value:r.ebt,isSubtotal:!0}
69,{label:"12. (-) Impostos sobre Lucro",value:r.impostosLucro,isSubtotal:!1,isNegative:!0},{label:"13. = Lucro LÃquido",value:r.lucroLiquido,isSubtotal:!0,highlight:!0,isFinal:!0}],m=(i,d)=>d?"text-red-600":i>=0?"text-green-600":"text-red-600",u=i=>r.receitaLiquida===0?0:i/r.receitaLiquida*100;return a("div",{className:"space-y-6 p-6",children:[a(K,{children:[e(te,{children:a("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[a("div",{children:[a(ne,{className:"flex items-center gap-2",children:[e(je,{className:"h-5 w-5"}),"DRE - Demonstração do Resultado do ExercÃcio"]}),a(Se,{className:"mt-1",children:["PerÃodo: ",Ze(t.startDate)," até ",Ze(t.endDate)]})]}),a("div",{className:"flex flex-wrap gap-2",children:[a(ae,{variant:"outline",className:"text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-800",children:[e(ma,{className:"w-3 h-3 mr-1"})," Regime de competência"]}),r.meta&&a(ae,{variant:"outline",title:r.meta.salesTaxLabel,children:["Impostos s/ vendas: ",r.meta.salesTaxRatePercent.toFixed(2),"%"]})]})]})}),e(ee,{children:a("div",{className:"bg-blue-50 dark:bg-blue-950 border-l-4 border-blue-500 p-3 rounded space-y-1",children:[a("p",{className:"text-sm",children:[e("strong",{children:"Importante:"})," Receitas pela ",e("strong",{children:"data da venda"}),"; despesas pelo mês de"," ",e("strong",{children:"competência"})," da conta (vencimento ao cadastrar). Não é necessário estar paga para entrar na DRE."]}),r.meta&&e("p",{className:"text-xs text-muted-foreground",children:r.meta.salesTaxLabel})]})})]}),a(K,{children:[e(te,{children:e(ne,{children:"Demonstrativo Completo"})}),e(ee,{children:e("div",{className:"space-y-2",children:o.map((i,d)=>a("div",{children:[i.isSubtotal&&d>0&&e(He,{className:"my-3"}),a("div",{className:`flex items-center justify-between py-2 ${i.highlight?"bg-blue-50 dark:bg-blue-950/30 px-3 rounded-md":""} ${i.isFinal?"bg-green-50 dark:bg-green-950/30 px-3 rounded-md font-bold":""}`,children:[a("div",{className:"flex items-center gap-2",children:[i.value>=0&&!i.isNegative?e(Oe,{className:"h-4 w-4 text-green-600"}):e(Qa,{className:"h-4 w-4 text-red-600"}),e("span",{className:`${i.isSubtotal?"font-semibold":""} ${i.isFinal?"text-lg":""}`,children:i.label})]}),a("div",{className:"text-right",children:[e("div",{className:`${i.isSubtotal?"font-semibold text-lg":""} ${m(i.value,i.isNegative)}`,children:ie(Math.abs(i.value))}),a("div",{className:"text-xs text-muted-foreground",children:[Te(u(i.value))," da receita"]})]})]}),i.isSubtotal&&!i.isFinal&&e(He,{className:"my-3"})]},d))})})]}),a(K,{children:[e(te,{children:e(ne,{children:"Detalhamento do CMV (Custo da Mercadoria Vendida)"})}),e(ee,{children:a("div",{className:"space-y-3",children:[a("div",{className:"flex justify-between",children:[e("span",{className:"text-sm",children:"Matéria-Prima"}),e("span",{className:"font-medium",children:ie(r.cmv.materiaPrima)})]}),a("div",{className:"flex justify-between",children:[e("span",{className:"text-sm",children:"Mão de Obra Direta"}),e("span",{className:"font-medium",children:ie(r.cmv.maoDeObraDireta)})]}),a("div",{className:"flex justify-between",children:[e("span",{className:"text-sm",children:"Custos de Produção"}),e("span",{className:"font-medium",children:ie(r.cmv.custosProducaoDiretos)})]}),e(He,{}),a("div",{className:"flex justify-between font-semibold text-lg",children:[e("span",{children:"Total CMV"}),e("span",{className:"text-red-600",children:ie(r.cmv.total)})]})]})})]}),a(K,{children:[e(te,{children:e(ne,{children:"Detalhamento das Despesas Operacionais"})}),e(ee,{children:a("div",{className:"space-y-3",children:[a("div",{className:"flex justify-between",children:[e("span",{className:"text-sm",children:"Despesas de Vendas"}),e("span",{className:"font-medium",children:ie(r.despesasOperacionais.despesasVendas)})]}),a("div",{className:"flex justify-between",children:[e("span",{className:"text-sm",children:"Despesas Administrativas"}),e("span",{className:"font-medium",children:ie(r.despesasOperacionais.despesasAdministrativas)})]}),a("div",{className:"flex justify-between",children:[e("span",{className:"text-sm",children:"Despesas Gerais"}),e("span",{className:"font-medium",children:ie(r.despesasOperacionais.despesasGerais)})]}),e(He,{}),a("div",{className:"flex justify-between font-semibold text-lg",children:[e("span",{children:"Total Despesas Operacionais"}),e("span",{className:"text-red-600",children:ie(r.despesasOperacionais.total)})]})]})})]}),a(K,{children:[e(te,{children:e(ne,{children:"Ãndices Importantes"})}),e(ee,{children:a("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[a("div",{className:"text-center p-4 bg-green-50 dark:bg-green-950/30 rounded-lg",children:[e("p",{className:"text-sm text-muted-foreground mb-1",children:"Margem Bruta"}),e("p",{className:"text-3xl font-bold text-green-600 dark:text-green-400",children:Te(r.margemBruta)})]}),a("div",{className:"text-center p-4 bg-blue-50 dark:bg-blue-950/30 rounded-lg",children:[e("p",{className:"text-sm text-muted-foreground mb-1",children:"Margem EBITDA"}
69),e("p",{className:"text-3xl font-bold text-blue-600 dark:text-blue-400",children:Te(r.margemEBITDA)})]}),a("div",{className:"text-center p-4 bg-purple-50 dark:bg-purple-950/30 rounded-lg",children:[e("p",{className:"text-sm text-muted-foreground mb-1",children:"Margem LÃquida"}),e("p",{className:"text-3xl font-bold text-purple-600 dark:text-purple-400",children:Te(r.margemLiquida)})]})]})})]})]})}const Gn={monthly:"Mensal",weekly:"Semanal",biweekly:"Quinzenal"};function Hn(t){return t.map(r=>({id:r.id,partner_name:r.partner_name,amountMonthly:bs(r.amount,r.frequency),frequency:r.frequency||"monthly",active:r.active}))}function Xn({open:t,onOpenChange:r,month:s,year:n,onApplied:o}){const[m,u]=_.useState(!0),[i,d]=_.useState(!1),[g,x]=_.useState(!0),[y,M]=_.useState([]),[E,h]=_.useState([]),[c,b]=_.useState(""),[N,C]=_.useState({receitas:0,despesasSemProlabore:0,margemContribuicaoPct:50,lucroOperacional:0,prolaboreAtual:0}),[A,f]=_.useState(null),$=_.useCallback(async()=>{u(!0);try{const{data:{user:P}}=await v.auth.getUser();if(!P)throw new Error("Não autenticado");await ut(P.id,{syncPayable:!0});const w=await us(n,s),O=await Ot(P.id),H=ps(O,w.prolaboreAtual);C({receitas:w.receitas,despesasSemProlabore:w.despesasSemProlabore,margemContribuicaoPct:w.margemContribuicaoPct,lucroOperacional:w.lucroOperacional,prolaboreAtual:w.prolaboreAtual}),f(w.payableMirror??null),M(H);const I=Hn(w.partners);h(I),I.length>0?b(String(Math.round(Nr(I.map(U=>({amount:U.amountMonthly,frequency:"monthly",active:U.active})))))):b(String(w.prolaboreAtual>0?Math.round(w.prolaboreAtual):0))}catch(P){console.error(P),ue.error("Não foi possÃvel carregar os dados financeiros")}finally{u(!1)}},[n,s]);_.useEffect(()=>{t&&$()},[t,$]);const S=_.useMemo(()=>E.filter(P=>P.active).reduce((P,w)=>P+(Number(w.amountMonthly)||0),0),[E]),Z=E.length>0?S:parseFloat(c)||0,z=_.useMemo(()=>Qt(y).reduce((P,w)=>P+(Number(w.amount)||0),0),[y]),X=_.useMemo(()=>m?null:_r({...N,prolaboreAtual:Z,gastosPessoais:z}),[N,Z,z,m]),me=async()=>{const P=Z;if(P<0){ue.error("Informe um valor válido");return}d(!0);try{const{data:{user:w}}=await v.auth.getUser();if(!w)throw new Error("Não autenticado");await wr({userId:w.id,totalAmount:P,partners:E.length>0?E.filter(O=>O.active).map(O=>({id:O.id,amount:O.amountMonthly,frequency:"monthly"})):void 0,syncPayable:g,personalExpenses:Qt(y)}),ue.success(`Pró-labore atualizado para ${ve(P)}/mês`),o==null||o(),r(!1)}catch(w){console.error(w),ue.error("Erro ao salvar pró-labore")}finally{d(!1)}},we=(P,w,O)=>{M(H=>{const I=[...H];return w==="amount"?I[P]={...I[P],amount:parseFloat(O)||0}:I[P]={...I[P],category:O},I})},Y=(P,w)=>{const O=parseFloat(w)||0;h(H=>H.map(I=>I.id===P?{...I,amountMonthly:O}:I))};return e(Ea,{open:t,onOpenChange:r,children:a(Sa,{className:"max-w-6xl w-[min(96vw,72rem)] max-h-[92vh] flex flex-col p-0 gap-0 overflow-hidden",children:[a(Pa,{className:"px-6 pt-6 pb-4 shrink-0 border-b",children:[a(Ma,{className:"flex items-center gap-2",children:[e(Ga,{className:"h-5 w-5 text-emerald-600"}),"Reajuste de Pró-labore"]}),e(Oa,{children:"Ajuste a retirada dos sócios e seus gastos pessoais. Os valores atualizam a precificação e as análises do financeiro."})]}),m?e("div",{className:"flex justify-center py-16 px-6",children:e(ba,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):a("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-5",children:[a("div",{className:"rounded-lg border bg-muted/30 p-4 text-sm grid grid-cols-2 md:grid-cols-4 gap-4",children:[a("div",{children:[e("span",{className:"text-muted-foreground text-xs uppercase tracking-wide",children:"Receita do mês"}),e("p",{className:"font-semibold text-lg",children:ve(N.receitas)})]}),a("div",{children:[e("span",{className:"text-muted-foreground text-xs uppercase tracking-wide",children:"Despesas (sem pró-labore)"}),e("p",{className:"font-semibold text-lg",children:ve(N.despesasSemProlabore)})]}),a("div",{children:[e("span",{className:"text-muted-foreground text-xs uppercase tracking-wide",children:"Margem de contribuição"}),a("p",{className:"font-semibold text-lg",children:[N.margemContribuicaoPct.toFixed(1),"%"]})]}),a("div",{children:[e("span",{className:"text-muted-foreground text-xs uppercase tracking-wide",children:"Lucro operacional (MC)"}),e("p",{className:"font-semibold text-lg",children:ve(N.lucroOperacional)})]})]}),a("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6 items-start",children:[a("div",{className:"space-y-4 min-w-0",children:[X&&a("div",{className:"grid grid-cols-2 gap-2 text-center",children:[a("div",{className:"rounded-lg border p-2 bg-muted/40",children:[e("p",{className:"text-xs text-muted-foreground",children:"Cadastrado"}),e("p",{className:"font-semibold",children:ve(N.prolaboreAtual)})]}),a("div",{className:"rounded-lg border p-2 bg-blue-50 dark:bg-blue-950/30",children:[e("p",{className:"text-xs text-muted-foreground",children:"MÃnimo"}),e("p",{className:"font-semibold text-blue-700 dark:text-blue-400",children:ve(X.minimo)})]}),a("div",{className:"rounded-lg border p-2 bg-emerald-50 dark:bg-emerald-950/30",children:[e("p",{className:"text-xs text-muted-foreground",children:"Sustentável"}),e("p",{className:"font-semibold text-emerald-700 dark:text-emerald-400",children:ve(X.saudavel)})]}),a("div",{className:"rounded-lg border p-2 bg-amber-50 dark:bg-amber-950/30",children:[e("p",{className:"text-xs text-muted-foreground",children:"Sugestão (+20%)"}),e("p",{className:"font-semibold text-amber-700 dark:text-amber-400",children:ve(Rt(z))})]})]}),a("div",{children:[e("div",{className:"flex items-center justify-between mb-2",children:a(be,{className:"flex items-center gap-2",children:[e(Aa,{className:"h-4 w-4"}),"Sócios cadastrados"]})}),E.length===0?a(Fe,{children:[e(Dt,{className:"h-4 w-4"}),e(Ie,{children:"Nenhum sócio cadastrado. Informe o valor abaixo para criar o cadastro do sócio principal."})]}):a("div",{className:"space-y-2",children:[E.map(P=>a("div",{className:"flex flex-wrap gap-2 items-center border rounded-md p-2",children:[a("span",{className:"flex-1 text-sm font-medium min-w-[120px]",children:[P.partner_name,a("span",{className:"block text-xs text-muted-foreground font-normal",children:["Retirada ",Gn[P.frequency]||P.frequency," â equivalente mensal abaixo"]})]}),e(Ce,{type:"number",className:"w-32 text-right",value:P.amountMonthly||"",onChange:w=>Y(P.id,w.target.value),"aria-label":`Valor mensal ${P.partner_name}`})]},P.id)),a("p",{className:"text-sm text-right font-semibold",children:["Total sócios: ",ve(S),"/mês"]})]})]}),E.length===0&&a("div",{children:[e(be,{className:"mb-2 block",children:"Pró-labore mensal desejado"}
69),e(Ce,{type:"number",min:0,step:.01,value:c,onChange:P=>b(P.target.value),className:"text-lg font-semibold text-right"})]}),X&&a("div",{className:"flex flex-wrap gap-2",children:[e(j,{type:"button",variant:"outline",size:"sm",onClick:()=>{if(E.length>0){const P=X.minimo/E.length;h(w=>w.map(O=>({...O,amountMonthly:Math.round(P)})))}else b(String(Math.round(X.minimo)))},children:"Usar mÃnimo"}),e(j,{type:"button",variant:"outline",size:"sm",onClick:()=>{if(E.length>0){const P=X.saudavel/E.length;h(w=>w.map(O=>({...O,amountMonthly:Math.round(P)})))}else b(String(Math.round(X.saudavel)))},children:"Usar sustentável"}),e(j,{type:"button",variant:"outline",size:"sm",onClick:()=>{const P=Math.round(Rt(z));if(E.length>0){const w=P/E.length;h(O=>O.map(H=>({...H,amountMonthly:Math.round(w)})))}else b(String(P))},children:"Sugestão assistente"})]}),A&&a("p",{className:"text-xs text-muted-foreground flex items-start gap-1 rounded-md border p-2 bg-muted/20",children:[e(Dt,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),"Conta recorrente em Contas a Pagar: ",A.description," â"," ",ve(A.amount),Math.abs(A.amount-Z)>1&&a("span",{className:"text-amber-600 dark:text-amber-400",children:[" ","(valor diferente do cadastro de sócios)"]})]})]}),a("div",{className:"space-y-3 min-w-0 rounded-lg border p-4 bg-card/50",children:[a("div",{className:"flex items-center justify-between",children:[a(be,{className:"flex items-center gap-2 text-base",children:[e(ea,{className:"h-4 w-4"}),"Gastos pessoais"]}),a(ae,{variant:"secondary",children:[ve(z),"/mês"]})]}),e("p",{className:"text-xs text-muted-foreground",children:'Mesmas categorias do assistente financeiro. Preencha cada valor mensal; use "Adicionar gasto" só para categorias extras.'}),a("div",{className:"space-y-2 max-h-[min(50vh,22rem)] overflow-y-auto pr-1",children:[y.map((P,w)=>{const O=wt(P.category)||Jt(P.category),H=Jt(P.category);return a("div",{className:`flex gap-2 items-center ${H?"rounded-md border border-amber-500/40 bg-amber-500/10 p-2":""}`,children:[O?e(be,{className:"flex-1 text-sm font-normal leading-snug py-2",children:P.category}):e(Ce,{className:"flex-1 text-sm",value:P.category,onChange:I=>we(w,"category",I.target.value),placeholder:"Descreva o gasto",list:"personal-expense-suggestions"}),e(Ce,{type:"number",className:"w-32 text-right shrink-0",placeholder:"0",value:P.amount||"",onChange:I=>we(w,"amount",I.target.value)}),e(j,{type:"button",variant:"ghost",size:"icon",className:"shrink-0",onClick:()=>M(I=>I.filter((U,se)=>se!==w)),disabled:wt(P.category)&&!H,title:wt(P.category)&&!H?"Categorias padrão do assistente não podem ser removidas":"Remover",children:e(ya,{className:"h-4 w-4"})})]},`${P.category}-${w}`)}),e("datalist",{id:"personal-expense-suggestions",children:gs.map(P=>e("option",{value:P.category},P.category))})]}),a(j,{type:"button",variant:"outline",size:"sm",onClick:()=>M(P=>[...P,hs(P)]),children:[e(ga,{className:"h-4 w-4 mr-1"}),"Adicionar gasto"]})]})]}),X&&X.impactoAtual.lucroAposRetirada<0&&e(Fe,{variant:"destructive",children:a(Ie,{children:["Com este valor, o lucro após retirada fica negativo (",ve(X.impactoAtual.lucroAposRetirada),")."]})}),(X==null?void 0:X.recomendacao)&&a(Fe,{children:[e(Oe,{className:"h-4 w-4"}),e(Ie,{children:X.recomendacao})]})]}),a(Tt,{className:"gap-2 sm:gap-0 px-6 py-4 border-t shrink-0 bg-background",children:[a("div",{className:"flex items-center gap-2 mr-auto",children:[e(st,{id:"sync-payable",checked:g,onCheckedChange:P=>x(P===!0)}),e("label",{htmlFor:"sync-payable",className:"text-sm cursor-pointer",children:"Atualizar também a conta mensal em Contas a Pagar"})]}),e(j,{variant:"outline",onClick:()=>r(!1),disabled:i,children:"Cancelar"}),a(j,{onClick:me,disabled:m||i,children:[i?e(ba,{className:"h-4 w-4 animate-spin mr-2"}):null,"Aplicar reajuste"]})]})]})})}function Hr({month:t,year:r,variant:s="outline",size:n="sm",className:o,onApplied:m}){const[u,i]=_.useState(!1);return a(Ee,{children:[a(j,{type:"button",variant:s,size:n,className:_e("gap-1.5",o),onClick:()=>i(!0),children:[e(Ga,{className:"h-4 w-4"}),e("span",{className:"hidden sm:inline",children:"Reajustar pró-labore"}),e("span",{className:"sm:hidden",children:"Pró-labore"})]}),e(Xn,{open:u,onOpenChange:i,month:t,year:r,onApplied:m})]})}function Yn({recommendations:t=[]}){const[r,s]=_.useState([]),[n,o]=_.useState(!0);_.useEffect(()=>{m()},[]);const m=async()=>{try{const{data:{user:u}}=await v.auth.getUser();if(!u)return;const i=de(tr(new Date,30),"yyyy-MM-dd"),d=de(tr(new Date,7),"yyyy-MM-dd"),{data:g}=await v.from("products").select("*").eq("user_id",u.id);if(!g)return;const{data:x}=await v.from("orders").select("id, created_at, total_amount, cancelled_at").eq("user_id",u.id).gte("created_at",i).is("cancelled_at",null),y=(x==null?void 0:x.map(c=>c.id))||[],{data:M}=y.length>0?await v.from("order_items").select("order_id, product_id, quantity, unit_price").in("order_id",y):{data:[]},E=[];for(const c of g){const b=(M==null?void 0:M.filter(z=>z.product_id===c.id))||[],N=b.reduce((z,X)=>z+(X.quantity||0),0),C=(x==null?void 0:x.filter(z=>z.created_at>=d).map(z=>z.id))||[],f=b.filter(z=>C.includes(z.order_id)).reduce((z,X)=>z+(X.quantity||0),0),$=Number(c.final_price||0),S=Number(c.material_cost||0)+Number(c.labor_cost||0)+Number(c.depreciation_cost||0)+Number(c.other_costs||0),Z=$>0?($-S)/$*100:0;if(f===0&&N<3){const z=S*1.1,X=Math.max(z,$*.7),me=(X-S)/X*100;E.push({id:c.id,name:c.name,category:c.category||"Outros",type:"slow_moving",metric:f,suggestion:" Produto Parado! Sem vendas há 7+ dias. Faça uma promoção ou queima de estoque.",action:`Vender por até R$ ${X.toFixed(2)} ainda garante ${me.toFixed(1)}% de margem`,icon:va,color:"text-orange-600"})}if(Z>40&&N>0&&E.push({id:c.id,name:c.name,category:c.category||"Outros",type:"high_margin",metric:Z,suggestion:` Margem Excelente! ${Z.toFixed(1)}% de lucro. Este produto é uma mina de ouro!`,action:`Divulgue mais nas redes sociais, invista em anúncios. Cada venda gera R$ ${($-S).toFixed(2)}`,icon:oa,color:"text-green-600"}),N>=10){const z=b.reduce((X,me)=>X+(me.quantity||0)*(me.unit_price||0),0);E.push({id:c.id,name:c.name,category:c.category||"Outros",type:"best_seller",metric:N,suggestion:` Campeão de Vendas! ${N} unidades vendidas em 30 dias.`,action:`Vender +${Math.ceil(N*.2)} por mês aumenta receita em R$ ${(z*.2).toFixed(2)}`,icon:Oe,color:"text-blue-600"})}if(Z>0&&Z<20&&N>0){const z=S*1.67,X=z-$;E.push({id:c.id,name:c.name,category:c.category||"Outros",type:"low_margin",metric:Z,suggestion:` Margem Baixa! Apenas ${Z.toFixed(1)}% de lucro. Considere reajustar o preço.`,action:`Aumentar para R$ ${z.toFixed(2)} (+R$ ${X.toFixed(2)}) daria 40% de margem`,icon:na,color:"text-red-600"})}}const h=E.sort((c,b)=>{const N={slow_moving:1,low_margin:2,high_margin:3,best_seller:4};return N[c.type]-N[b.type]});s(h.slice(0,6)),o(!1)}catch(u){console.error("Erro ao carregar insights:",u),o(!1)}};return n?a(K,{children:[e(te,{children:a(ne,{className:"flex items-center gap-2",children:[e(pa,{
69className:"h-5 w-5"}),"Análise Inteligente de Produtos"]})}),e(ee,{children:e("p",{className:"text-sm text-muted-foreground",children:"Analisando seu catálogo..."})})]}):r.length===0?a(K,{children:[e(te,{children:a(ne,{className:"flex items-center gap-2",children:[e(pa,{className:"h-5 w-5"}),"Análise Inteligente de Produtos"]})}),e(ee,{children:e("p",{className:"text-sm text-muted-foreground",children:"Nenhum insight disponÃvel no momento. Registre mais vendas para obter análises personalizadas."})})]}):a(K,{children:[a(te,{children:[a(ne,{className:"flex items-center gap-2",children:[e(pa,{className:"h-5 w-5"}),"Análise Inteligente de Produtos"]}),e("p",{className:"text-sm text-muted-foreground mt-1",children:"Insights práticos baseados em vendas reais dos últimos 30 dias"})]}),a(ee,{children:[e("div",{className:"space-y-4",children:r.map(u=>{const i=u.icon;return e("div",{className:"p-4 border rounded-lg hover:bg-muted/50 transition-colors",children:a("div",{className:"flex items-start gap-3",children:[e("div",{className:`p-2 rounded-lg ${u.type==="slow_moving"?"bg-orange-100":u.type==="low_margin"?"bg-red-100":u.type==="high_margin"?"bg-green-100":"bg-blue-100"}`,children:e(i,{className:`h-5 w-5 ${u.color}`})}),a("div",{className:"flex-1 space-y-2",children:[a("div",{className:"flex items-center justify-between gap-2",children:[e("h4",{className:"font-semibold text-sm",children:u.name}),e(ae,{variant:"outline",className:"text-xs",children:u.category})]}),e("p",{className:"text-sm text-muted-foreground leading-relaxed",children:u.suggestion}),a("div",{className:`text-xs font-medium p-2 rounded ${u.type==="slow_moving"?"bg-orange-50 text-orange-900":u.type==="low_margin"?"bg-red-50 text-red-900":u.type==="high_margin"?"bg-green-50 text-green-900":"bg-blue-50 text-blue-900"}`,children:[e("strong",{children:"Ação:"})," ",u.action]})]})]})},u.id)})}),e("div",{className:"mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:a("p",{className:"text-xs text-blue-900",children:[e("strong",{children:" Dica:"}),' Focar nos produtos certos pode melhorar seu ponto de equilÃbrio muito mais que apenas "vender mais".']})}),t.length>0&&a("div",{className:"mt-6 pt-6 border-t",children:[a("h3",{className:"font-semibold text-sm mb-3 flex items-center gap-2",children:[e(pa,{className:"h-4 w-4"}),"Recomendações do Sistema"]}),e("div",{className:"space-y-2",children:t.map((u,i)=>a("div",{className:"flex items-start gap-2 p-3 bg-amber-50 border border-amber-200 rounded-lg",children:[e(na,{className:"h-4 w-4 text-amber-600 mt-0.5 flex-shrink-0"}),e("p",{className:"text-sm text-amber-900",children:u})]},i))})]})]})]})}function Wn({period:t}){const{breakEven:r,isLoading:s,error:n,refetch:o}=qn(t),{analysis:m,isLoading:u,refetch:i}=Vn(t),d=t.startDate.getMonth()+1,g=t.startDate.getFullYear(),[x,y]=_.useState(!1),[M,E]=_.useState([]),[h,c]=_.useState(!1),[b,N]=_.useState(!1),{toast:C}=Wa();_.useEffect(()=>{x&&A()},[x]),_.useEffect(()=>{const z=()=>{o(),x&&A()};return window.addEventListener("accounts-payable-updated",z),window.addEventListener("prolabore-updated",z),()=>{window.removeEventListener("accounts-payable-updated",z),window.removeEventListener("prolabore-updated",z)}},[x,o]);const A=async()=>{c(!0);try{const{data:{user:z}}=await v.auth.getUser();if(!z)return;const{data:X}=await v.from("accounts_payable").select("*").eq("user_id",z.id).gte("due_date",t.startDate.toISOString()).lte("due_date",t.endDate.toISOString()).order("amount",{ascending:!1});E(X||[])}catch(z){console.error("Erro ao carregar contas:",z)}finally{c(!1)}},f=async()=>{N(!0);try{await o(),x&&await A(),C({title:"â Dados atualizados!",description:"As informações foram recarregadas com sucesso."})}catch{C({title:"Erro ao atualizar",description:"Não foi possÃvel recarregar os dados.",variant:"destructive"})}finally{N(!1)}};if(s)return e("div",{className:"flex items-center justify-center p-8",children:"Carregando ponto de equilÃbrio..."});if(n||!r)return a("div",{className:"text-red-600 p-4",children:["Erro ao carregar ponto de equilÃbrio: ",n]});const S={above:{color:"text-green-600 dark:text-green-400",bg:"bg-green-50 dark:bg-green-950/30",icon:nt,text:"Acima do PE"},at:{color:"text-yellow-600 dark:text-yellow-400",bg:"bg-yellow-50 dark:bg-yellow-950/30",icon:Me,text:"No PE"},below:{color:"text-red-600 dark:text-red-400",bg:"bg-red-50 dark:bg-red-950/30",icon:Me,text:"Abaixo do PE"}}[r.current.status],Z=S.icon;return a("div",{className:"space-y-6 p-6",children:[a(K,{className:S.bg,children:[e(te,{children:a("div",{className:"flex items-center justify-between",children:[a(ne,{className:"flex items-center gap-2",children:[e(Z,{className:`h-5 w-5 ${S.color}`}),a("span",{className:S.color,children:["Status: ",S.text]})]}),a("div",{className:"flex items-center gap-2 flex-wrap justify-end",children:[e(Hr,{month:d,year:g,onApplied:()=>{o(),i()}}),a(j,{variant:"outline",size:"sm",onClick:f,disabled:b,children:[e(ha,{
69className:`h-4 w-4 mr-2 ${b?"animate-spin":""}`}),"Atualizar"]}),e(j,{variant:"outline",size:"sm",onClick:()=>y(!x),children:x?a(Ee,{children:[e(Ns,{className:"h-4 w-4 mr-2"}),"Ocultar Detalhes"]}):a(Ee,{children:[e(_s,{className:"h-4 w-4 mr-2"}),"Ver de Onde Vem o PE"]})})]})]})}),a(ee,{className:"space-y-6",children:[a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a("div",{children:[e("p",{className:"text-sm text-muted-foreground",children:"Faturamento Atual"}),e("p",{className:"text-3xl font-bold",children:ie(r.current.currentRevenue)})]}),a("div",{children:[e("p",{className:"text-sm text-muted-foreground",children:"Ponto de EquilÃbrio (Mensal)"}),e("p",{className:"text-3xl font-bold text-blue-600",children:ie(r.breakEven.revenueValue)})]})]}),e("div",{className:"p-4 bg-white/50 rounded-lg border",children:a("div",{className:"flex items-center justify-between",children:[a("div",{children:[e("p",{className:"text-sm text-muted-foreground",children:"Faturamento Necessário (Diário)"}),e("p",{className:"text-2xl font-bold text-blue-600",children:ie(r.breakEven.dailyRevenue)})]}),e(ae,{variant:"outline",className:"text-xs",children:"22 dias úteis"})]})}),a("div",{children:[a("div",{className:"flex justify-between text-sm mb-2",children:[e("span",{children:"Cobertura dos Custos Fixos"}),e("span",{className:"font-semibold",children:Te(r.current.fixedCostsCoverage)})]}),e(Ia,{value:r.current.fixedCostsCoverage,className:"h-3"})]}),x&&a("div",{className:"mt-6 pt-6 border-t",children:[a("div",{className:"flex items-center gap-2 mb-4",children:[e(da,{className:"h-5 w-5 text-blue-600"}),e("h3",{className:"font-semibold text-lg",children:"De Onde Vem o Ponto de EquilÃbrio?"})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6 mb-4 p-4 bg-white/50 rounded-lg border",children:[a("div",{className:"space-y-3",children:[a("div",{className:"flex justify-between",children:[e("span",{className:"text-sm text-muted-foreground",children:"Custos Fixos Totais"}),e("span",{className:"font-semibold",children:ie(r.components.fixedCosts)})]}),a("div",{className:"flex justify-between",children:[e("span",{className:"text-sm text-muted-foreground",children:"Margem de Contribuição (%)"}),e("span",{className:"font-semibold text-green-600",children:Te(r.components.averageContributionMarginPercent)})]})]}),a("div",{className:"space-y-3",children:[a("div",{className:"flex justify-between",children:[e("span",{className:"text-sm text-muted-foreground",children:"Preço Médio de Venda"}),e("span",{className:"font-semibold",children:ie(r.components.averageSellingPrice)})]}),a("div",{className:"flex justify-between",children:[e("span",{className:"text-sm text-muted-foreground",children:"Custo Variável Médio"}),e("span",{className:"font-semibold",children:ie(r.components.averageVariableCost)})]})]})]}),h?e("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Carregando contas..."}):M.length===0?a(Fe,{children:[e(Me,{className:"h-4 w-4"}),e(Ie,{children:"Nenhuma conta encontrada para este perÃodo."})]}):a(Ee,{children:[a(Fe,{className:"mb-4",children:[e(Me,{className:"h-4 w-4"}),a(Ie,{children:[e("strong",{children:"Atenção:"})," O PE considera TODAS as contas com vencimento neste mês (pagas e a pagar). Para parcelas, considera apenas o valor da parcela do mês."]})]}),e("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:M.map(z=>a("div",{className:`flex items-center justify-between p-3 rounded-lg border ${z.paid?"bg-green-50 dark:bg-green-950/30 border-green-200 dark:border-green-800":"bg-amber-50 dark:bg-amber-950/30 border-amber-200 dark:border-amber-800"}`,children:[a("div",{className:"flex-1",children:[e("p",{className:"font-medium text-sm",children:z.description}),a("div",{className:"flex items-center gap-3 mt-1 flex-wrap",children:[e(ae,{variant:z.paid?"default":"secondary",className:"text-xs",children:z.paid?"â Pago":" A Pagar"}),z.installment_number&&a("span",{className:"text-xs text-muted-foreground",children:["Parcela ",z.installment_number,"/",z.total_installments]}),a("span",{className:"text-xs text-muted-foreground",children:["Venc: ",Ze(z.due_date)]})]})]}),a("div",{className:"text-right ml-4",children:[e("p",{className:"font-bold text-lg",children:ie(z.amount)}),z.monthly_equivalent_amount&&e("span",{className:"text-xs text-muted-foreground",children:"(Equiv. mensal)"})]})]},z.id))}),a("div",{className:"mt-4 p-4 bg-blue-50 dark:bg-blue-950/30 rounded-lg border border-blue-200 dark:border-blue-800",children:[a("div",{className:"flex justify-between items-center",children:[e("span",{className:"font-semibold text-blue-900 dark:text-blue-300",children:"Total de Contas do PerÃodo:"}
69),e("span",{className:"text-2xl font-bold text-blue-600 dark:text-blue-400",children:ie(M.reduce((z,X)=>z+Number(X.amount||0),0))})]}),a("p",{className:"text-xs text-blue-700 dark:text-blue-400 mt-2",children:[M.filter(z=>z.paid).length," contas pagas + ",M.filter(z=>!z.paid).length," contas a pagar"]})]})]})]})]})]}),r.current.status==="below"&&e(Yn,{recommendations:r.viability.recommendations}),!u&&m&&m.atual>0&&a(K,{className:m.diferenca>0?"border-red-200 dark:border-red-800 bg-red-50/50 dark:bg-red-950/20":"border-green-200 dark:border-green-800 bg-green-50/50 dark:bg-green-950/20",children:[e(te,{children:a(ne,{className:"flex items-center gap-2",children:[e(aa,{className:"h-5 w-5"}),"Análise de Pró-labore",m.diferenca>0?a(ae,{variant:"destructive",className:"ml-2",children:[e(Me,{className:"h-3 w-3 mr-1"}),"Atenção"]}):a(ae,{variant:"default",className:"ml-2 bg-green-600",children:[e(nt,{className:"h-3 w-3 mr-1"}),"Saudável"]})]})}),a(ee,{className:"space-y-6",children:[a("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[a("div",{className:"text-center p-4 bg-white dark:bg-card rounded-lg border",children:[e("p",{className:"text-sm text-muted-foreground mb-2",children:"Pró-labore Atual"}),e("p",{className:"text-3xl font-bold text-blue-600",children:ie(m.atual)}),a("p",{className:"text-xs text-muted-foreground mt-1",children:[Te(m.percentualReceita)," da receita"]})]}),e("div",{className:"flex items-center justify-center",children:e(Er,{className:`h-8 w-8 ${m.diferenca>0?"text-red-500":"text-green-500"}`})}),a("div",{className:"text-center p-4 bg-white dark:bg-card rounded-lg border border-green-300 dark:border-green-700",children:[e("p",{className:"text-sm text-muted-foreground mb-2",children:"Pró-labore Recomendado"}),e("p",{className:"text-3xl font-bold text-green-600",children:ie(m.saudavel)}),e("p",{className:"text-xs text-green-700 dark:text-green-400 mt-1 font-semibold",children:"Para saúde financeira"})]})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[a("div",{className:"p-4 bg-white dark:bg-card rounded-lg border",children:[a("h4",{className:"font-semibold text-sm mb-3 flex items-center gap-2",children:[e(pa,{className:"h-4 w-4 text-blue-600"}),"Com Pró-labore Atual"]}),a("div",{className:"space-y-2 text-sm",children:[a("div",{className:"flex justify-between",children:[e("span",{className:"text-muted-foreground",children:"Ponto de EquilÃbrio:"}),e("span",{className:"font-semibold",children:ie(m.impactoAtual.pontoEquilibrio)})]}),a("div",{className:"flex justify-between",children:[e("span",{className:"text-muted-foreground",children:"Lucro após retirada:"}),e("span",{className:`font-semibold ${m.impactoAtual.lucroOperacional>=0?"text-green-600":"text-red-600"}`,children:ie(m.impactoAtual.lucroOperacional)})]})]})]}),a("div",{className:"p-4 bg-green-50 dark:bg-green-950/30 rounded-lg border border-green-200 dark:border-green-800",children:[a("h4",{className:"font-semibold text-sm mb-3 flex items-center gap-2",children:[e(pa,{className:"h-4 w-4 text-green-600"}),"Com Pró-labore Recomendado"]}),a("div",{className:"space-y-2 text-sm",children:[a("div",{className:"flex justify-between",children:[e("span",{className:"text-muted-foreground",children:"Ponto de EquilÃbrio:"}),e("span",{className:"font-semibold text-green-700 dark:text-green-400",children:ie(m.impactoSaudavel.pontoEquilibrio)})]}),a("div",{className:"flex justify-between",children:[e("span",{className:"text-muted-foreground",children:"Lucro após retirada:"}),e("span",{className:"font-semibold text-green-600",children:ie(m.impactoSaudavel.lucroOperacional)})]})]})]})]}),a(Fe,{className:m.diferenca>0?"border-red-300 dark:border-red-800 bg-red-50 dark:bg-red-950/30":"border-green-300 dark:border-green-800 bg-green-50 dark:bg-green-950/30",children:[e(aa,{className:`h-4 w-4 ${m.diferenca>0?"text-red-600":"text-green-600"}`}),e(Ar,{className:m.diferenca>0?"text-red-800 dark:text-red-400":"text-green-800 dark:text-green-400",children:"Recomendação do Sistema"}),e(Ie,{className:m.diferenca>0?"text-red-700 dark:text-red-400":"text-green-700 dark:text-green-400",children:m.recomendacao})]})]})]}),a(K,{className:r.safetyMargin.benchmark==="excellent"?"bg-green-50 dark:bg-green-950/30":r.safetyMargin.benchmark==="good"?"bg-blue-50 dark:bg-blue-950/30":"bg-red-50 dark:bg-red-950/30",children:[e(te,{children:a(ne,{className:"flex items-center gap-2",children:[e(Oe,{className:"h-5 w-5"}),"Margem de Segurança"]})}),e(ee,{children:a("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[a("div",{className:"text-center",children:[e("p",{className:"text-sm text-muted-foreground mb-1",children:"Margem de Segurança"}),e("p",{className:`text-3xl font-bold ${r.safetyMargin.benchmark==="excellent"?"text-green-600":r.safetyMargin.benchmark==="good"?"text-blue-600":"text-red-600"}`,children:Te(r.safetyMargin.percentage)}),e("p",{className:"text-xs text-muted-foreground mt-1",children:r.safetyMargin.benchmark==="excellent"?"Excelente (â¥35%)":r.safetyMargin.benchmark==="good"?"Bom (â¥20%)":"CrÃtico (<20%)"})]}),a("div",{className:"text-center",children:[e("p",{className:"text-sm text-muted-foreground mb-1",children:"Valor da Margem"}),e("p",{className:"text-3xl font-bold",children:ie(r.safetyMargin.value)})]}),a("div",{className:"text-center",children:[e("p",{className:"text-sm text-muted-foreground mb-1",children:"Buffer de Receita"}),e("p",{className:"text-3xl font-bold",children:ie(r.safetyMargin.revenueBuffer)})]})]})})]}),a(K,{children:[e(te,{children:e(ne,{children:"Grau de Alavancagem Operacional (GAO)"})}),e(ee,{children:a("div",{className:"space-y-4",children:[e("div",{className:"text-center",children:a("p",{className:"text-4xl font-bold text-purple-600",children:[It(r.operatingLeverage.degree,2),"x"]})}),e(Fe,{children:e(Ie,{className:"text-center",children:r.operatingLeverage.interpretation})}),a("div",{className:"mt-4 p-4 bg-slate-50 dark:bg-slate-800/50 rounded-lg space-y-2 text-sm",children:[e("div",{className:"font-semibold text-slate-700 dark:text-slate-300 mb-2",children:"Como chegamos neste valor:"}),a("div",{className:"flex justify-between",children:[e("span",{className:"text-slate-600",children:"Receita do Mês:"}),e("span",{className:"font-semibold",children:ie(r.operatingLeverage.details.receita)})]}),a("div",{className:"flex justify-between text-orange-600",children:[e("span",{children:"(-) Custos Variáveis:"}
69),a("span",{className:"font-semibold",children:["-",ie(r.operatingLeverage.details.custosVariaveis)]})]}),a("div",{className:"border-t pt-2 flex justify-between text-blue-600",children:[e("span",{className:"font-semibold",children:"Margem de Contribuição:"}),e("span",{className:"font-bold",children:ie(r.operatingLeverage.details.margemContribuicao)})]}),a("div",{className:"flex justify-between text-red-600 mt-2",children:[e("span",{children:"(-) Custos Fixos:"}),a("span",{className:"font-semibold",children:["-",ie(r.operatingLeverage.details.custosFixos)]})]}),a("div",{className:"border-t pt-2 flex justify-between text-green-600",children:[e("span",{className:"font-semibold",children:"Lucro Operacional:"}),e("span",{className:"font-bold",children:ie(r.operatingLeverage.details.lucroOperacional)})]}),a("div",{className:"border-t mt-3 pt-3 bg-purple-50 dark:bg-purple-950/30 -mx-4 px-4 py-2 rounded",children:[e("div",{className:"text-xs text-slate-600 mb-1",children:"Fórmula do GAO:"}),a("div",{className:"text-center font-mono text-sm",children:["GAO = ",ie(r.operatingLeverage.details.margemContribuicao)," ÷ ",ie(r.operatingLeverage.details.lucroOperacional)," = ",It(r.operatingLeverage.degree,2),"x"]})]})]}),e("div",{className:"mt-4",children:r.operatingLeverage.degree<1?e(Fe,{className:"bg-amber-50 dark:bg-amber-950/30 border-amber-200 dark:border-amber-800",children:e(Ie,{children:a("div",{className:"space-y-2",children:[e("p",{className:"font-semibold text-amber-800 dark:text-amber-400",children:" Como melhorar sua alavancagem:"}),a("ul",{className:"list-disc list-inside space-y-1 text-sm text-amber-700 dark:text-amber-400",children:[a("li",{children:[e("strong",{children:"Aumentar Margem de Contribuição:"})," Reduza custos variáveis ou aumente preços (cada produto vendido gerará mais lucro)"]}),a("li",{children:[e("strong",{children:"Otimizar Custos Fixos:"})," Seus custos fixos (",ie(r.operatingLeverage.details.custosFixos),") estão consumindo muito do faturamento"]}),a("li",{children:[e("strong",{children:"Meta:"})," GAO acima de 1,5x indica boa alavancagem operacional"]})]})]})})}):r.operatingLeverage.degree>2?e(Fe,{className:"bg-green-50 dark:bg-green-950/30 border-green-200 dark:border-green-800",children:e(Ie,{children:a("p",{className:"text-sm text-green-700 dark:text-green-400",children:[" ",e("strong",{children:"Excelente!"})," Cada aumento de 10% nas vendas gera ",Te(r.operatingLeverage.degree*10)," mais lucro!"]})})}):null})]})})]}),a(K,{children:[e(te,{children:e(ne,{children:"Cenários de Projeção"})}),e(ee,{children:a("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[a("div",{className:"p-4 border rounded-lg bg-green-50 dark:bg-green-950/30",children:[e("h4",{className:"font-semibold text-green-700 dark:text-green-400 mb-3",children:"Otimista (+20%)"}),a("div",{className:"space-y-2 text-sm",children:[a("div",{className:"flex justify-between",children:[e("span",{children:"Receita:"}),e("span",{className:"font-semibold",children:ie(r.scenarios.optimistic.revenue)})]}),a("div",{className:"flex justify-between",children:[e("span",{children:"Margem Segurança:"}),e("span",{className:"font-semibold",children:Te(r.scenarios.optimistic.safetyMargin)})]}),a("div",{className:"flex justify-between",children:[e("span",{children:"Lucro:"}),e("span",{className:"font-semibold text-green-600",children:ie(r.scenarios.optimistic.profit)})]})]})]}),a("div",{className:"p-4 border rounded-lg bg-blue-50 dark:bg-blue-950/30",children:[e("h4",{className:"font-semibold text-blue-700 dark:text-blue-400 mb-3",children:"Realista (Atual)"}),a("div",{className:"space-y-2 text-sm",children:[a("div",{className:"flex justify-between",children:[e("span",{children:"Receita:"}),e("span",{className:"font-semibold",children:ie(r.scenarios.realistic.revenue)})]}),a("div",{className:"flex justify-between",children:[e("span",{children:"Margem Segurança:"}),e("span",{className:"font-semibold",children:Te(r.scenarios.realistic.safetyMargin)})]}),a("div",{className:"flex justify-between",children:[e("span",{children:"Lucro:"}),e("span",{className:`font-semibold ${r.scenarios.realistic.profit>=0?"text-green-600":"text-red-600"}`,children:ie(r.scenarios.realistic.profit)})]})]})]}),a("div",{className:"p-4 border rounded-lg bg-orange-50 dark:bg-orange-950/30",children:[e("h4",{className:"font-semibold text-orange-700 dark:text-orange-400 mb-3",children:"Pessimista (-20%)"}),a("div",{className:"space-y-2 text-sm",children:[a("div",{className:"flex justify-between",children:[e("span",{children:"Receita:"}),e("span",{className:"font-semibold",children:ie(r.scenarios.pessimistic.revenue)})]}),a("div",{className:"flex justify-between",children:[e("span",{children:"Margem Segurança:"}),e("span",{className:"font-semibold",children:Te(r.scenarios.pessimistic.safetyMargin)})]}),a("div",{className:"flex justify-between",children:[e("span",{children:"Lucro:"}),e("span",{className:`font-semibold ${r.scenarios.pessimistic.profit>=0?"text-green-600":"text-red-600"}`,children:ie(r.scenarios.pessimistic.profit)})]})]})]})]})})]})]})}function Ya(t){if(t.is_recurring)return!0;const r=t.recurrence_type||"one_time";
69return r==="monthly"||r==="annual"}function ct(t){return t.parent_recurrence_id||t.id}function Qn(t,r){const s=ct(t),n=ct(r);return s===n||t.parent_recurrence_id===r.id||r.parent_recurrence_id===t.id?!0:t.description===r.description&&(t.recurrence_type||"monthly")===(r.recurrence_type||"monthly")}function Jn(t){return t.recurrence_day&&t.recurrence_day>=1&&t.recurrence_day<=31?t.recurrence_day:t.due_date?ra(t.due_date).getDate():1}function Kn(t,r,s){const n=ra(t),m=Ha(n,r==="annual"?12:1),u=s||n.getDate(),i=new Date(m.getFullYear(),m.getMonth()+1,0).getDate(),d=Math.min(u,i);return Va(new Date(m.getFullYear(),m.getMonth(),d))}function br(t,r){const s=t==="monthly"||t==="annual";return{is_recurring:s,recurrence_day:s?ra(r).getDate():null}}function Zn(t,r){return r.some(s=>!s.paid&&Qn(s,t)&&s.due_date>t.due_date)}async function Xr(t,r){if(!Ya(t))return{created:!1};const s=t.recurrence_type==="annual"?"annual":"monthly",n=Jn(t),o=ct(t),m=Kn(t.due_date,s,n),{data:u}=await v.from("accounts_payable").select("id").eq("user_id",r).eq("paid",!1).eq("due_date",m).eq("description",t.description).eq("recurrence_type",s).limit(1);if(u&&u.length>0)return{created:!1,nextDueDate:m};const{data:i,error:d}=await v.from("accounts_payable").insert({user_id:r,description:t.description,amount:t.amount,due_date:m,competence_date:m,supplier_id:t.supplier_id||null,paid:!1,is_recurring:!0,recurrence_day:n,parent_recurrence_id:o,expense_category:t.expense_category||null,include_in_costing:t.include_in_costing??!0,recurrence_type:s,requires_regular_update:t.requires_regular_update??!1,alert_days_before:t.alert_days_before??3,bank_account_id:t.bank_account_id||null,account_type:"expense",monthly_equivalent:t.monthly_equivalent??null,monthly_equivalent_amount:t.monthly_equivalent_amount??null}).select("id").single();if(d)throw d;return await v.from("accounts_payable").update({next_recurrence_created:!0}).eq("id",t.id),{created:!0,nextDueDate:m,id:i==null?void 0:i.id}}async function eo(t,r){const s=new Map;for(const o of t){if(!Ya(o))continue;const m=o.parent_recurrence_id?o.parent_recurrence_id:`${o.description}::${o.recurrence_type||"monthly"}`,u=s.get(m)||[];u.push(o),s.set(m,u)}let n=0;for(const o of s.values()){const m=o.filter(i=>i.paid).sort((i,d)=>d.due_date.localeCompare(i.due_date))[0];if(!m||Zn(m,t))continue;const u=await Xr(m,r);u.created&&(n+=1,t.push({...m,id:u.id||`pending-${n}`,due_date:u.nextDueDate||m.due_date,paid:!1,parent_recurrence_id:ct(m)}))}return n}function fr({account:t,supplierName:r,onEdit:s,onDelete:n,onTogglePaid:o}){const u=((M,E)=>{if(E)return{label:"Paga",color:"text-green-700",bg:"bg-green-50",gradient:"from-green-500 to-green-600"};const h=tt(de(new Date,"yyyy-MM-dd")),c=tt(M),b=ws(c,h);return b<0?{label:`Vencida há ${Math.abs(b)} dias`,color:"text-red-700",bg:"bg-red-50",gradient:"from-red-500 to-red-600"}:b===0?{label:"Vence Hoje!",color:"text-orange-700",bg:"bg-orange-50",gradient:"from-orange-500 to-orange-600"}:b<=3?{label:`Vence em ${b} dias`,color:"text-yellow-700",bg:"bg-yellow-50",gradient:"from-yellow-500 to-yellow-600"}:{label:`Vence em ${b} dias`,color:"text-blue-700",bg:"bg-blue-50",gradient:"from-blue-500 to-blue-600"}})(t.due_date,t.paid),i=typeof t.amount=="number"?t.amount:parseFloat(t.amount),d=t.recurrence_type==="installment"&&(t.total_installments??0)>0,g=Ya(t),x=i,y=d?i*(t.total_installments??1):i;return a(K,{className:"overflow-hidden hover:shadow-md transition-all border-2",children:[e(te,{className:_e("p-3 bg-gradient-to-r text-white",u.gradient),children:a("div",{className:"flex items-start justify-between gap-2",children:[a("div",{className:"flex-1 min-w-0",children:[e("h3",{className:"font-semibold text-lg truncate",children:t.description}),a("div",{className:"flex items-center gap-1.5 mt-1 text-white/90",children:[t.paid?e(nt,{className:"h-3.5 w-3.5"}):e(Me,{className:"h-3.5 w-3.5"}),e("span",{className:"text-sm font-medium",children:u.label})]})]}),a("div",{className:"flex flex-col gap-1 items-end",children:[g&&a(ae,{variant:"secondary",className:"bg-white/20 text-white border-white/30 text-xs",children:[e(ha,{
69className:"h-3 w-3 mr-1"}),"Recorrente"]}),t.requires_regular_update&&e(ae,{variant:"secondary",className:"bg-white/20 text-white border-white/30 text-xs",children:"Atualizar"})]})]})}),a(ee,{className:"p-3 space-y-3",children:[a("div",{className:"grid grid-cols-2 gap-3",children:[a("div",{className:"flex items-center gap-2 p-2 bg-muted/50 rounded-md",children:[e(aa,{className:"h-4 w-4 text-green-600"}),a("div",{className:"flex-1",children:[e("div",{className:"text-xs text-muted-foreground",children:d?"Valor da Parcela":"Valor"}),a("div",{className:"font-bold text-sm",children:["R$ ",x.toFixed(2)]}),d&&a("div",{className:"text-[10px] text-muted-foreground mt-0.5",children:[t.installment_number,"/",t.total_installments]})]})]}),a("div",{className:"flex items-center gap-2 p-2 bg-muted/50 rounded-md",children:[e(je,{className:"h-4 w-4 text-blue-600"}),a("div",{children:[e("div",{className:"text-xs text-muted-foreground",children:"Vencimento"}),e("div",{className:"font-bold text-sm",children:Ze(t.due_date)})]})]})]}),d&&a("div",{className:"flex items-center gap-2 p-2 bg-blue-50 dark:bg-blue-950/30 rounded-md border border-blue-200 dark:border-blue-800",children:[e(ae,{variant:"outline",className:"text-xs bg-blue-100 dark:bg-blue-950/40 text-blue-700 dark:text-blue-400 border-blue-300 dark:border-blue-700",children:"Parcelamento"}),a("span",{className:"text-xs text-muted-foreground flex-1",children:["Valor total: ",a("span",{className:"font-semibold",children:["R$ ",y.toFixed(2)]})]})]}),r&&r!=="-"&&a("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded-md",children:[e(
69ot,{className:"h-4 w-4 text-purple-600"}),a("div",{className:"flex-1 min-w-0",children:[e("div",{className:"text-xs text-muted-foreground",children:"Fornecedor"}),e("div",{className:"font-medium text-sm truncate",children:r})]})]}),t.expense_category&&a("div",{className:"flex items-center gap-2",children:[e(ae,{variant:"outline",className:"text-xs",children:t.expense_category}),t.include_in_costing&&e(ae,{variant:"outline",className:"text-xs bg-blue-50 dark:bg-blue-950/30 text-blue-700 dark:text-blue-400",children:"Custo Fixo"})]}),a("div",{className:"grid grid-cols-3 gap-1.5 pt-2 border-t",children:[!t.paid&&a(j,{size:"sm",variant:"outline",className:"h-8 px-2 bg-green-50 dark:bg-green-950/30 hover:bg-green-100 dark:hover:bg-green-900/40 text-green-700 dark:text-green-400 border-green-300 dark:border-green-700 col-span-3",onClick:()=>o(t.id,t.paid,g),title:g?"Marcar como pago e gerar próxima recorrência":"Marcar como pago",children:[e(Ke,{className:"h-3.5 w-3.5 mr-1.5"}),g?"Pagar e Gerar Próxima":"Marcar como Pago"]}),e(j,{size:"sm",variant:"outline",className:"h-8 px-2",onClick:()=>s(t),title:"Editar",children:e($t,{className:"h-3 w-3"})}),e(j,{size:"sm",variant:"outline",className:"h-8 px-2",onClick:()=>n(t.id),title:"Excluir",children:e(ya,{className:"h-3 w-3 text-red-600"})}),t.paid&&e(j,{size:"sm",variant:"outline",className:"h-8 px-2 bg-orange-50 dark:bg-orange-950/30 hover:bg-orange-100 dark:hover:bg-orange-900/40 text-orange-700 dark:text-orange-400 border-orange-300 dark:border-orange-700",onClick:()=>o(t.id,t.paid,!1),title:"Desfazer pagamento",children:e(ha,{className:"h-3 w-3"})})]})]})]})}function Yr({value:t,onChange:r,label:s="Conta bancária (opcional)",optional:n=!0,className:o,id:m="bank_account_id"}){const{accounts:u,loading:i}=Ln();return!i&&u.length===0?e("p",{className:"text-xs text-muted-foreground",children:"Cadastre contas em Financeiro â Bancos para vincular pagamentos ao saldo."}):a("div",{className:o,children:[e(be,{htmlFor:m,children:s}),a(Ve,{value:t||"none",onValueChange:d=>r(d==="none"?"":d),disabled:i,children:[e(Le,{id:m,children:e(Be,{placeholder:i?"Carregando...":"Selecione a conta"})}),a(ze,{children:[n&&e(fe,{value:"none",children:"Não informar / outro meio"}),u.map(d=>e(fe,{value:d.id,children:a("span",{className:"inline-flex items-center gap-2",children:[e(ht,{className:"h-3.5 w-3.5 text-muted-foreground"}),d.name,d.bank_name?` â ${d.bank_name}`:"",d.is_main?" (principal)":""]})},d.id))]})]}),n&&t&&e("p",{className:"text-xs text-muted-foreground mt-1",children:"O saldo desta conta será atualizado ao confirmar o pagamento."})]})}function ao({isOpen:t,onClose:r,account:s,onSuccess:n}){const{toast:o}=Wa(),[m,u]=_.useState(!1),[i,d]=_.useState({amount_paid:0,payment_date:Zt(),payment_method:"transfer",bank_account_id:"",payment_notes:""}),[g,x]=_.useState(null);_.useEffect(()=>{if(t&&s){let c=s.amount;(s.recurrence_type==="installment"||s.installment_count)&&(c=s.monthly_equivalent||s.amount),d(b=>({...b,amount_paid:c||0,bank_account_id:s.bank_account_id||""}))}},[t,s]);const y=c=>{var N;const b=(N=c.target.files)==null?void 0:N[0];if(b){if(b.size>5*1024*1024){o({title:"Arquivo muito grande",description:"O comprovante deve ter no máximo 5MB",variant:"destructive"});return}x(b)}},M=async c=>{if(!g)return null;try{const{data:{user:b}}=await v.auth.getUser();if(!b)throw new Error("Usuário não autenticado");const N=g.name.split(".").pop(),C=`${b.id}/${c}_${Date.now()}.${N}`,{error:A}=await v.storage.from("receipts").upload(C,g);if(A)throw A;const{data:{publicUrl:f}}=v.storage.from("receipts").getPublicUrl(C);return f}catch(b){return console.error("Erro ao fazer upload do comprovante:",b),o({title:"Erro no upload",description:"Não foi possÃvel anexar o comprovante",variant:"destructive"}),null}},E=async()=>{if(s){if(i.amount_paid<=0){o({title:"Valor inválido",description:"O valor pago deve ser maior que zero",variant:"destructive"});return}u(!0);try{let c=null;g&&(c=await M(s.id));const b=new Date(i.payment_date+"T12:00:00"),N=i.bank_account_id||null,{error:C}=await v.from("accounts_payable").update({paid:!0,payment_date:i.payment_date,paid_at:b.toISOString(),payment_month:b.getMonth()+1,payment_year:b.getFullYear(),amount_paid:i.amount_paid,payment_method:i.payment_method,payment_notes:i.payment_notes,receipt_url:c,bank_account_id:N,account_type:"expense"}).eq("id",s.id);if(C)throw C;let A;if(Ya(s)){const{data:{user:f}}=await v.auth.getUser();f&&(A=(await Xr(s,f.id)).nextDueDate)}if(s.recurrence_type==="installment"&&s.installment_count){const f=s.description.match(/(\d+)\/(\d+)/);if(f){const $=parseInt(f[1]),S=parseInt(f[2]);$>
69=S?o({title:"Parcelamento concluÃdo!",description:`${s.description} - Ãltima parcela paga com sucesso!`}):o({title:"Pagamento confirmado!",description:`Parcela ${$}/${S} paga. Restam ${S-$} parcelas.`})}else o({title:"Pagamento confirmado!",description:`${s.description} pago com sucesso`})}else Ya(s)&&A?o({title:"Pagamento confirmado!",description:`${s.description} pago. Próximo vencimento: ${Ze(A)}`}):o({title:"Pagamento confirmado!",description:`${s.description} pago com sucesso`});window.dispatchEvent(new CustomEvent("accounts-payable-updated")),n(),h()}catch(c){console.error("Erro ao confirmar pagamento:",c),o({title:"Erro ao confirmar pagamento",description:c instanceof Error?c.message:"Tente novamente",variant:"destructive"})}finally{u(!1)}}},h=()=>{d({amount_paid:0,payment_date:Zt(),payment_method:"transfer",bank_account_id:"",payment_notes:""}),x(null),r()};return s?e(Ea,{open:t,onOpenChange:h,children:a(Sa,{className:"max-w-2xl max-h-[90vh]",children:[a(Pa,{children:[a(Ma,{className:"flex items-center gap-2 text-xl",children:[e(Ba,{className:"h-5 w-5 text-primary","aria-hidden":!0}),"Confirmar Pagamento"]}),e(Oa,{children:"Registre os detalhes do pagamento realizado"})]}),e(Sr,{className:"max-h-[calc(90vh-180px)] pr-4",children:a("div",{className:"space-y-4 py-4",children:[a("div",{className:"bg-gray-50 dark:bg-gray-800 p-3 rounded-lg border border-gray-200 dark:border-gray-700 space-y-1",children:[e("p",{className:"text-sm font-semibold text-gray-700 dark:text-gray-300",children:"Conta:"}),e("p",{className:"text-base font-bold",children:s.description}),s.category&&a("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:["Categoria: ",s.category]}),s.recurrence_type==="installment"||s.installment_count?a(Ee,{children:[a("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:["Valor da Parcela: R$"," ",(s.monthly_equivalent||0).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]}),a("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:[(()=>{const c=s.description.match(/(\d+)\/(\d+)/),b=c?c[1]:"?",N=s.installment_count||(c?c[2]:"?");return`Parcela ${b}/${N}`})()," - Total: R$"," ",(s.amount||0).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}):a("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:["Valor: R$"," ",(s.amount||0).toLocaleString("pt-BR",{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),a("div",{className:"border-t dark:border-gray-700 pt-4 space-y-4",children:[a("div",{children:[e(be,{htmlFor:"amount_paid",children:"Valor Pago *"}),e(Ce,{id:"amount_paid",type:"number",step:"0.01",value:i.amount_paid,onChange:c=>d({...i,amount_paid:parseFloat(c.target.value)||0}),className:"text-lg font-semibold"})]}),a("div",{children:[e(be,{htmlFor:"payment_date",children:"Data do Pagamento *"}),e(Ce,{id:"payment_date",type:"date",value:i.payment_date,onChange:c=>d({...i,payment_date:c.target.value})})]}),e(Yr,{value:i.bank_account_id,onChange:c=>d({...i,bank_account_id:c}),label:"Pago com qual conta? (opcional)"}),a("div",{children:[e(be,{htmlFor:"payment_method",children:"Forma de Pagamento"}),a(Ve,{value:i.payment_method,onValueChange:c=>d({...i,payment_method:c}),children:[e(Le,{children:e(Be,{})}),a(ze,{children:[e(fe,{value:"transfer",children:"Transferência"}),e(fe,{value:"pix",children:"PIX"}),e(fe,{value:"boleto",children:"Boleto"}),e(fe,{value:"card",children:"Cartão"}),e(fe,{value:"cash",children:"Dinheiro"})]})]})]}),a("div",{children:[e(be,{htmlFor:"receipt",children:"Comprovante (opcional)"}),a("div",{className:"flex items-center gap-2",children:[e(Ce,{id:"receipt",type:"file",accept:".pdf,.jpg,.jpeg,.png",onChange:y,className:"hidden"}),a(j,{type:"button",variant:"outline",size:"sm",onClick:()=>{var c;return(c=document.getElementById("receipt"))==null?void 0:c.click()},className:"w-full",children:[e(qt,{className:"h-4 w-4 mr-2"}),g?g.name:"Anexar arquivo"]}),g&&e(j,{type:"button",variant:"ghost",size:"sm",onClick:()=>x(null),children:e(rs,{className:"h-4 w-4"})})]}),e("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:"PDF, JPG ou PNG (máx. 5MB)"})]}),a("div",{children:[e(be,{htmlFor:"notes",children:"Observações"}),e(Cs,{id:"notes",value:i.payment_notes,onChange:c=>d({...i,payment_notes:c.target.value}),placeholder:"Informações adicionais sobre o pagamento...",rows:3})]})]})]})}),a(Tt,{className:"mt-4",children:[e(j,{variant:"outline",onClick:h,disabled:m,children:"Cancelar"}),e(j,{onClick:E,disabled:m,children:m?a(Ee,{children:[e(ba,{className:"mr-2 h-4 w-4 animate-spin"}),"Processando..."]}):"Confirmar Pagamento"})]})]})}):null}function to({open:t,onOpenChange:r,title:s,description:n,type:o="delete",confirmText:m,cancelText:u="Cancelar",onConfirm:i,details:d=[]}){const g=o==="delete";return e(bt,{open:t,onOpenChange:r,children:a(ft,{className:"max-w-md",children:[a(xt,{children:[a("div",{className:"flex items-center gap-3 mb-2",children:[e("div",{className:`p-2 rounded-full ${g?"bg-red-100 dark:bg-red-950":"bg-blue-100 dar
69k:bg-blue-950"}`,children:g?e(ya,{className:"h-5 w-5 text-red-600 dark:text-red-400"}):e(Pr,{className:"h-5 w-5 text-blue-600 dark:text-blue-400"})}),e(vt,{className:"text-xl",children:s})]}),e(yt,{className:"text-base leading-relaxed pt-2",children:n})]}),d.length>0&&e("div",{className:"space-y-2 py-4 border-t border-b",children:d.map((x,y)=>a("div",{className:"flex justify-between items-center",children:[e("span",{className:"text-sm text-muted-foreground",children:x.label}),e(ae,{variant:"outline",className:"font-semibold",children:x.value})]},y))}),a(Nt,{className:"gap-2 sm:gap-2",children:[e(_t,{className:"m-0",children:u}),e(Ta,{onClick:i,className:g?"bg-red-600 hover:bg-red-700 text-white":"bg-blue-600 hover:bg-blue-700 text-white",children:m||(g?"Excluir":"Confirmar")})]})]})})}function ro({open:t,onOpenChange:r,installmentNumber:s,totalInstallments:n,description:o,unpaidCount:m,onDeleteAll:u,onDeleteOne:i}){return e(bt,{open:t,onOpenChange:r,children:a(ft,{className:"max-w-lg",children:[a(xt,{children:[a("div",{className:"flex items-center gap-3 mb-2",children:[e("div",{className:"p-2 rounded-full bg-red-100 dark:bg-red-950",children:e(na,{className:"h-5 w-5 text-red-600 dark:text-red-400"})}),e(vt,{className:"text-xl",children:"Excluir Parcelamento"})]}),a(yt,{className:"text-base leading-relaxed pt-2",children:["Esta é a parcela ",a("strong",{children:[s,"/",n]}),' de "',o,'".']})]}),a("div",{className:"space-y-3 py-4 border-t border-b",children:[a("div",{className:"flex justify-between items-center p-3 bg-orange-50 dark:bg-orange-950/30 rounded-lg border border-orange-200 dark:border-orange-800",children:[e("span",{className:"text-sm font-medium",children:"Parcelas em aberto"}),a(ae,{variant:"outline",className:"bg-orange-100 text-orange-700 border-orange-300",children:[m," pendentes"]})]}),a("div",{className:"text-sm text-muted-foreground bg-blue-50 dark:bg-blue-950/30 p-3 rounded-lg border border-blue-200 dark:border-blue-800",children:[e("p",{className:"font-medium text-blue-900 dark:text-blue-100 mb-1",children:" O que você deseja fazer?"}),a("ul",{className:"space-y-1 text-xs text-blue-800 dark:text-blue-200",children:[a("li",{children:["⢠",e("strong",{children:"Excluir todas"}),": Remove as ",m," parcelas pendentes"]}),a("li",{children:["⢠",e("strong",{children:"Excluir apenas esta"}),": Remove só a parcela ",s]})]})]})]}),a(Nt,{className:"gap-2 sm:gap-2 flex-col sm:flex-row",children:[e(_t,{className:"m-0 sm:flex-1",children:"Cancelar"}),e(Ta,{onClick:i,className:"bg-orange-600 hover:bg-orange-700 text-white m-0 sm:flex-1",children:"Excluir apenas esta"}),a(Ta,{onClick:u,className:"bg-red-600 hover:bg-red-700 text-white m-0 sm:flex-1",children:["Excluir todas (",m,")"]})]})]})})}function so({open:t,onOpenChange:r,installmentNumber:s,totalInstallments:n,unpaidCount:o,onEditAll:m,onEditOne:u}){return e(bt,{open:t,onOpenChange:r,children:a(ft,{className:"max-w-lg",children:[a(xt,{children:[a("div",{className:"flex items-center gap-3 mb-2",children:[e("div",{className:"p-2 rounded-full bg-blue-100 dark:bg-blue-950",children:e(Pr,{className:"h-5 w-5 text-blue-600 dark:text-blue-400"})}),e(vt,{className:"text-xl",children:"Atualizar Parcelamento"})]}),a(yt,{className:"text-base leading-relaxed pt-2",children:["Esta é a parcela ",a("strong",{children:[s,"/",n]}),"."]})]}),a("div",{className:"space-y-3 py-4 border-t border-b",children:[a("div",{className:"flex justify-between items-center p-3 bg-blue-50 dark:bg-blue-950/30 rounded-lg border border-blue-200 dark:border-blue-800",children:[e("span",{className:"text-sm font-medium",children:"Parcelas em aberto"}),a(ae,{variant:"outline",className:"bg-blue-100 text-blue-700 border-blue-300",children:[o," pendentes"]})]}),a("div",{className:"text-sm text-muted-foreground bg-amber-50 dark:bg-amber-950/30 p-3 rounded-lg border border-amber-200 dark:border-amber-800",children:[e("p",{className:"font-medium text-amber-900 dark:text-amber-100 mb-1",children:" O que você deseja fazer?"}),a("ul",{className:"space-y-1 text-xs text-amber-800 dark:text-amber-200",children:[a("li",{children:["⢠",e("strong",{children:"Atualizar todas"}),": Aplica as mudanças nas ",o," parcelas pendentes"]}),a("li",{children:["⢠",e("strong",{children:"Atualizar apenas esta"}),": Modifica só a parcela ",s]})]})]})]}),a(Nt,{className:"gap-2 sm:gap-2 flex-col sm:flex-row",children:[e(_t,{className:"m-0 sm:flex-1",children:"Cancelar"}),e(Ta,{onClick:u,className:"bg-orange-600 hover:bg-orange-700 text-white m-0 sm:flex-1",children:"Apenas esta"}),a(Ta,{onClick:m,className:"bg-blue-600 hover:bg-blue-700 text-white m-0 sm:flex-1",children:["Todas (",o,")"]})]})]})})}const no=[{month:1,day:1},{month:4,day:21},{month:5,day:1},{month:9,day:7},{month:10,day:12},{month:11,day:2},{month:11,day:15},{month:12,day:25}],oo=t=>{const r=t.getMonth()+1,s=t.getDate();return no.some(n=>n.month===r&&n.day===s)},io=t=>zr(t)===0,lo=t=>!io(t)&&!oo(t),St=(t,r)=>{let s=0,n=qa(new Date(t,r,1));for(;s<5;){if(lo(n)&&(s++,s===5))return zr(n)===0?rr(n,-2):n;n=rr(n,1)}return n};function co({onSyncComplete:t}){const{user:r}=ss(),[s,n]=_.useState(!1),[o,m]=_.useState(!1),[u,i]=_.useState(null),d=(E,h)=>{const c=new Date,b=new Date(h),N=c.getMonth(),C=c.getFullYear();if(b.getMonth()===N&&b.getFullYear()===C){const A=sr(c),f=b.getDate(),$=c.getDate()-f+1;return $>=15?{amount:E,isProportional:!1,workedDays:$,totalDays:A}:{amount:0,isProportional:!0,workedDays:$,totalDays:A,skipThisMonth:!0}}if(b.getFullYear()===C||b.getFullYear()===C-1){const A=b.getDate();if(b.getMonth()===N-1&&A>15){const f=sr(b)-A+1;return{amount:E/30*f,isProportional:!0,workedDays:f,totalDays:30}}}return{amount:E,isProportional:!1,workedDays:0,totalDays:0}},g=(E,h)=>{const c=E/12*h;return{total:c,firstInstallment:c/2,secondInstallment:c/2}},x=E=>{const h=new Date(E),c=new Date,b=c.getFullYear();if(h.getFullYear()!==b)return 12;const N=h.getMonth(),C=c.getMonth(),A=h.getDate();let f=C-N+1;return A>15&&f--,Math.max(0,f)},y=async(E=!1)=>
69{if(r){n(!0);try{const{data:h,error:c}=await v.from("employees").select("id, name, salary, department, created_at").eq("user_id",r.id).neq("department","production").gt("salary",0);if(c)throw c;if(!h||h.length===0){ue.info("Nenhum funcionário administrativo encontrado",{description:"Apenas funcionários não-produção são sincronizados automaticamente"}),n(!1);return}const b=new Date,N=b.getMonth(),C=b.getFullYear(),A=St(C,N);let f,$;if(b>A?(f=Ha(b,1),$=St(f.getFullYear(),f.getMonth())):(f=b,$=A),!E){const{data:Y}=await v.from("accounts_payable").select("id, description").eq("user_id",r.id).eq("expense_category","employee_salary").gte("due_date",de(new Date(f.getFullYear(),f.getMonth(),1),"yyyy-MM-dd")).lte("due_date",de(new Date(f.getFullYear(),f.getMonth()+1,0),"yyyy-MM-dd")),P=h.some(w=>d(w.salary,w.created_at).isProportional);if(Y&&Y.length>0){i({count:Y.length,month:de(f,"MMMM/yyyy",{locale:Fa}),hasProportional:P}),m(!0),n(!1);return}}let S=0,Z=0,z=0,X=0;for(const Y of h){const P=d(Y.salary,Y.created_at);if(P.skipThisMonth){const I=Ha(f,1),U=St(I.getFullYear(),I.getMonth()),{data:se}=await v.from("accounts_payable").select("id").eq("user_id",r.id).eq("expense_category","employee_salary").ilike("description",`%Salário - ${Y.name}%`).not("description","ilike","%13º%").gte("due_date",de(new Date(I.getFullYear(),I.getMonth(),1),"yyyy-MM-dd")).lte("due_date",de(new Date(I.getFullYear(),I.getMonth()+1,0),"yyyy-MM-dd")).maybeSingle();if(!se){const ce={user_id:r.id,description:`Salário - ${Y.name} (${xa(Y.department)})`,amount:Y.salary,due_date:de(U,"yyyy-MM-dd"),expense_category:"employee_salary",paid:!1,is_recurring:!0,recurrence_type:"monthly",recurrence_day:U.getDate()};await v.from("accounts_payable").insert(ce),X++}const le=f.getMonth();if(le===10||le===11){const ce=x(Y.created_at);if(ce>0){const R=g(Y.salary,ce);if(new Date(Y.created_at)>new Date(f.getFullYear(),10,30)){const F=new Date(f.getFullYear(),11,20),W=`13º Salário - ${Y.name} (${xa(Y.department)}) - ${ce}/12 avos`,{data:D}=await v.from("accounts_payable").select("id").eq("user_id",r.id).eq("expense_category","employee_salary").ilike("description",`%13º Salário%${Y.name}%`).gte("due_date",de(new Date(f.getFullYear(),11,1),"yyyy-MM-dd")).lte("due_date",de(new Date(f.getFullYear(),11,31),"yyyy-MM-dd")).maybeSingle();D||(await v.from("accounts_payable").insert({user_id:r.id,description:W,amount:R.total,due_date:de(F,"yyyy-MM-dd"),expense_category:"employee_salary",is_recurring:!1,recurrence_type:"one_time",paid:!1}),z++)}else{const F=new Date(f.getFullYear(),10,30),W=`13º Salário (1ª Parcela) - ${Y.name} (${xa(Y.department)}) - ${ce}/12 avos`,{data:D}=await v.from("accounts_payable").select("id").eq("user_id",r.id).eq("expense_category","employee_salary").ilike("description",`%13º Salário (1ª Parcela) - ${Y.name}%`).gte("due_date",de(new Date(f.getFullYear(),10,1),"yyyy-MM-dd")).lte("due_date",de(new Date(f.getFullYear(),10,30),"yyyy-MM-dd")).maybeSingle();D||(await v.from("accounts_payable").insert({user_id:r.id,description:W,amount:R.firstInstallment,due_date:de(F,"yyyy-MM-dd"),expense_category:"employee_salary",is_recurring:!1,recurrence_type:"one_time",paid:!1}),z++);const re=new Date(f.getFullYear(),11,20),k=`13º Salário (2ª Parcela) - ${Y.name} (${xa(Y.department)}) - ${ce}/12 avos`,{data:ke}=await v.from("accounts_payable").select("id").eq("user_id",r.id).eq("expense_category","employee_salary").ilike("description",`%13º Salário (2ª Parcela) - ${Y.name}%`).gte("due_date",de(new Date(f.getFullYear(),11,1),"yyyy-MM-dd")).lte("due_date",de(new Date(f.getFullYear(),11,31),"yyyy-MM-dd")).maybeSingle();ke||(await v.from("accounts_payable").insert({user_id:r.id,description:k,amount:R.secondInstallment,due_date:de(re,"yyyy-MM-dd"),expense_category:"employee_salary",is_recurring:!1,recurrence_type:"one_time",paid:!1}),z++)}}}continue}const w=P.isProportional?`Salário - ${Y.name} (${xa(Y.department)}) - Proporcional ${P.workedDays}/${P.totalDays} dias`:`Salário - ${Y.name} (${xa(Y.department)})`,{data:O}=await v.from("accounts_payable").select("id").eq("user_id",r.id).eq("expense_category","employee_salary").ilike("description",`%Salário - ${Y.name}%`).not("description","ilike","%13º%").gte("due_date",de(new Date(f.getFullYear(),f.getMonth(),1),"yyyy-MM-dd")).lte("due_date",de(new Date(f.getFullYear(),f.getMonth()+1,0),"yyyy-MM-dd")).maybeSingle();if(O){const I={description:w,amount:P.amount,due_date:de($,"yyyy-MM-dd"),is_recurring:!P.isProportional,recurrence_type:P.isProportional?"one_time":"monthly"};P.isProportional||(I.recurrence_day=$.getDate()),await v.from("accounts_payable").update(I).eq("id",O.id),Z++}else{const I={user_id:r.id,description:w,amount:P.amount,due_date:de($,"yyyy-MM-dd"),expense_category:"employee_salary",is_recurring:!P.isProportional,recurrence_type:P.isProportional?"one_time":"monthly",paid:!1};P.isProportional||(I.recurrence_day=$.getDate()),await v.from("accounts_payable").insert(I),S++}
69const H=f.getMonth();if(H===10||H===11){const I=x(Y.created_at);if(I>0){const U=g(Y.salary,I);if(new Date(Y.created_at)>new Date(f.getFullYear(),10,30)){const ce=new Date(f.getFullYear(),11,20),R=`13º Salário - ${Y.name} (${xa(Y.department)}) - ${I}/12 avos`,{data:pe}=await v.from("accounts_payable").select("id").eq("user_id",r.id).eq("expense_category","employee_salary").ilike("description",`%13º Salário%${Y.name}%`).gte("due_date",de(new Date(f.getFullYear(),11,1),"yyyy-MM-dd")).lte("due_date",de(new Date(f.getFullYear(),11,31),"yyyy-MM-dd")).maybeSingle();pe?await v.from("accounts_payable").update({description:R,amount:U.total,due_date:de(ce,"yyyy-MM-dd")}).eq("id",pe.id):(await v.from("accounts_payable").insert({user_id:r.id,description:R,amount:U.total,due_date:de(ce,"yyyy-MM-dd"),expense_category:"employee_salary",is_recurring:!1,recurrence_type:"one_time",paid:!1}),z++)}else{const ce=new Date(f.getFullYear(),10,30),R=`13º Salário (1ª Parcela) - ${Y.name} (${xa(Y.department)}) - ${I}/12 avos`,{data:pe}=await v.from("accounts_payable").select("id").eq("user_id",r.id).eq("expense_category","employee_salary").ilike("description",`%13º Salário (1ª Parcela) - ${Y.name}%`).gte("due_date",de(new Date(f.getFullYear(),10,1),"yyyy-MM-dd")).lte("due_date",de(new Date(f.getFullYear(),10,30),"yyyy-MM-dd")).maybeSingle();pe?await v.from("accounts_payable").update({description:R,amount:U.firstInstallment,due_date:de(ce,"yyyy-MM-dd")}).eq("id",pe.id):(await v.from("accounts_payable").insert({user_id:r.id,description:R,amount:U.firstInstallment,due_date:de(ce,"yyyy-MM-dd"),expense_category:"employee_salary",is_recurring:!1,recurrence_type:"one_time",paid:!1}),z++);const B=new Date(f.getFullYear(),11,20),F=`13º Salário (2ª Parcela) - ${Y.name} (${xa(Y.department)}) - ${I}/12 avos`,{data:W}=await v.from("accounts_payable").select("id").eq("user_id",r.id).eq("expense_category","employee_salary").ilike("description",`%13º Salário (2ª Parcela) - ${Y.name}%`).gte("due_date",de(new Date(f.getFullYear(),11,1),"yyyy-MM-dd")).lte("due_date",de(new Date(f.getFullYear(),11,31),"yyyy-MM-dd")).maybeSingle();W?await v.from("accounts_payable").update({description:F,amount:U.secondInstallment,due_date:de(B,"yyyy-MM-dd")}).eq("id",W.id):(await v.from("accounts_payable").insert({user_id:r.id,description:F,amount:U.secondInstallment,due_date:de(B,"yyyy-MM-dd"),expense_category:"employee_salary",is_recurring:!1,recurrence_type:"one_time",paid:!1}),z++)}}}}const me=h.filter(Y=>{const P=d(Y.salary,Y.created_at);return P.isProportional&&!P.skipThisMonth}).length,we=[];S>0&&we.push(`${S} criado(s)`),Z>
690&&we.push(`${Z} atualizado(s)`),X>0&&we.push(`${X} mês seguinte`),me>0&&we.push(`${me} proporcional(is)`),z>0&&we.push(`${z} 13º salário`),ue.success(" Salários sincronizados!",{description:`${we.join(" ⢠")} | Vencimento: ${Ze($)}`}),t==null||t()}catch(h){console.error(" Erro ao sincronizar salários:",h),ue.error("Erro ao sincronizar salários")}finally{n(!1)}}},M=async()=>{m(!1),await y(!0)};return a(Ee,{children:[a(j,{onClick:()=>y(),disabled:s,variant:"outline",size:"sm",children:[e(ha,{className:`h-4 w-4 mr-2 ${s?"animate-spin":""}`}),s?"Sincronizando...":"Atualizar Salários"]}),e(bt,{open:o,onOpenChange:m,children:a(ft,{className:"max-w-md",children:[a(xt,{children:[a("div",{className:"flex items-center gap-3 mb-2",children:[e("div",{className:"h-12 w-12 rounded-full bg-blue-100 flex items-center justify-center",children:e(Aa,{className:"h-6 w-6 text-blue-600"})}),e("div",{children:e(vt,{className:"text-xl",children:"Salários já sincronizados"})})]}),e(yt,{asChild:!0,children:a("div",{className:"text-base space-y-3 pt-2",children:[a("div",{className:"flex items-start gap-2",children:[e(je,{className:"h-5 w-5 text-muted-foreground mt-0.5"}),a("span",{className:"font-medium text-foreground",children:["Já existem ",u==null?void 0:u.count," conta(s) de salário para ",u==null?void 0:u.month]})]}),(u==null?void 0:u.hasProportional)&&a("div",{className:"flex items-start gap-2 bg-amber-50 p-3 rounded-lg border border-amber-200",children:[e(aa,{className:"h-5 w-5 text-amber-600 mt-0.5 flex-shrink-0"}),a("div",{className:"text-sm",children:[e("div",{className:"font-medium text-amber-900",children:"Atenção: Salários proporcionais"}),e("div",{className:"text-amber-700",children:"Alguns funcionários têm salário proporcional aos dias trabalhados no mês."})]})]}),a("div",{className:"text-muted-foreground pt-2",children:["O sistema vai ",e("strong",{children:"atualizar"})," os salários existentes e ",e("strong",{children:"criar"})," contas para novos funcionários."]})]})})]}),a(Nt,{children:[e(_t,{children:"Cancelar"}),e(Ta,{onClick:M,className:"bg-blue-600 hover:bg-blue-700",children:"Sim, atualizar salários"})]})]})})]})}function xa(t){return{production:"Produção",design:"Design",marketing:"Marketing",sales:"Vendas",administrative:"Administrativo",supp
69ort:"Suporte"}[t]||t}async function mo(t){const{data:r}=await v.auth.getUser();if(!r.user)throw new Error("Usuário não autenticado");const{data:s,error:n}=await v.from("accounts_payable").select(` 70 *, 71 bank_accounts:bank_account_id(name), 72 suppliers(name) 73 `).eq("user_id",r.user.id).not("payment_date","is",null).gte("payment_date",t.startDate).lte("payment_date",t.endDate).order("payment_date",{ascending:!0});if(n)throw n;const{data:o,error:m}=await v.from("sales").select("id, total_amount, created_at").eq("user_id",r.user.id).is("cancelled_at",null).gte("created_at",t.startDate).lte("created_at",t.endDate).order("created_at",{ascending:!0});if(m)throw m;const{data:u}=await v.from("bank_accounts").select("*").eq("user_id",r.user.id).eq("is_active",!0);let i=0;if(u)for(const c of u){const{data:b}=await v.rpc("calculate_bank_balance",{p_account_id:c.id,p_up_to_date:t.startDate});i+=b||0}const d=(s||[]).map(c=>{var b;return{transaction_date:c.payment_date,description:c.description,amount:c.amount,account_type:c.account_type||"expense",bank_account_name:(b=c.bank_accounts)==null?void 0:b.name,is_revenue:c.account_type==="revenue"}}),g=(o||[]).map(c=>({transaction_date:c.created_at,description:`Venda #${c.id.substring(0,8)}`,amount:Number(c.total_amount),account_type:"revenue",bank_account_name:void 0,is_revenue:!0})),x=[...d,...g].sort((c,b)=>new Date(c.transaction_date).getTime()-new Date(b.transaction_date).getTime()),y=x.filter(c=>c.is_revenue).reduce((c,b)=>c+Number(b.monthly_equivalent??b.amount),0),M=x.filter(c=>!c.is_revenue).reduce((c,b)=>c+Number(b.monthly_equivalent??b.amount),0),E=y-M,h=i+E;return{period:`${Ze(t.startDate)} - ${Ze(t.endDate)}`,total_revenue:y,total_expense:M,net_flow:E,initial_balance:i,final_balance:h,entries:x}}async function Wr(t){const{data:r}=await v.auth.getUser();if(!r.user)throw new Error("Usuário não autenticado");const{data:s,error:n}=await v.from("accounts_payable").select("*").eq("user_id",r.user.id).not("competence_date","is",null).gte("competence_date",t.startDate).lte("competence_date",t.endDate).order("competence_date",{ascending:!0});if(n)throw n;const{data:o,error:m}=await v.from("sales").select("id, subtotal, created_at").eq("user_id",r.user.id).is("cancelled_at",null).gte("created_at",t.startDate).lte("created_at",t.endDate).order("created_at",{ascending:!0});if(m)throw m;const u=(s||[]).map(f=>({competence_date:f.competence_date,description:f.description,amount:f.amount,cost_classification:f.cost_classification||"despesa_fixa"})),i=(o||[]).reduce((f,$)=>f+Number($.subtotal),0),d=(s||[]).filter(f=>f.cost_classification==="custo_variavel").reduce((f,$)=>f+Number($.monthly_equivalent??$.amount),0),g=(s||[]).filter(f=>f.cost_classification==="custo_fixo").reduce((f,$)=>f+Number($.monthly_equivalent??$.amount),0),x=(s||[]).filter(f=>f.cost_classification==="despesa_fixa").reduce((f,$)=>f+Number($.monthly_equivalent??$.amount),0),y=(s||[]).filter(f=>f.cost_classification==="despesa_variavel").reduce((f,$)=>f+Number($.monthly_equivalent??$.amount),0),M=(s||[]).filter(f=>f.account_type==="prolabore").reduce((f,$)=>f+Number($.monthly_equivalent??$.amount),0),E=i-d,h=i>0?E/i*100:0,c=E-g-x-y-M,b=i>0?c/i*100:0,N=As(t.startDate),C=N.getFullYear(),A=N.getMonth()+1;return{period:`${de(N,"MMMM/yyyy",{locale:Fa})}`,year:C,month:A,total_revenue:i,total_variable_cost:d,contribution_margin:E,contribution_margin_percent:h,total_fixed_cost:g,total_fixed_expense:x,total_variable_expense:y,total_prolabore:M,operational_result:c,operational_margin_percent:b,entries:u}}async function uo(){const{data:t}=await v.auth.getUser();if(!t.user)throw new Error("Usuário não autenticado");const{data:r}=await v.from("bank_accounts").select("*").eq("user_id",t.user.id).eq("is_active",!0).order("is_main",{ascending:!1}),s=(r||[]).reduce((A,f)=>A+Number(f.current_balance),0),{data:n}=await v.from("accounts_payable").select("amount").eq("user_id",t.user.id).eq("paid",!1).in("account_type",["expense","investment","prolabore"]),o=(n||[]).reduce((A,f)=>A+Number(f.monthly_equivalent??f.amount),0),{data:m}=await v.from("accounts_payable").select("amount").eq("user_id",t.user.id).eq("paid",!1).eq("account_type","revenue"),u=(m||[]).reduce((A,f)=>A+Number(f.monthly_equivalent??f.amount),0),i=de(new Date,"yyyy-MM-dd"),{count:d}=await v.from("accounts_payable").select("*",{count:"exact",head:!0}).eq("user_id",t.user.id).eq("paid",!1).lt("due_date",i),{count:g}=await v.from("accounts_payable").select("*",{count:"exact",head:!0}).eq("user_id",t.user.id).eq("paid",!1).eq("due_date",i),{count:x}=await v.from("accounts_payable").select("*",{count:"exact",head:!0}).eq("user_id",t.user.id).eq("paid",!1).gte("due_date",i).lte("due_date",de(new Date(Date.now()+7*24*60*60*1e3),"yyyy-MM-dd")),y=[];for(let A=5;A>=0;A--){const f=new Date;f.setMonth(f.getMonth()-A);const $=de(qa(f),"yyyy-MM-dd"),S=de(Xa(f),"yyyy-MM-dd"),{data:Z}=await v.from("accounts_payable").select("amount").eq("user_id",t.user.id).eq("account_type","revenue").not("payment_date","is",null).gte("payment_date",$).lte("payment_date",S),{data:z}=await v.from("accounts_payable").select("amount").eq("user_id",t.user.id).in("account_type",["expense","investment","prolabore"]).not("payment_date","is",null).gte("payment_date",$).lte("payment_date",S),X=(Z||[]).reduce((we,Y)=>we+Number(Y.amount),0),me=(z||[]).reduce((we,Y)=>we+Number(Y.amount),0);y.push({label:de(f,"MMM/yy",{locale:Fa}),revenue:X,expense:me,balance:X-me})}const M=de(qa(new Date),"yyyy-MM-dd"),E=de(Xa(new Date),"yyyy-MM-dd"),h=await Wr({startDate:M,endDate:E}),{data:c}=await v.from("accounts_payable").select("cost_center, amount").eq("user_id",t.user.id).not("competence_date","is",null).gte("competence_date",M).lte("competence_date",E).not("cost_center","is",null),b={};
73(c||[]).forEach(A=>{A.cost_center&&(b[A.cost_center]=(b[A.cost_center]||0)+Number(A.amount))});const N=Object.values(b).reduce((A,f)=>A+f,0),C=Object.entries(b).map(([A,f])=>({cost_center:A,total:f,percentage:N>0?f/N*100:0}));return{total_bank_balance:s,total_pending_payables:o,total_pending_receivables:u,bank_accounts:r||[],overdue_count:d||0,due_today_count:g||0,due_this_week_count:x||0,cash_flow_chart:{labels:y.map(A=>A.label),revenue:y.map(A=>A.revenue),expense:y.map(A=>A.expense),balance:y.map(A=>A.balance)},dre_chart:{revenue:h.total_revenue,variable_costs:h.total_variable_cost,fixed_costs:h.total_fixed_cost,expenses:h.total_fixed_expense+h.total_variable_expense,profit:h.operational_result},by_cost_center:C}}async function po(){const{data:t}=await v.auth.getUser();if(!t.user)throw new Error("Usuário não autenticado");const{data:r,error:s}=await v.from("bank_accounts").select("*").eq("user_id",t.user.id).order("is_main",{ascending:!1}).order("name");if(s)throw s;return r||[]}async function go(t){const{data:r}=await v.auth.getUser();if(!r.user)throw new Error("Usuário não autenticado");const{data:s,error:n}=await v.from("bank_accounts").insert({...t,user_id:r.user.id,current_balance:t.initial_balance}).select().single();if(n)throw n;return s}async function ho(t,r){const{data:s,error:n}=await v.from("bank_accounts").update({...r,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(n)throw n;return s}function dt(t){return t&&typeof t=="object"&&"message"in t?String(t.message):"Erro desconhecido"}async function bo(t){var u;const{data:r}=await v.auth.getUser();if(!r.user)throw new Error("Usuário não autenticado");const{error:s}=await v.rpc("delete_bank_account_safe",{p_account_id:t});if(!s)return;if(s.code!=="PGRST202"&&!((u=s.message)!=null&&u.includes("delete_bank_account_safe")))throw new Error(dt(s));const n=r.user.id;await v.from("accounts_payable").update({bank_account_id:null}).eq("bank_account_id",t).eq("user_id",n),await v.from("accounts_payable").update({payment_account_id:null}).eq("payment_account_id",t).eq("user_id",n),await v.from("cash_movements").delete().eq("bank_account_id",t).eq("user_id",n),await v.from("financial_transfers").delete().eq("user_id",n).or(`from_account_id.eq.${t},to_account_id.eq.${t}`);const{data:o,error:m}=await v.from("bank_accounts").delete().eq("id",t).eq("user_id",n).select("id");if(m)throw new Error(dt(m));if(!(o!=null&&o.length))throw new Error("Conta não encontrada ou sem permissão para excluir")}async function fo(t){var m;const{data:r}=await v.auth.getUser();if(!r.user)throw new Error("Usuário não autenticado");const{error:s}=await v.rpc("delete_accounts_payable_safe",{p_account_id:t});if(!s)return;if(s.code!=="PGRST202"&&!((m=s.message)!=null&&m.includes("delete_accounts_payable_safe")))throw new Error(dt(s));await v.from("account_value_history").delete().eq("account_id",t).eq("user_id",r.user.id);const{data:n,error:o}=await v.from("accounts_payable").delete().eq("id",t).eq("user_id",r.user.id).select("id");if(o)throw new Error(dt(o));if(!(n!=null&&n.length))throw new Error("Conta não encontrada ou sem permissão para excluir")}async function Qr(t){const{data:r,error:s}=await v.rpc("update_bank_balance",{p_account_id:t});if(s)throw s;const{data:n}=await v.from("bank_accounts").select("current_balance").eq("id",t).single();return(n==null?void 0:n.current_balance)||0}async function xo(t){const{data:r}=await v.auth.getUser();if(!r.user)throw new Error("Usuário não autenticado");const{error:s}=await v.from("financial_transfers").insert({...t,user_id:r.user.id,transfer_fee:t.transfer_fee||0});if(s)throw s}async function vo(t,r){const s=await Qr(t),n=r-s;let o="";return Math.abs(n)<.01?o="Saldo conciliado! Não há diferenças significativas.":n>0?o=`Há R$ ${n.toFixed(2)} a mais na conta real. Verifique se há receitas não lançadas.`:o=`Há R$ ${Math.abs(n).toFixed(2)} a menos na conta real. Verifique se há despesas não lançadas.`,{difference:n,suggestion:o}}async function Jr(){const{data:t}=await v.auth.getUser();if(!t.user)throw new Error("Usuário não autenticado");const r=new Date,s=de(qa(r),"yyyy-MM-dd"),n=de(Xa(r),"yyyy-MM-dd"),{data:o,error:m}=await v.from("accounts_payable").select("*").eq("user_id",t.user.id).or(`and(competence_date.gte.${s},competence_date.lte.${n}),and(competence_date.is.null,due_date.gte.${s},due_date.lte.${n})`);m&&console.error("â [getMonthlyPricingCosts] Erro ao buscar contas:",m);const{data:u,error:i}=await v.from("prolabore_partners").select("amount").eq("user_id",t.user.id).eq("active",!0);i&&console.error("â [getMonthlyPricingCosts] Erro ao buscar pró-labore:",i);const d=(u||[]).reduce((A,f)=>A+Number(f.amount),0);let g=0,x=0,y=0,M=0,E=0,h=0,c=0;
73(o||[]).forEach(A=>{const f=Number(A.amount);let $=A.expense_category;if(!$||$===null||$===""){h+=f,console.warn(`â ï¸ Conta "${A.description}" sem expense_category - incluindo em other_fixed`);return}switch($){case"rent":g+=f;break;case"electricity":case"water":case"internet":case"phone":x+=f;break;case"insurance":y+=f;break;case"accounting":M+=f;break;case"marketing":E+=f;break;case"supplies":case"transport":c+=f;break;default:A.recurrence_type==="monthly"?h+=f:c+=f}});const b=g+x+y+M+h,N=E+c,C=b+N+d;return{fixed_costs:b,variable_costs:N,prolabore_total:d,total_costs_to_allocate:C,breakdown:{rent:g,utilities:x,insurance:y,accounting:M,marketing:E,prolabore:d,other_fixed:h,other_variable:c}}}async function yo(){const t=await Jr(),r=160,s=25,n=8.5,o=50,m=t.total_costs_to_allocate/r,u=m/60,i=t.total_costs_to_allocate/o;return{total_costs_to_allocate:t.total_costs_to_allocate,cost_per_hour:m,cost_per_minute:u,cost_per_unit_average:i,monthly_hours:r,labor_cost_per_hour:s,tax_rate:n,legacy_format:{fixedCosts:{rent:t.breakdown.rent,utilities:t.breakdown.utilities,insurance:t.breakdown.insurance,accounting:t.breakdown.accounting,marketing:t.breakdown.marketing}}}}const Da={getCashFlowReport:mo,getDREReport:Wr,getFinancialDashboard:uo,getBankAccounts:po,createBankAccount:go,updateBankAccount:ho,deleteBankAccount:bo,deleteAccountsPayable:fo,refreshBankBalance:Qr,createTransfer:xo,reconcileBankAccount:vo,getMonthlyPricingCosts:Jr,getPricingAllocationData:yo},xr=[{value:"rent",label:"Aluguel/CondomÃnio",icon:za},{value:"employee_salary",label:"Salários de Funcionários",icon:Aa},{value:"prolabore",label:"Pró-labore",icon:ea},{value:"electricity",label:"Energia Elétrica",icon:zt},{value:"water",label:"Ãgua",icon:Es},{value:"internet",label:"Internet",icon:Dr},{value:"phone",label:"Telefone/Celular",icon:$r},{value:"taxes",label:"Impostos e Taxas (IPTU, Alvará)",icon:ht},{value:"supplies",label:"Materiais/Reposição",icon:va},{value:"raw_materials",label:"Matéria-prima",icon:va},{value:"equipment",label:"Equipamentos",icon:it},{value:"maintenance",label:"Manutenção",icon:it},{value:"marketing",label:"Marketing/Publicidade",icon:Ss},{value:"commissions",label:"Comissões",icon:Ke},{value:"shipping",label:"Frete/Entrega",icon:Fr},{value:"subscriptions",label:"Assinaturas (Software, Serviços)",icon:Ps},{value:"accounting",label:"Contabilidade",icon:Ga},{value:"insurance",label:"Seguros",icon:Ir},{value:"other",label:"Outros",icon:da}];function No(){var L,V;const[t,r]=_.useState([]),[s,n]=_.useState([]),[o,m]=_.useState(!0),[u,i]=_.useState(()=>{const l=localStorage.getItem("accounts-payable-view-mode");return l==="list"||l==="cards"?l:"cards"}),[d,g]=_.useState("current"),[x,y]=_.useState(!1),[M,E]=_.useState(!1),[h,c]=_.useState(null),[b,N]=_.useState(!1),[C,A]=_.useState(null),[f,$]=_.useState(!1),[S,Z]=_.useState(!1),[z,X]=_.useState(!1),[me,we]=_.useState(null),[Y,P]=_.useState(null),[w,O]=_.useState(!1),[H,I]=_.useState(""),[U,se]=_.useState(""),[le,ce]=_.useState(!1),[R,pe]=_.useState({description:"",amount:"",due_date:void 0,supplier_id:"",is_recurring:!1,recurrence_day:"",expense_category:"",include_in_costing:!0,recurrence_type:"one_time",requires_regular_update:!1,alert_days_before:"3",installment_count:"",payment_method:"",amount_paid:"",receipt_url:"",payment_notes:"",bank_account_id:""});_.useEffect(()=>{B()},[d]),_.useEffect(()=>{localStorage.setItem("accounts-payable-view-mode",u)},[u]);const B=async()=>{try{m(!0);const{data:{user:l}}=await v.auth.getUser();if(!l){ue.error("Sessão expirada. Faça login novamente.");return}let T=null;const{data:Ne,error:J}=await v.from("accounts_payable").select("*, suppliers(name)").eq("user_id",l.id).order("due_date",{ascending:!0});if(J){console.warn("Falha no join com suppliers, tentando select simples:",J);const{data:Qe,error:ka}=await v.from("accounts_payable").select("*").eq("user_id",l.id).order("due_date",{ascending:!0});if(ka)throw ka;T=Qe||[]}else T=Ne||[];const{data:Re,error:ia}=await v.from("suppliers").select("id, name").eq("user_id",l.id).order("name");ia&&console.warn("Erro ao carregar fornecedores:",ia);let la=T||[];if(await eo(la,l.id)>0){const{data:Qe}=await v.from("accounts_payable").select("*, suppliers(name)").eq("user_id",l.id).order("due_date",{ascending:!0});la=Qe||la}r(la),n(Re||[])}catch(l){console.error("Erro ao carregar dados:",l),ue.error("Erro ao carregar contas a pagar")}finally{m(!1)}},W=(()=>{const l=new Date,T=l.getMonth(),Ne=l.getFullYear();return t.filter(J=>{if(d==="all")return!0;const Re=tt(J.due_date),ia=Re.getMonth(),la=Re.getFullYear();if(d==="current"){const fa=ia===T&&la===Ne,Qe=Re<l&&!J.paid,ka=J.paid&&Re<new Date(Ne,T,1);return fa||Qe||ka}else if(d==="previous"){const fa=T===0?11:T-1,Qe=T===0?Ne-1:Ne;return ia===fa&&la===Qe}else if(d==="next"){const fa=T===11?0:T+1,Qe=T===11?Ne+1:Ne;return ia===fa&&la===Qe}return!0})})(),D=W.filter(l=>!l.paid).sort((l,T)=>new Date(l.due_date).getTime()-new Date(T.due_date).getTime()),re=W.filter(l=>l.paid).sort((l,T)=>new Date(T.due_date).getTime()-new Date(l.due_date).getTime());D.reduce((l,T)=>l+Number(T.amount),0);const k=async()=>{try{if(!R.description||!R.amount||!R.due_date){ue.error("Preencha todos os campos obrigatórios");return}if(!R.expense_category){ue.error("Selecione a categoria de despesa");return}if(R.recurrence_type==="installment"&&!R.installment_count){ue.error("Informe o número de parcelas para parcelamentos");return}const{data:{user:l}}=await v.auth.getUser();if(!l)return;if(R.recurrence_type==="installment"&&R.installment_count){const T=parseInt(R.installment_count),J=parseFloat(R.amount)/T,Re=crypto.randomUUID(),ia=[],la=ra(R.due_date);for(let Qe=1;Qe<=T;Qe++){const ka=Ha(la,Qe-1);ia.push({user_id:l.id,description:`${R.description} (${Qe}/${T})`,amount:J,due_date:Va(ra(ka)),supplier_id:R.supplier_id||null,expense_category:R.expense_category||"other",recurrence_type:"installment",installment_count:null,installment_number:Qe,total_installments:T,installment_group_id:Re,alert_days_before:parseInt(R.alert_days_before),requires_regular_update:!1,include_in_costing:!0,paid:!1,bank_account_id:R.bank_account_id||null,account_type:"expense",competence_date:Va(ra(ka))})}const{error:fa}=await v.from("accounts_payable").insert(ia);if(fa)throw fa;ue.success(`${T} parcelas criadas com sucesso! (${T}x R$ ${J.toFixed(2)})`)}else{const T=Va(ra(R.due_date)),Ne=br(R.recurrence_type,R.due_date),{error:J}=await v.from("accounts_payable").insert({user_id:l.id,description:R.description,amount:parseFloat(R.amount),due_date:T,supplier_id:R.supplier_id||null,expense_category:R.expense_category||"other",recurrence_type:R.recurrence_type,installment_count:null,alert_days_before:parseInt(R.alert_days_before),requires_regular_update:R.requires_regular_update,include_in_costing:!0,paid:!1,bank_account_id:R.bank_account_id||null,account_type:"expense",competence_date:T,...Ne});if(J)throw J;ue.success("Conta adicionada com sucesso!")}y(!1),pe({description:"",amount:"",due_date:void 0,supplier_id:"",is_recurring:!1,recurrence_day:"",expense_category:"",include_in_costing:!0,recurrence_type:"one_time",requires_regular_update:!1,alert_days_before:"3",installment_count:"",payment_method:"",amount_paid:"",receipt_url:"",payment_notes:"",bank_account_id:""}),B()}catch(l){console.error("Erro ao adicionar conta:",l),ue.error("Erro ao adicionar conta")}},ke=l=>{c(l),E(!0)},Q=async()=>
73{if(h)try{const{data:l}=await v.from("accounts_payable").select("installment_group_id, installment_number, total_installments").eq("id",h.id).single();if(l==null?void 0:l.installment_group_id){const{count:Ne}=await v.from("accounts_payable").select("*",{count:"exact",head:!0}).eq("installment_group_id",l.installment_group_id).eq("paid",!1);P({installmentGroupId:l.installment_group_id,installmentNumber:l.installment_number||1,totalInstallments:l.total_installments||1,unpaidCount:Ne||1}),X(!0)}else await oe()}catch(l){console.error("Erro ao editar:",l),ue.error("Erro ao editar conta")}},p=async()=>{if(!(!h||!Y))try{const{error:l}=await v.from("accounts_payable").update({description:h.description,amount:h.amount,supplier_id:h.supplier_id,expense_category:h.expense_category,recurrence_type:h.recurrence_type,alert_days_before:h.alert_days_before,requires_regular_update:h.requires_regular_update,include_in_costing:!0}).eq("installment_group_id",Y.installmentGroupId).eq("paid",!1);if(l)throw l;ue.success(`${Y.unpaidCount} parcelas atualizadas!`),X(!1),E(!1),c(null),P(null),B()}catch(l){console.error("Erro ao atualizar parcelas:",l),ue.error("Erro ao atualizar parcelas")}},oe=async()=>{if(h)try{const l=br(h.recurrence_type||"one_time",h.due_date),{error:T}=await v.from("accounts_payable").update({description:h.description,amount:h.amount,due_date:h.due_date,supplier_id:h.supplier_id,expense_category:h.expense_category,recurrence_type:h.recurrence_type,alert_days_before:h.alert_days_before,requires_regular_update:h.requires_regular_update,include_in_costing:!0,...l}).eq("id",h.id);if(T)throw T;ue.success("Conta atualizada!"),X(!1),E(!1),c(null),P(null),B()}catch(l){console.error("Erro ao atualizar conta:",l),ue.error("Erro ao atualizar conta")}},he=async l=>{try{const{data:T}=await v.from("accounts_payable").select("installment_group_id, installment_number, total_installments, description").eq("id",l).single();if(T==null?void 0:T.installment_group_id){const{count:J}=await v.from("accounts_payable").select("*",{count:"exact",head:!0}).eq("installment_group_id",T.installment_group_id).eq("paid",!1);we({id:l,installmentGroupId:T.installment_group_id,installmentNumber:T.installment_number||1,totalInstallments:T.total_installments||1,description:T.description||"",unpaidCount:J||1}),Z(!0)}else we({id:l}),$(!0)}catch(T){console.error("Erro ao preparar exclusão:",T),ue.error("Erro ao preparar exclusão")}},ye=async()=>{if(me!=null&&me.installmentGroupId)try{const{error:l}=await v.from("accounts_payable").delete().eq("installment_group_id",me.installmentGroupId).eq("paid",!1);if(l)throw l;ue.success(`${me.unpaidCount} parcelas excluÃdas!`),Z(!1),we(null),B(),window.dispatchEvent(new CustomEvent("accounts-payable-updated"))}catch(l){console.error("Erro ao deletar parcelas:",l),ue.error("Erro ao excluir parcelas")}},ge=async()=>{if(me!=null&&me.id)try{const{data:l}=await v.from("accounts_payable").select("parent_recurrence_id, is_recurring, recurrence_type, description").eq("id",me.id).single();if(l&&(l.is_recurring||l.recurrence_type==="monthly"||l.recurrence_type==="annual")){const T=l.parent_recurrence_id||me.id;await v.from("accounts_payable").update({is_recurring:!1,recurrence_type:"one_time",recurrence_day:null}).or(`id.eq.${T},parent_recurrence_id.eq.${T}`),l.description&&l.recurrence_type&&await v.from("accounts_payable").update({is_recurring:!1,recurrence_type:"one_time",recurrence_day:null}).eq("description",l.description).eq("recurrence_type",l.recurrence_type)}await Da.deleteAccountsPayable(me.id),ue.success(me.installmentGroupId?"Parcela excluÃda!":"Conta excluÃda!"),Z(!1),$(!1),we(null),B(),window.dispatchEvent(new CustomEvent("accounts-payable-updated"))}catch(l){console.error("Erro ao deletar:",l);const T=l instanceof Error?l.message:"Erro ao excluir";ue.error(T)}},Pe=async(l,T)=>{if(!T){const Ne=t.find(J=>J.id===l);Ne&&(A(Ne),N(!0));return}try{const{error:Ne}=await v.from("accounts_payable").update({paid:!1,payment_date:null}).eq("id",l);if(Ne)throw Ne;ue.success("Pagamento desfeito!"),B()}catch(Ne){console.error("Erro ao desfazer pagamento:",Ne),ue.error("Erro ao desfazer pagamento")}},Ue=()=>{N(!1),A(null),B()},Xe=async()=>
73{if(!H.trim()){ue.error("Digite o nome do fornecedor");return}ce(!0);try{const{data:{user:l}}=await v.auth.getUser();if(!l)return;const{data:T,error:Ne}=await v.from("suppliers").insert({user_id:l.id,name:H.trim(),phone:U.trim()||null}).select().single();if(Ne)throw Ne;ue.success(`Fornecedor "${T.name}" cadastrado!`),I(""),se(""),O(!1),B()}catch(l){console.error("Erro ao cadastrar fornecedor:",l),ue.error("Erro ao cadastrar fornecedor")}finally{ce(!1)}},Ge=l=>{if(!l)return"-";const T=s.find(Ne=>Ne.id===l);return T?T.name:"-"},xe=()=>D.length===0&&re.length===0?e("div",{className:"text-center text-muted-foreground py-8",children:"Nenhuma conta a pagar"}):u==="cards"?a("div",{className:"space-y-6",children:[D.length>0&&a("div",{children:[a("p",{className:"text-sm font-medium text-muted-foreground mb-2",children:["Pendentes (",D.length,")"]}),e("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:D.map(l=>e(fr,{account:l,supplierName:Ge(l.supplier_id),onEdit:ke,onDelete:he,onTogglePaid:Pe},l.id))})]}),re.length>0&&a("div",{children:[a("p",{className:"text-sm font-medium text-muted-foreground mb-2",children:["Pagas (",re.length,")"]}),e("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 opacity-70",children:re.map(l=>e(fr,{account:l,supplierName:Ge(l.supplier_id),onEdit:ke,onDelete:he,onTogglePaid:Pe},l.id))})]})]}):a(Vt,{children:[e(Lt,{children:a(_a,{children:[e(We,{children:"Descrição"}),e(We,{children:"Fornecedor"}),e(We,{children:"Valor"}),e(We,{children:"Vencimento"}),e(We,{children:"Status"}),e(We,{children:"Ações"})]})}),a(Bt,{children:[D.map(l=>a(_a,{children:[e(De,{children:l.description}),e(De,{children:Ge(l.supplier_id)}),a(De,{children:["R$ ",Number(l.amount).toFixed(2)]}),e(De,{children:Ze(l.due_date)}),e(De,{children:e(ae,{variant:"destructive",children:"Pendente"})}),e(De,{children:a("div",{className:"flex gap-1",children:[e(j,{size:"sm",variant:"outline",onClick:()=>Pe(l.id,l.paid),children:e(Ke,{className:"h-4 w-4"})}),e(j,{size:"sm",variant:"ghost",onClick:()=>ke(l),children:e($t,{className:"h-4 w-4"})}),e(j,{size:"sm",variant:"ghost",onClick:()=>he(l.id),children:e(ya,{className:"h-4 w-4 text-red-600"})})]})})]},l.id)),D.length>0&&re.length>0&&e(_a,{children:e(De,{colSpan:6,className:"py-1 bg-muted/40",children:a("span",{className:"text-xs text-muted-foreground font-medium",children:["â
Pagas (",re.length,")"]})})}),re.map(l=>a(_a,{className:"opacity-60",children:[e(De,{children:l.description}),e(De,{children:Ge(l.supplier_id)}),a(De,{children:["R$ ",Number(l.amount).toFixed(2)]}),e(De,{children:Ze(l.due_date)}),e(De,{children:e(ae,{variant:"outline",className:"text-green-600 border-green-600",children:"Paga"})}),e(De,{children:a("div",{className:"flex gap-1",children:[e(j,{size:"sm",variant:"ghost",onClick:()=>Pe(l.id,l.paid),title:"Desfazer pagamento",children:e(Ke,{className:"h-4 w-4 text-green-600"})}),e(j,{size:"sm",variant:"ghost",onClick:()=>he(l.id),children:e(ya,{className:"h-4 w-4 text-red-600"})})]})})]},l.id))]})]}),q=D.reduce((l,T)=>l+Number(T.amount),0);return a("div",{className:"space-y-4",children:[e(K,{className:"bg-gradient-to-r from-red-50 to-orange-50 dark:from-red-950 dark:to-orange-950 border-red-200",children:e(ee,{className:"pt-6",children:a("div",{className:"flex items-center justify-between",children:[a("div",{children:[e("p",{className:"text-sm text-muted-foreground mb-1",children:"Total de Contas a Pagar"}),e("p",{className:"text-3xl font-bold text-red-600",children:new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format(q)}),a("p",{className:"text-xs text-muted-foreground mt-1",children:[D.length," ",D.length===1?"conta pendente":"contas pendentes"]})]}),e(ta,{className:"h-12 w-12 text-red-600 opacity-20"})]})})}),a(K,{children:[e(te,{children:a("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[a("div",{children:[a(ne,{className:"flex items-center gap-2",children:[e(ta,{className:"h-5 w-5 text-red-600"}),"Contas a Pagar"]}),e(Se,{children:"Sua fila de trabalho de obrigações pendentes"})]}),a("div",{className:"flex gap-2 flex-wrap",children:[a("div",{className:"flex gap-1 bg-muted p-1 rounded-lg",children:[e(j,{size:"sm",variant:d==="previous"?"default":"ghost",onClick:()=>g("previous"),className:"h-8 px-3 text-xs",children:"â Anterior"}),e(j,{size:"sm",variant:d==="current"?"default":"ghost",onClick:()=>g("current"),className:"h-8 px-3 text-xs",children:"Corrente"}),e(j,{size:"sm",variant:d==="next"?"default":"ghost",onClick:()=>g("next"),className:"h-8 px-3 text-xs",children:"Próximo â"}),e(j,{size:"sm",variant:d==="all"?"default":"ghost",onClick:()=>g("all"),className:"h-8 px-3 text-xs",children:"Todas"})]}),a("div",{className:"flex gap-1 bg-muted p-1 rounded-lg",children:[e(j,{size:"sm",variant:u==="cards"?"default":"ghost",onClick:()=>i("cards"),children:e(Mr,{className:"h-4 w-4"})}),e(j,{size:"sm",variant:u==="list"?"default":"ghost",onClick:()=>i("list"),children:e(Rr,{className:"h-4 w-4"})})]}),e(co,{onSyncComplete:B}),a(Ea,{open:x,onOpenChange:y,children:[e(kr,{asChild:!0,children:a(j,{children:[e(ga,{className:"h-4 w-4 mr-1"}),"Nova Conta"]})}),a(Sa,{className:"max-h-[90vh] max-w-2xl overflow-hidden flex flex-col",children:[a(Pa,{className:"px-6 pt-6",children:[a(Ma,{className:"flex items-center gap-2",children:[e(ga,{className:"h-4 w-4"}),"Adicionar Conta a Pagar"]}),e(Oa,{children:"Registre uma nova obrigação financeira"})]}),e("div",{className:"flex-1 overflow-y-auto px-6 py-4",children:a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e("div",{className:"md:col-span-2",children:a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Descrição *"}),e(Ce,{placeholder:"Ex: Aluguel, Energia Elétrica, Fornecedor X",value:R.description,onChange:l=>pe({...R,description:l.target.value})})]})}),a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Valor *"}),e(Ce,{type:"number",step:"0.01",placeholder:"0.00",className:"h-9 text-sm",value:R.amount,onChange:l=>pe({...R,amount:l.target.value})})]}),a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Data de Vencimento *"}),e(rt,{value:R.due_date,onChange:l=>pe({...R,due_date:ra(l)}),label:"Vencimento",size:"sm",className:"w-full"})]}),a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Fornecedor"}),a("div",{className:"flex gap-1.5",children:[a(Ve,{value:R.supplier_id,onValueChange:l=>pe({...R,supplier_id:l}),children:[e(Le,{className:"h-9 text-sm flex-1",children:e(Be,{placeholder:"Selecione um fornecedor"})}),e(ze,{children:s.map(l=>e(fe,{value:l.id,children:a("span",{className:"inline-flex items-center gap-2",children:[e(ta,{className:"h-4 w-4 text-muted-foreground"}),l.name]})},l.id))})]}),e(j,{type:"button",variant:"outline",size:"sm",className:"h-9 px-3",onClick:()=>O(!w),title:"Cadastro rápido de fornecedor",children:e(ga,{className:"h-4 w-4"})}),e(j,{type:"button",variant:"outline",size:"sm",className:"h-9 px-3",onClick:B,title:"Atualizar lista de fornecedores",children:e(ha,{className:"h-4 w-4"})})]}),w&&a("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-2 mt-2",children:[a("p",{className:"text-xs font-semibold text-blue-900 inline-flex items-center gap-1",children:[e(ga,{className:"h-3.5 w-3.5"}),"Cadastro Rápido de Fornecedor"]}),e(Ce,{placeholder:"Nome do fornecedor *",value:H,onChange:l=>I(l.target.value),className:"h-8 text-sm"}),e(Ce,{placeholder:"Telefone (opcional)",value:U,onChange:l=>se(l.target.value),className:"h-8 text-sm"}),a("div",{className:"flex gap-2",children:[e(j,{type:"button",size:"sm",onClick:Xe,disabled:le,className:"h-7 text-xs flex-1",children:le?"Salvando...":"â Salvar"}),e(j,{type:"button",size:"sm",variant:"outline",onClick:()=>{O(!1),I(""),se("")},className:"h-7 text-xs",children:"Cancelar"})]})]})]}),a("div",{className:"space-y-1.5",children:[a(be,{className:"text-sm",children:["Categoria de Despesa",e("span",{className:"text-destructive ml-1",children:"*"})]}),a(Ve,{value:R.expense_category,onValueChange:l=>pe({...R,expense_category:l}),children:[e(Le,{className:"h-9 text-sm",children:e(Be,{placeholder:"Selecione a categoria"})}),e(ze,{children:xr.map(l=>e(fe,{value:l.value,children:a("span",{className:"inline-flex items-center gap-2",children:[e(l.icon,{className:"h-4 w-4 text-muted-foreground"}),l.label]})},l.value))})]})]}),e("div",{className:"md:col-span-2 space-y-1.5",children:e(Yr,{value:R.bank_account_id,onChange:l=>pe({...R,bank_account_id:l}),label:"Conta para pagamento (opcional)"})}),a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Tipo de Recorrência"}),a(Ve,{value:R.recurrence_type,onValueChange:l=>pe({...R,recurrence_type:l,installment_count:l==="installment"?R.installment_count:""}),children:[e(Le,{className:"h-9 text-sm",children:e(Be,{placeholder:"Selecione o tipo"})}),a(ze,{children:[e(fe,{value:"one_time",children:a("span",{className:"inline-flex items-center gap-2",children:[e(ta,{className:"h-4 w-4 text-muted-foreground"}),"Pagamento Ãnico"]})}),e(fe,{value:"monthly",children:a("span",{className:"inline-flex items-center gap-2",children:[e(ha,{
73className:"h-4 w-4 text-muted-foreground"}),"Mensal"]})}),e(fe,{value:"annual",children:a("span",{className:"inline-flex items-center gap-2",children:[e(je,{className:"h-4 w-4 text-muted-foreground"}),"Anual"]})}),e(fe,{value:"installment",children:a("span",{className:"inline-flex items-center gap-2",children:[e(Ke,{className:"h-4 w-4 text-muted-foreground"}),"Parcelamento"]})})]})]})]}),R.recurrence_type==="installment"&&a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Número de Parcelas *"}),a(Ve,{value:R.installment_count,onValueChange:l=>pe({...R,installment_count:l}),children:[e(Le,{className:"h-9 text-sm",children:e(Be,{placeholder:"Quantas vezes?"})}),e(ze,{className:"max-h-[250px]",children:Array.from({length:24},(l,T)=>T+2).map(l=>e(fe,{value:l.toString(),children:a("span",{className:"inline-flex items-center gap-2",children:[e(Ke,{className:"h-4 w-4 text-muted-foreground"}),l,"x parcelas"]})},l))})]})]}),R.recurrence_type==="installment"&&R.installment_count&&R.amount&&a("div",{className:"md:col-span-2 bg-purple-50 border-2 border-purple-300 rounded-lg p-4",children:[a("p",{className:"text-sm text-purple-900 font-semibold mb-2 flex items-center gap-2",children:[e(Ke,{className:"h-4 w-4"}),"Parcelamento Selecionado"]}),a("div",{className:"space-y-2",children:[a("p",{className:"text-sm text-purple-800",children:[e("strong",{children:"Total:"})," R$ ",parseFloat(R.amount).toFixed(2)]}),a("p",{className:"text-sm text-purple-800",children:[e("strong",{children:"Parcelas:"})," ",R.installment_count,"x de R$ ",(parseFloat(R.amount)/parseInt(R.installment_count)).toFixed(2)]}),a("p",{className:"text-xs text-purple-700 mt-2 bg-purple-100 p-2 rounded",children:["O sistema criará automaticamente ",R.installment_count," contas mensais com valores iguais."]})]})]}),R.recurrence_type==="annual"&&R.amount&&a("div",{className:"md:col-span-2 bg-green-50 border-2 border-green-300 rounded-lg p-4",children:[a("p",{className:"text-sm text-green-900 font-semibold mb-2 flex items-center gap-2",children:[e(ta,{className:"h-4 w-4"}),"Conta Anual (ex: IPTU, Impostos)"]}),a("div",{className:"space-y-2",children:[a("p",{className:"text-sm text-green-800",children:[e("strong",{children:"Valor Total Anual:"})," R$ ",parseFloat(R.amount).toFixed(2)]}),a("p",{className:"text-sm text-green-800",children:[e("strong",{children:"Equivalente Mensal:"})," R$ ",(parseFloat(R.amount)/12).toFixed(2),"/mês"]}),e("p",{className:"text-xs text-green-700 mt-2 bg-green-100 p-2 rounded",children:"O valor total será dividido por 12 para cálculo do custo mensal. O pagamento é feito 1 vez por ano."})]})]}),a("div",{className:"md:col-span-2 space-y-3 border-t pt-3",children:[a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Avisar quantos dias antes do vencimento?"}),a(Ve,{value:R.alert_days_before,onValueChange:l=>pe({...R,alert_days_before:l}),children:[e(Le,{className:"h-9 text-sm",children:e(Be,{placeholder:"Selecione"})}),a(ze,{children:[e(fe,{value:"1",children:a("span",{className:"inline-flex items-center gap-2",children:[e(je,{className:"h-4 w-4 text-muted-foreground"}),"1 dia antes"]})}),e(fe,{value:"2",children:a("span",{className:"inline-flex items-center gap-2",children:[e(je,{className:"h-4 w-4 text-muted-foreground"}),"2 dias antes"]})}),e(fe,{value:"3",children:a("span",{className:"inline-flex items-center gap-2",children:[e(je,{className:"h-4 w-4 text-muted-foreground"}),"3 dias antes (padrão)"]})}),e(fe,{value:"5",children:a("span",{className:"inline-flex items-center gap-2",children:[e(je,{className:"h-4 w-4 text-muted-foreground"}),"5 dias antes"]})}),e(fe,{value:"7",children:a("span",{className:"inline-flex items-center gap-2",children:[e(je,{className:"h-4 w-4 text-muted-foreground"}),"7 dias antes"]})})]})]})]}),R.recurrence_type!=="installment"&&a(Ee,{children:[a("div",{className:"flex items-center space-x-2",children:[e(st,{id:"requires_regular_update",checked:R.requires_regular_update,onCheckedChange:l=>pe({...R,requires_regular_update:l===!0})}),e(be,{htmlFor:"requires_regular_update",className:"text-xs sm:text-sm font-medium cursor-pointer",children:"Conta com valor variável (ex: água, luz)"})]}),R.requires_regular_update&&e("div",{className:"bg-yellow-50 border border-yellow-200 rounded-lg p-3 ml-6",children:a("p",{className:"text-xs text-yellow-800",children:[e("strong",{children:"Conta Variável:"})," O valor pode mudar a cada mês. Você receberá um lembrete para atualizar o valor antes do vencimento."]})})]})]}),e("div",{className:"md:col-span-2 bg-blue-50 border border-blue-200 rounded-lg p-3",children:a("p",{className:"text-sm text-blue-900 flex items-center gap-2",children:[e(na,{className:"h-4 w-4"}),R.recurrence_type==="monthly"&&a("span",{children:[e("strong",{children:"Recorrência automática:"})," Esta conta será recriada todo mês automaticamente"]}),R.recurrence_type==="annual"&&a("span",{children:[e("strong",{children:"Recorrência automática:"})," Esta conta será recriada todo ano automaticamente"]}),R.recurrence_type==="installment"&&a("span",{children:[e("strong",{children:"Parcelamento:"})," Serão criadas parcelas mensais até completar o número informado"]}),R.recurrence_type==="one_time"&&a("span",{children:[e("strong",{children:"Pagamento único:"})," Esta conta não se repetirá"]})]})})]})}),e("div",{className:"px-6 py-4 border-t",children:e(j,{onClick:k,className:"w-full h-9 text-sm",children:"Adicionar Conta"})})]})]})]})]})}),e(ee,{children:o?e("div",{className:"text-center py-8",children:"Carregando..."}):xe()})]}),e(Ea,{open:M,onOpenChange:E,children:a(Sa,{className:"max-h-[90vh] max-w-2xl overflow-hidden flex flex-col",children:[a(Pa,{className:"px-6 pt-6",children:[a(Ma,{className:"flex items-center gap-2",children:[e($t,{className:"h-4 w-4"}),"Editar Conta a Pagar"]}),e(Oa,{children:"Atualize as informações da conta"})]}),h&&a(Ee,{children:[e("div",{className:"flex-1 overflow-y-auto px-6 py-4",children:a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e("div",{className:"md:col-span-2",children:a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Descrição *"}),e(Ce,{placeholder:"Ex: Aluguel, Energia Elétrica, Fornecedor X",value:h.description,onChange:l=>c({...h,description:l.target.value})})]})}),a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Valor *"}),e(Ce,{type:"number",step:"0.01",placeholder:"0.00",className:"h-9 text-sm",value:h.amount,onChange:l=>c({...h,amount:parseFloat(l.target.value)})})]}),a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Data de Vencimento *"}),e(rt,{value:h.due_date?tt(h.due_date):void 0,onChange:l=>c({...h,due_date:Va(ra(l))}),label:"Vencimento",size:"sm",className:"w-full"})]}),a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Fornecedor"}),a("div",{className:"flex gap-1.5",children:[a(Ve,{value:h.supplier_id||"",onValueChange:l=>c({...h,supplier_id:l}),children:[e(Le,{className:"h-9 text-sm flex-1",children:e(Be,{placeholder:"Selecione um fornecedor"})}),e(ze,{children:s.map(l=>e(fe,{value:l.id,children:a("span",{className:"inline-flex items-center gap-2",children:[e(ta,{className:"h-4 w-4 text-muted-foreground"}),l.name]})},l.id))})]}),e(j,{type:"button",variant:"outline",size:"sm",className:"h-9 px-3",onClick:B,title:"Atualizar lista de fornecedores",children:e(ha,{className:"h-4 w-4"})})]})]}),a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Categoria de Despesa"}),a(Ve,{value:h.expense_category||"",onValueChange:l=>c({...h,expense_category:l}),children:[e(Le,{className:"h-9 text-sm",children:e(Be,{placeholder:"Selecione a categoria"})}),e(ze,{children:xr.map(l=>e(fe,{value:l.value,children:a("span",{className:"inline-flex items-center gap-2",children:[e(l.icon,{className:"h-4 w-4 text-muted-foreground"}),l.label]})},l.value))})]})]}),a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Tipo de Recorrência"}),a(Ve,{value:h.recurrence_type||"one_time",onValueChange:l=>c({...h,recurrence_type:l,installment_count:l==="installment"?h.installment_count:void 0}),children:[e(Le,{className:"h-9 text-sm",children:e(Be,{placeholder:"Selecione o tipo"})}),a(ze,{children:[e(fe,{value:"one_time",children:a("span",{className:"inline-flex items-center gap-2",children:[e(ta,{className:"h-4 w-4 text-muted-foreground"}),"Pagamento Ãnico"]})}),e(fe,{value:"monthly",children:a("span",{className:"inline-flex items-center gap-2",children:[e(ha,{
73className:"h-4 w-4 text-muted-foreground"}),"Mensal"]})}),e(fe,{value:"annual",children:a("span",{className:"inline-flex items-center gap-2",children:[e(je,{className:"h-4 w-4 text-muted-foreground"}),"Anual"]})}),e(fe,{value:"installment",children:a("span",{className:"inline-flex items-center gap-2",children:[e(Ke,{className:"h-4 w-4 text-muted-foreground"}),"Parcelamento"]})})]})]})]}),h.recurrence_type==="installment"&&a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Número de Parcelas *"}),a(Ve,{value:((L=h.installment_count)==null?void 0:L.toString())||"",onValueChange:l=>c({...h,installment_count:parseInt(l)}),children:[e(Le,{className:"h-9 text-sm",children:e(Be,{placeholder:"Quantas vezes?"})}),e(ze,{className:"max-h-[250px]",children:Array.from({length:24},(l,T)=>T+2).map(l=>e(fe,{value:l.toString(),children:a("span",{className:"inline-flex items-center gap-2",children:[e(Ke,{className:"h-4 w-4 text-muted-foreground"}),l,"x parcelas"]})},l))})]})]}),h.recurrence_type==="installment"&&h.installment_count&&h.amount&&a("div",{className:"md:col-span-2 bg-purple-50 border-2 border-purple-300 rounded-lg p-4",children:[a("p",{className:"text-sm text-purple-900 font-semibold mb-2 flex items-center gap-2",children:[e(Ke,{className:"h-4 w-4"}),"Parcelamento Selecionado"]}),a("div",{className:"space-y-2",children:[a("p",{className:"text-sm text-purple-800",children:[e("strong",{children:"Total:"})," R$ ",Number(h.amount).toFixed(2)]}),a("p",{className:"text-sm text-purple-800",children:[e("strong",{children:"Parcelas:"})," ",h.installment_count,"x de R$ ",(Number(h.amount)/h.installment_count).toFixed(2)]}),a("p",{className:"text-xs text-purple-700 mt-2 bg-purple-100 p-2 rounded",children:["O sistema criará automaticamente ",h.installment_count," contas mensais com valores iguais."]})]})]}),h.recurrence_type==="annual"&&h.amount&&a("div",{className:"md:col-span-2 bg-green-50 border-2 border-green-300 rounded-lg p-4",children:[a("p",{className:"text-sm text-green-900 font-semibold mb-2 flex items-center gap-2",children:[e(ta,{className:"h-4 w-4"}),"Conta Anual (ex: IPTU, Impostos)"]}),a("div",{className:"space-y-2",children:[a("p",{className:"text-sm text-green-800",children:[e("strong",{children:"Valor Total Anual:"})," R$ ",Number(h.amount).toFixed(2)]}),a("p",{className:"text-sm text-green-800",children:[e("strong",{children:"Equivalente Mensal:"})," R$ ",(Number(h.amount)/12).toFixed(2),"/mês"]}),e("p",{className:"text-xs text-green-700 mt-2 bg-green-100 p-2 rounded",children:"O valor total será dividido por 12 para cálculo do custo mensal. O pagamento é feito 1 vez por ano."})]})]}),a("div",{className:"md:col-span-2 space-y-3 border-t pt-3",children:[a("div",{className:"space-y-1.5",children:[e(be,{className:"text-sm",children:"Avisar quantos dias antes do vencimento?"}),a(Ve,{value:((V=h.alert_days_before)==null?void 0:V.toString())||"3",onValueChange:l=>c({...h,alert_days_before:parseInt(l)}),children:[e(Le,{className:"h-9 text-sm",children:e(Be,{placeholder:"Selecione"})}),a(ze,{children:[e(fe,{value:"1",children:a("span",{className:"inline-flex items-center gap-2",children:[e(je,{className:"h-4 w-4 text-muted-foreground"}),"1 dia antes"]})}),e(fe,{value:"2",children:a("span",{className:"inline-flex items-center gap-2",children:[e(je,{className:"h-4 w-4 text-muted-foreground"}),"2 dias antes"]})}),e(fe,{value:"3",children:a("span",{className:"inline-flex items-center gap-2",children:[e(je,{className:"h-4 w-4 text-muted-foreground"}),"3 dias antes (padrão)"]})}),e(fe,{value:"5",children:a("span",{className:"inline-flex items-center gap-2",children:[e(je,{className:"h-4 w-4 text-muted-foreground"}),"5 dias antes"]})}),e(fe,{value:"7",children:a("span",{className:"inline-flex items-center gap-2",children:[e(je,{className:"h-4 w-4 text-muted-foreground"}),"7 dias antes"]})})]})]})]}),h.recurrence_type!=="installment"&&a(Ee,{children:[a("div",{className:"flex items-center space-x-2",children:[e(st,{id:"edit_requires_regular_update",checked:h.requires_regular_update||!1,onCheckedChange:l=>c({...h,requires_regular_update:l===!0}
73)}),e(be,{htmlFor:"edit_requires_regular_update",className:"text-xs sm:text-sm font-medium cursor-pointer",children:"Conta com valor variável (ex: água, luz)"})]}),h.requires_regular_update&&e("div",{className:"bg-yellow-50 border border-yellow-200 rounded-lg p-3 ml-6",children:a("p",{className:"text-xs text-yellow-800",children:[e("strong",{children:"Conta Variável:"})," O valor pode mudar a cada mês. Você receberá um lembrete para atualizar o valor antes do vencimento."]})})]})]}),e("div",{className:"md:col-span-2 bg-blue-50 border border-blue-200 rounded-lg p-3",children:a("p",{className:"text-sm text-blue-900 flex items-center gap-2",children:[e(na,{className:"h-4 w-4"}),h.recurrence_type==="monthly"&&a("span",{children:[e("strong",{children:"Recorrência automática:"})," Esta conta será recriada todo mês automaticamente"]}),h.recurrence_type==="annual"&&a("span",{children:[e("strong",{children:"Recorrência automática:"})," Esta conta será recriada todo ano automaticamente"]}),h.recurrence_type==="installment"&&a("span",{children:[e("strong",{children:"Parcelamento:"})," Serão criadas parcelas mensais até completar o número informado"]}),h.recurrence_type==="one_time"&&a("span",{children:[e("strong",{children:"Pagamento único:"})," Esta conta não se repetirá"]})]})})]})}),e("div",{className:"px-6 py-4 border-t",children:a("div",{className:"flex gap-2",children:[e(j,{variant:"outline",onClick:()=>E(!1),className:"flex-1",children:"Cancelar"}),e(j,{onClick:Q,className:"flex-1",children:"Salvar Alterações"})]})})]})]})}),e(ao,{isOpen:b,onClose:()=>{N(!1),A(null)},account:C,onSuccess:Ue}),e(to,{open:f,onOpenChange:$,type:"delete",title:"Excluir Conta",description:"Tem certeza que deseja excluir esta conta a pagar? Esta ação não pode ser desfeita.",confirmText:"Sim, excluir",onConfirm:ge}),me&&e(ro,{open:S,onOpenChange:Z,installmentNumber:me.installmentNumber||1,totalInstallments:me.totalInstallments||1,description:me.description||"",unpaidCount:me.unpaidCount||1,onDeleteAll:ye,onDeleteOne:ge}),Y&&e(so,{open:z,onOpenChange:X,installmentNumber:Y.installmentNumber,totalInstallments:Y.totalInstallments,unpaidCount:Y.unpaidCount,onEditAll:p,onEditOne:oe})]})}function _o({customer:t,onReceivePayment:r}){const n=(o=>o>=5e3?{label:"DÃvida Alta",color:"text-red-700",gradient:"from-red-500 to-red-600",icon:e(na,{className:"h-4 w-4"})}:o>=1e3?{label:"DÃvida Média",color:"text-orange-700",gradient:"from-orange-500 to-orange-600",icon:e(na,{className:"h-4 w-4"})}:{label:"DÃvida Baixa",color:"text-yellow-700",gradient:"from-yellow-500 to-yellow-600",icon:e(aa,{className:"h-4 w-4"})})(t.balance);return a(K,{className:"overflow-hidden hover:shadow-md transition-all border-2",children:[e(te,{className:_e("p-3 bg-gradient-to-r text-white",n.gradient),children:e("div",{className:"flex items-start justify-between gap-2",children:a("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e(at,{className:"h-5 w-5 flex-shrink-0"}),a("div",{className:"flex-1 min-w-0",children:[e("h3",{className:"font-semibold text-lg truncate",children:t.name}),a("div",{className:"flex items-center gap-1.5 mt-0.5",children:[n.icon,e("span",{className:"text-sm font-medium",children:n.label})]})]})]})})}),a(ee,{className:"p-3 space-y-3",children:[e("div",{className:"p-4 bg-gradient-to-br from-red-50 to-rose-50 dark:from-red-950/30 dark:to-rose-950/30 border-2 border-red-200 dark:border-red-800 rounded-lg",children:a("div",{className:"flex items-center justify-between",children:[a("div",{children:[e("div",{className:"text-xs text-red-600 dark:text-red-400 font-medium mb-1",children:"Saldo Devedor"}),a("div",{className:"text-2xl font-bold text-red-700 dark:text-red-400",children:["R$ ",t.balance.toFixed(2)]})]}),e(aa,{className:"h-8 w-8 text-red-500 dark:text-red-400"})]})}),a(j,{size:"lg",className:"w-full h-10 bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white font-bold",onClick:()=>r(t),children:[e(Ba,{className:"h-4 w-4 mr-2"}),"Receber Pagamento"]}),e("div",{className:"text-center text-xs text-muted-foreground pt-1 border-t",children:"Clique para registrar um pagamento deste cliente"})]})]})}function wo(){const[t,r]=_.useState([]),[s,n]=_.useState(!0),[o,m]=_.useState(()=>{const C=localStorage.getItem("accounts-receivable-view-mode");return C==="list"||C==="cards"?C:"cards"}),[u,i]=_.useState(!1),[d,g]=_.useState(null),[x,y]=_.useState(!0);_.useEffect(()=>{M()},[]),_.useEffect(()=>{localStorage.setItem("accounts-receivable-view-mode",o)},[o]);const M=async()=>{try{n(!0);const{data:{user:C}}=await v.auth.getUser();if(!C)return;const{data:A,error:f}=await v.from("customers").select("id, name, balance, email, phone,
73created_at").eq("user_id",C.id).gt("balance",0).order("balance",{ascending:!1});if(f)throw f;r(A||[])}catch(C){console.error("Erro ao carregar clientes:",C),ue.error("Erro ao carregar contas a receber")}finally{n(!1)}},E=t.reduce((C,A)=>C+Number(A.balance),0),h=C=>{if(!C.created_at)return 0;const A=new Date,f=new Date(C.created_at),$=Math.abs(A.getTime()-f.getTime());return Math.ceil($/(1e3*60*60*24))},b=(()=>{const C=[{label:"Atual",days:"0-30",count:0,amount:0,color:"bg-green-100 dark:bg-green-950/40 text-green-800 dark:text-green-400"},{label:"Atraso Leve",days:"31-60",count:0,amount:0,color:"bg-yellow-100 dark:bg-yellow-950/40 text-yellow-800 dark:text-yellow-400"},{label:"Atraso Moderado",days:"61-90",count:0,amount:0,color:"bg-orange-100 dark:bg-orange-950/40 text-orange-800 dark:text-orange-400"},{label:"Inadimplente",days:">90",count:0,amount:0,color:"bg-red-100 dark:bg-red-950/40 text-red-800 dark:text-red-400"}];return t.forEach(A=>{const f=h(A),$=Number(A.balance);f<=30?(C[0].count++,C[0].amount+=$):f<=60?(C[1].count++,C[1].amount+=$):f<=90?(C[2].count++,C[2].amount+=$):(C[3].count++,C[3].amount+=$)}),C})(),N=()=>t.length===0?a("div",{className:"text-center text-muted-foreground py-8",children:[e(Ke,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e("p",{className:"font-semibold",children:"Nenhuma conta a receber"}),e("p",{className:"text-sm",children:"Todos os clientes estão com saldo zerado"})]}):o==="cards"?e("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:t.map(C=>e(_o,{customer:C,onReceivePayment:A=>{g(A),i(!0)}},C.id))}):a(Vt,{children:[e(Lt,{children:a(_a,{children:[e(We,{children:"Cliente"}),e(We,{children:"Contato"}),e(We,{className:"text-right",children:"Saldo Devedor"}),e(We,{className:"text-center",children:"Ação"})]})}),e(Bt,{children:t.map(C=>a(_a,{children:[e(De,{className:"font-medium",children:C.name}),a(De,{className:"text-sm text-muted-foreground",children:[C.email&&e("div",{className:"truncate max-w-[200px]",title:C.email,children:C.email}),C.phone&&e("div",{className:"text-xs",children:C.phone}),!C.email&&!C.phone&&"-"]}),e(De,{className:"text-right",children:a(ae,{variant:"destructive",className:"text-base font-semibold",children:["R$ ",Number(C.balance).toFixed(2)]})}),e(De,{className:"text-center",children:a(j,{size:"sm",onClick:()=>{g(C),i(!0)},className:"gap-2",children:[e(Ke,{className:"h-4 w-4"}),"Receber Pagamento"]})})]},C.id))})]});return a("div",{className:"space-y-4",children:[a(K,{children:[e(te,{children:a("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[a("div",{children:[a(ne,{className:"flex items-center gap-2",children:[e(Ke,{className:"h-5 w-5 text-green-600"}),"Contas a Receber"]}),e(Se,{children:"Clientes com saldo devedor"})]}),a("div",{className:"flex gap-2",children:[a("div",{className:"bg-green-50 dark:bg-green-950/30 border border-green-200 dark:border-green-800 rounded-lg px-4 py-2",children:[e("p",{className:"text-xs text-green-700 dark:text-green-400 font-medium",children:"Total a Receber"}),a("p",{className:"text-xl font-bold text-green-600 dark:text-green-400",children:["R$ ",E.toFixed(2)]}),a("p",{className:"text-xs text-muted-foreground",children:[t.length," ",t.length===1?"cliente":"clientes"]})]}),a("div",{className:"flex gap-1 bg-muted p-1 rounded-lg",children:[e(j,{size:"sm",variant:o==="cards"?"default":"ghost",onClick:()=>m("cards"),children:e(Mr,{className:"h-4 w-4"})}),e(j,{size:"sm",variant:o==="list"?"default":"ghost",onClick:()=>m("list"),children:e(Rr,{className:"h-4 w-4"})})]})]})]})}),e(ee,{children:s?a("div",{className:"text-center py-8 inline-flex items-center gap-2 text-muted-foreground",children:[e(ba,{className:"h-4 w-4 animate-spin"}),"Carregando..."]}):N()})]}),t.length>0&&a(K,{children:[e(te,{children:a("div",{className:"flex items-center justify-between",children:[a("div",{children:[a(ne,{className:"text-lg inline-flex items-center gap-2",children:[e(Ca,{className:"h-5 w-5 text-orange-600"}),"Análise de Inadimplência (Aging)"]}),e(Se,{children:"Distribuição das dÃvidas por perÃodo de atraso"})]}),a(j,{variant:"outline",size:"sm",onClick:()=>y(!x),children:[x?"Ocultar":"Mostrar"," Detalhes"]})]})}),x&&a(ee,{children:[e("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4 mb-6",children:b.map((C,A)=>a("div",{className:`p-4 rounded-lg border-2 ${C.count>0?"border-current":"border-gray-200 dark:border-gray-700 opacity-50"}`,children:[e("div",{className:`inline-flex items-center px-2 py-1 rounded text-xs font-semibold mb-2 ${C.color}`,children:C.label}),a("p",{className:"text-xs text-muted-foreground mb-1",children:[C.days," dias"]}),a("div",{className:"space-y-1",children:[a("p",{className:"text-2xl font-bold",children:["R$ ",C.amount.toFixed(2)]}),a("p",{className:"text-sm text-muted-foreground",children:[C.count," ",C.count===1?"cliente":"clientes"]})]})]},A))}),b[3].count>0&&e("div",{className:"bg-red-50 dark:bg-red-950/30 border-l-4 border-red-500 p-4 rounded",children:a("div",{className:"flex items-start gap-3",children:[e(na,{className:"h-6 w-6 text-red-600 dark:text-red-400"}),a("div",{children:[a("p",{className:"font-semibold text-red-800 dark:text-red-400",children:["Atenção: ",b[3].count," ",b[3].count===1?"cliente inadimplente":"clientes inadimplentes"]}),a("p",{className:"text-sm text-red-700 dark:text-red-400 mt-1",children:["Há clientes com dÃvidas há mais de 90 dias no valor total de"," ",a("strong",{children:["R$ ",b[3].amount.toFixed(2)]}),". Considere ações de cobrança ou renegociação."]})]})]})}),e("div",{className:"mt-4 bg-blue-50 dark:bg-blue-950/30 border-l-4 border-blue-500 p-4 rounded",children:a("p",{className:"text-sm text-blue-800 dark:text-blue-300",children:[a("strong",{className:"inline-flex items-center gap-1",children:[e(ca,{className:"h-4 w-4"}),"Dica Profissional:"]})," Clientes com dÃvidas acima de 60 dias têm baixa taxa de recuperação. Priorize cobranças de clientes entre 31-60 dias para melhor resultado."]})})]})]}),d&&e(Ms,{open:u,onOpenChange:i,customer:d,onSuccess:()=>{M(),i(!1),g(null)}})]})}function Co(){const[t,r]=_.useState([]),[s,n]=_.useState(!0),[o,m]=_.useState(new Date),[u,i]=_.useState(0),[d,g]=_.useState(()=>{const N=localStorage.getItem("payment-history-view-mode");return N==="list"||N==="cards"?N:"cards"});_.useEffect(()=>{x()},[o]),_.useEffect(()=>{localStorage.setItem("payment-history-view-mode",d)},[d]);const x=async()=>{try{n(!0);const{data:{user:N}}=await v.auth.getUser();if(!N)return;const C=qa(o),A=Xa(o),{data:f,error:$}=await v.from("accounts_payable").select("*").eq("user_id",N.id).eq("paid",!0).gte("due_date",de(C,"yyyy-MM-dd")).lte("due_date",de(A,"yyyy-MM-dd")).order("payment_date",{ascending:!1});if($)throw $;r(f||[]);const S=(f||[]).reduce((Z,z)=>Z+(Number(z.monthly_equivalent??z.amount)||0),0);i(S)}catch(N){console.error("Erro ao carregar histórico:",N)}finally{n(!1)}},y=()=>{m(Is(o,1))},M=()=>{m(Ha(o,1))},E=()=>{m(new Date)},h=async N=>{if(confirm("Deseja realmente desfazer este pagamento?"))try{const{error:C}=await v.from("accounts_payable").update({paid:!1,payment_date:null}).eq("id",N);if(C)throw C;ue.success("Pagamento desfeito com sucesso!"),x()}catch(C){console.error("Erro ao desfazer pagamento:",C),ue.error("Erro ao desfazer pagamento")}},c=N=>{const C=(N==null?void 0:N.toLowerCase())||"";
73return C.includes("aluguel")?"bg-purple-100 dark:bg-purple-950/40 text-purple-700 dark:text-purple-400":C.includes("fornecedor")?"bg-blue-100 dark:bg-blue-950/40 text-blue-700 dark:text-blue-400":C.includes("salário")||C.includes("prolabore")?"bg-green-100 dark:bg-green-950/40 text-green-700 dark:text-green-400":C.includes("imposto")||C.includes("taxa")?"bg-red-100 dark:bg-red-950/40 text-red-700 dark:text-red-400":C.includes("energia")||C.includes("água")||C.includes("internet")?"bg-yellow-100 dark:bg-yellow-950/40 text-yellow-700 dark:text-yellow-400":"bg-gray-100 dark:bg-gray-800/50 text-gray-700 dark:text-gray-400"},b=N=>{const C=(N==null?void 0:N.toLowerCase())||"";return C.includes("custo_fixo")||C==="custo fixo"?e(ae,{variant:"outline",className:"bg-blue-50 dark:bg-blue-950/30 text-blue-700 dark:text-blue-400 border-blue-200 dark:border-blue-800",children:"Custo Fixo"}):C.includes("custo_variavel")||C==="custo variavel"?e(ae,{variant:"outline",className:"bg-green-50 dark:bg-green-950/30 text-green-700 dark:text-green-400 border-green-200 dark:border-green-800",children:"Custo Variável"}):C.includes("despesa_fixa")||C==="despesa fixa"?e(ae,{variant:"outline",className:"bg-purple-50 dark:bg-purple-950/30 text-purple-700 dark:text-purple-400 border-purple-200 dark:border-purple-800",children:"Despesa Fixa"}):C.includes("despesa_variavel")||C==="despesa variavel"?e(ae,{variant:"outline",className:"bg-orange-50 dark:bg-orange-950/30 text-orange-700 dark:text-orange-400 border-orange-200 dark:border-orange-800",children:"Despesa Variável"}):e(ae,{variant:"outline",className:"bg-gray-50 dark:bg-gray-800/30 text-gray-700 dark:text-gray-400",children:"Não Classificado"})};return s?e("div",{className:"flex items-center justify-center p-12",children:a("div",{className:"text-center space-y-4",children:[e(ba,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),e("p",{className:"text-muted-foreground",children:"Carregando histórico de pagamentos..."})]})}):a("div",{className:"space-y-6",children:[a(K,{className:"bg-gradient-to-r from-green-50 to-emerald-50 dark:from-green-950/30 dark:to-emerald-950/30 border-green-200 dark:border-green-800",children:[a(te,{children:[a(ne,{className:"flex items-center gap-2",children:[e($e,{className:"h-6 w-6 text-green-600 dark:text-green-400"}),"Histórico de Pagamentos"]}),e(Se,{children:"Visualize todas as contas já pagas organizadas por mês"})]}),e(ee,{children:a("div",{className:"flex items-center justify-between gap-4",children:[a("div",{className:"flex items-center gap-2",children:[a(j,{variant:"outline",size:"sm",onClick:y,className:"h-9",children:[e(Rs,{className:"h-4 w-4"}),"Anterior"]}),a(j,{variant:"outline",size:"sm",onClick:E,className:"h-9 min-w-[140px]",children:[e(je,{className:"h-4 w-4 mr-2"}),de(o,"MMMM yyyy",{locale:Fa})]}),a(j,{variant:"outline",size:"sm",onClick:M,className:"h-9",children:["Próximo",e(Ds,{className:"h-4 w-4"})]})]}),a("div",{className:"text-right",children:[e("p",{className:"text-sm text-muted-foreground",children:"Total Pago no Mês"}),a("p",{className:"text-2xl font-bold text-green-600 dark:text-green-400",children:["R$ ",u.toFixed(2)]}),a("p",{className:"text-xs text-muted-foreground",children:[t.length," ",t.length===1?"conta paga":"contas pagas"]})]})]})})]}),a("div",{className:"flex justify-between items-center",children:[a("h3",{className:"text-lg font-semibold",children:["Pagamentos de ",de(o,"MMMM yyyy",{locale:Fa})]}),a("div",{className:"flex gap-2",children:[e(j,{variant:d==="cards"?"default":"outline",size:"sm",onClick:()=>g("cards"),children:"Cards"}),e(j,{variant:d==="list"?"default":"outline",size:"sm",onClick:()=>g("list"),children:"Lista"})]})]}),t.length===0?a(Fe,{children:[e($s,{className:"h-4 w-4"}),a(Ie,{children:["Nenhuma conta paga encontrada em ",de(o,"MMMM yyyy",{locale:Fa}),"."]})]}):d==="cards"?e("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:t.map(N=>a(K,{className:"border-green-200 dark:border-green-800 bg-green-50/30 dark:bg-green-950/20",children:[e(te,{className:"pb-3",children:a("div",{className:"flex items-start justify-between",children:[a("div",{className:"flex-1",children:[a(ne,{className:"text-base flex items-center gap-2",children:[e($e,{className:"h-4 w-4 text-green-600"}),N.description]}),e(Se,{className:"mt-1",children:N.supplier_name||"Sem fornecedor"})]}),e(ae,{className:_e("ml-2",c(N.category)),children:N.category||"Sem categoria"})]})}),a(ee,{className:"space-y-3",children:[a("div",{className:"flex items-center justify-between",children:[a("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e(aa,{className:"h-3 w-3"}),"Valor Pago"]}),a("span",{className:"font-bold text-green-600 dark:text-green-400",children:["R$ ",(N.monthly_equivalent??N.amount).toFixed(2)]})]}),a("div",{className:"flex items-center justify-between",children:[a("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e(Fs,{className:"h-3 w-3"}),"Classificação"]}),b(N.cost_classification)]}),a("div",{className:"flex items-center justify-between text-sm",children:[a("span",{className:"text-muted-foreground flex items-center gap-1",children:[e(je,{className:"h-3 w-3"}),"Vencimento"]}),e("span",{children:Ze(N.due_date)})]}),N.payment_date&&a("div",{className:"flex items-center justify-between text-sm",children:[a("span",{className:"text-muted-foreground flex items-center gap-1",children:[e($e,{className:"h-3 w-3"}),"Pago em"]}),e("span",{className:"text-green-600 dark:text-green-400 font-medium",children:Ze(N.payment_date)})]}),N.payment_method&&a("div",{className:"flex items-center justify-between text-sm",children:[e("span",{className:"text-muted-foreground",children:"Método"}),e(ae,{variant:"secondary",children:N.payment_method})]}),N.notes&&e("div",{className:"pt-2 border-t",children:a("p",{className:"text-xs text-muted-foreground flex items-start gap-1",children:[e(da,{className:"h-3 w-3 mt-0.5"}),N.notes]})}),a("div",{className:"flex gap-2 pt-2 border-t",children:[a(j,{size:"sm",variant:"outline",onClick:()=>h(N.id),className:"flex-1",children:[e(nr,{className:"h-3 w-3 mr-1"}),"Desfazer"]}),N.receipt_url&&a(j,{size:"sm",variant:"outline",onClick:()=>window.open(N.receipt_url,"_blank"),className:"flex-1",children:[e(
73or,{className:"h-3 w-3 mr-1"}),"Recibo"]})]})]})]},N.id))}):e(K,{children:e(ee,{className:"p-0",children:e("div",{className:"overflow-x-auto",children:a("table",{className:"w-full",children:[e("thead",{className:"bg-muted/50",children:a("tr",{children:[e("th",{className:"text-left p-3 text-sm font-medium",children:"Descrição"}),e("th",{className:"text-left p-3 text-sm font-medium",children:"Fornecedor"}),e("th",{className:"text-left p-3 text-sm font-medium",children:"Categoria"}),e("th",{className:"text-left p-3 text-sm font-medium",children:"Classificação"}),e("th",{className:"text-right p-3 text-sm font-medium",children:"Valor"}),e("th",{className:"text-center p-3 text-sm font-medium",children:"Vencimento"}),e("th",{className:"text-center p-3 text-sm font-medium",children:"Pagamento"}),e("th",{className:"text-center p-3 text-sm font-medium",children:"Ações"})]})}),e("tbody",{children:t.map(N=>a("tr",{className:"border-t hover:bg-muted/30",children:[e("td",{className:"p-3",children:a("div",{className:"flex items-center gap-2",children:[e($e,{className:"h-4 w-4 text-green-600"}),e("span",{className:"font-medium",children:N.description})]})}),e("td",{className:"p-3 text-sm text-muted-foreground",children:N.supplier_name||"-"}),e("td",{className:"p-3",children:e(ae,{className:_e("text-xs",c(N.category)),children:N.category||"Sem categoria"})}),e("td",{className:"p-3",children:b(N.cost_classification)}),a("td",{className:"p-3 text-right font-bold text-green-600 dark:text-green-400",children:["R$ ",(N.monthly_equivalent??N.amount).toFixed(2)]}),e("td",{className:"p-3 text-center text-sm",children:Ze(N.due_date)}),e("td",{className:"p-3 text-center text-sm text-green-600 dark:text-green-400 font-medium",children:N.payment_date?Ze(N.payment_date):"-"}),e("td",{className:"p-3",children:a("div",{className:"flex gap-1 justify-center",children:[e(j,{size:"sm",variant:"ghost",onClick:()=>h(N.id),title:"Desfazer pagamento",children:e(nr,{className:"h-4 w-4 text-orange-600"})}),N.receipt_url&&e(j,{size:"sm",variant:"ghost",title:"Baixar comprovante",onClick:()=>window.open(N.receipt_url,"_blank"),children:e(or,{className:"h-4 w-4 text-blue-600"})})]})})]},N.id))})]})})})}),t.length>0&&a(K,{children:[e(te,{children:e(ne,{className:"text-lg",children:"Resumo por Classificação"})}),e(ee,{children:e("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:["custo_fixo","custo_variavel","despesa_fixa","despesa_variavel"].map(N=>{const C=t.filter($=>{var S,Z;return((S=$.cost_classification)==null?void 0:S.toLowerCase().includes(N.replace("_"," ")))||((Z=$.cost_classification)==null?void 0:Z.toLowerCase())===N}).reduce(($,S)=>$+(Number(S.monthly_equivalent??S.amount)||0),0),A=t.filter($=>{var S,Z;return((S=$.cost_classification)==null?void 0:S.toLowerCase().includes(N.replace("_"," ")))||((Z=$.cost_classification)==null?void 0:Z.toLowerCase())===N}).length;return a("div",{className:"bg-muted/30 rounded-lg p-4",children:[e("p",{className:"text-xs text-muted-foreground mb-1",children:N==="custo_fixo"?"Custos Fixos":N==="custo_variavel"?"Custos Variáveis":N==="despesa_fixa"?"Despesas Fixas":"Despesas Variáveis"}),a("p",{className:"text-lg font-bold",children:["R$ ",C.toFixed(2)]}),a("p",{className:"text-xs text-muted-foreground",children:[A," ",A===1?"conta":"contas"]})]},N)})})})]})]})}const Kr=_.createContext(void 0);function ko({children:t}){const[r,s]=_.useState(()=>localStorage.getItem("financial_mode")||"beginner"),n=m=>{s(m),localStorage.setItem("financial_mode",m)},o=(m,u)=>r==="professional"?m:u;return e(Kr.Provider,{value:{mode:r,setMode:n,t:o},children:t})}function Zr(){const t=_.useContext(Kr);if(!t)throw new Error("useFinancialMode deve ser usado dentro de FinancialModeProvider");return t}const Ao={dashboard:{professional:"Dashboard",beginner:"Visão Geral"},accountsPayable:{professional:"Contas a Pagar",beginner:"Minhas Contas"},accountsReceivable:{professional:"Contas a Receber",beginner:"Dinheiro a Receber"},paymentHistory:{professional:"Histórico de Pagamentos",beginner:"O que Já Paguei"},indicators:{professional:"Indicadores Financeiros",beginner:"Saúde do Negócio"},dre:{professional:"DRE",beginner:"Lucro e PrejuÃzo"},breakEven:{professional:"Ponto de EquilÃbrio",beginner:"Quanto Preciso Vender"},aiAnalysis:{professional:"Análise IA",beginner:"Ajuda Inteligente"},bankAccounts:{professional:"Contas Bancárias",beginner:"Meus Bancos"},bankImport:{professional:"Importar Extrato",beginner:"Subir Extrato"},bankBalance:{professional:"Saldo em Bancos",beginner:"Dinheiro no Banco"},healthScore:{professional:"Saúde Financeira",beginner:"Como Está Meu Negócio"},monthlyIncome:{professional:"Receitas do Mês",beginner:"Quanto Entrou"},monthlyExpenses:{professional:"Despesas do Mês",beginner:"Quanto Gastei"},netFlow:{professional:"Fluxo LÃquido",beginner:"Sobrou ou Faltou"},cashProjection:{professional:"Projeção de Caixa",beginner:"Quanto Vai Sobrar"},cashBalance:{professional:"Saldo do Caixa",beginner:"Dinheiro DisponÃvel"},paid:{professional:"Pagas",beginner:"Já Paguei"},pending:{professional:"Pendentes",beginner:"Ainda Não Paguei"},overdue:{professional:"Vencidas",beginner:"Atrasadas"},fixedCosts:{professional:"Custos Fixos",beginner:"Gastos Todo Mês"},variableCosts:{professional:"Custos Variáveis",beginner:"Gastos que Variam"},fixedExpenses:{professional:"Despesas Fixas",beginner:"Contas Fixas"},variableExpenses:{professional:"Despesas Variáveis",beginner:"Contas que Mudam"},grossRevenue:{professional:"Receita Bruta",beginner:"Total de Vendas"},contributionMargin:{professional:"Margem de Contribuição",beginner:"Quanto Sobra das Vendas"},operatingProfit:{professional:"Lucro Operacional",beginner:"Lucro do Negócio"},netProfit:{professional:"Lucro LÃquido",beginner:"Lucro Final"},breakEvenRevenue:{professional:"Faturamento de EquilÃbrio",beginner:"Quanto Preciso Faturar"},safetyMargin:{professional:"Margem de Segurança",beginner:"Folga de Segurança"},currentRevenue:{professional:"Faturamento Atual",beginner:"Quanto Estou Vendendo"},liquidity:{professional:"Liquidez",beginner:"Capacidade de Pagar"},profitability:{professional:"Rentabilidade",beginner:"Quanto Lucro"},indebtedness:{professional:"Endividamento",beginner:"Quanto Devo"},activity:{professional:"Atividade",beginner:"Giro do Negócio"},workingCapital:{professional:"Capital de Giro",beginner:"Dinheiro para Trabalhar"},supplier:{professional:"Fornecedor",beginner:"De Quem Compro"},customer:{professional:"Cliente",beginner:"Quem Me Deve"},category:{professional:"Categoria",beginner:"Tipo de Gasto"},dueDate:{professional:"Data de Vencimento",beginner:"Vence em"},paymentDate:{professional:"Data de Pagamento",beginner:"Paguei em"},description:{professional:"Descrição",beginner:"O que é"},amount:{professional:"Valor",beginner:"Quanto"},installments:{professional:"Parcelamento",beginner:"Dividido em"},total:{professional:"Total",beginner:"Tudo Junto"}};function Ut(){const{mode:t}
73=Zr();return{mode:t,get:r=>{const s=Ao[r];return t==="professional"?s.professional:s.beginner},t:(r,s)=>t==="professional"?r:s}}function Eo(){const[t,r]=_.useState(null),[s,n]=_.useState(!0),o=Ut();_.useEffect(()=>{m()},[]);const m=async()=>{var d,g,x;try{n(!0);const{data:{user:y}}=await v.auth.getUser();if(!y)return;const M=new Date,E=M.getMonth(),h=M.getFullYear(),c=new Date(h,E,1),b=new Date(h,E+1,0),{data:N}=await v.from("accounts_payable").select("*").eq("user_id",y.id),C=new Date(h,E,1),A=(N||[]).filter(l=>{const T=new Date(l.due_date+"T00:00:00"),Ne=T.getMonth()===E&&T.getFullYear()===h,J=T<M&&!l.paid,Re=l.paid&&T<C;return Ne||J||Re}),f=A.filter(l=>l.paid).length,$=A.filter(l=>!l.paid).length,S=A.filter(l=>l.paid?!1:new Date(l.due_date)<M).length,Z=A.reduce((l,T)=>l+Number(T.monthly_equivalent??T.amount),0),z=A.filter(l=>l.paid).reduce((l,T)=>l+Number(T.monthly_equivalent??T.amount),0),X=A.filter(l=>!l.paid).reduce((l,T)=>l+Number(T.monthly_equivalent??T.amount),0),me=A.filter(l=>l.paid?!1:new Date(l.due_date)<M).reduce((l,T)=>l+Number(T.monthly_equivalent??T.amount),0),{data:we}=await v.from("customers").select("balance").eq("user_id",y.id).gt("balance",0),Y=(we||[]).reduce((l,T)=>l+Number(T.balance),0),{data:P}=await v.from("products").select("id, name, stock_quantity, material_cost, labor_cost, depreciation_cost, other_costs, final_price").eq("user_id",y.id),w=new Date;w.setDate(w.getDate()-30);const{data:O}=await wa(v.from("sales").select("subtotal").eq("user_id",y.id).gte("created_at",w.toISOString())),H=(O||[]).reduce((l,T)=>l+Number(T.subtotal),0),I=H/30;let U=0,se=0,le=0;(P||[]).forEach(l=>{const T=Number(l.stock_quantity||0);if(T===0)return;const Ne=Number(l.material_cost||0)+Number(l.labor_cost||0)+Number(l.depreciation_cost||0)+Number(l.other_costs||0);if(Ne>0)U+=T*Ne,se++;else{const J=Number(l.final_price||0);if(J>0){const Re=J/1.6;U+=T*Re,le++}}}),U===0&&H>0&&(U=I*15*.6);const{data:ce}=await wa(v.from("sales").select("subtotal").eq("user_id",y.id).gte("created_at",c.toISOString()).lte("created_at",b.toISOString())),R=(ce||[]).reduce((l,T)=>l+Number(T.subtotal),0),pe=E===0?11:E-1,B=E===0?h-1:h,F=new Date(B,pe,1),W=new Date(B,pe+1,0),{data:D}=await wa(v.from("sales").select("subtotal").eq("user_id",y.id).gte("created_at",F.toISOString()).lte("created_at",W.toISOString())),re=(D||[]).reduce((l,T)=>l+Number(T.subtotal),0),{data:k}=await Ua(v.from("cash_register").select("*").eq("user_id",y.id).in("type",["opening","closing"]).order("created_at",{ascending:!1}).limit(1)),ke=((d=k==null?void 0:k[0])==null?void 0:d.type)==="opening",Q=ke&&Number((g=k==null?void 0:k[0])==null?void 0:g.amount)||0,p=((x=k==null?void 0:k[0])==null?void 0:x.created_at)||c.toISOString(),{data:oe}=await Ua(v.from("cash_register").select("*").eq("user_id",y.id).gte("created_at",p).neq("type","opening").neq("type","closing")),he=(oe||[]).filter(l=>l.type==="entry").reduce((l,T)=>l+Number(T.amount),0),ye=(oe||[]).filter(l=>l.type==="withdrawal").reduce((l,T)=>l+Number(T.amount),0),ge=Q+he-ye,{data:Pe}=await v.from("bank_accounts").select("current_balance").eq("user_id",y.id).eq("is_active",!0),Ue=(Pe||[]).reduce((l,T)=>l+Number(T.current_balance||0),0),Xe=(Pe==null?void 0:Pe.length)||0,Ge=z,xe=R-Ge,q=ge+Ue-X;let L=50;xe>0&&(L+=20),S===0&&(L+=15),ge+Ue>=X&&(L+=15),S>0&&A.length>0&&S/A.length>.2&&(L-=10),q<0&&(L-=15),L=Math.min(100,Math.max(0,L));const V=re>0?(R-re)/re*100:0;r({accountsPayable:{total:A.length,paid:f,pending:$,overdue:S,totalAmount:Z,paidAmount:z,pendingAmount:X,overdueAmount:me},accountsReceivable:{total:(we==null?void 0:we.length)||0,totalAmount:Y},cashRegister:{isOpen:ke,balance:ge},bankAccounts:{count:Xe,totalBalance:Ue},inventory:{totalValue:U,totalItems:(P==null?void 0:P.length)||0,productsWithCost:se,productsWithoutCost:le,salesLast30Days:H},healthScore:L,cashFlow:q,monthlyIncome:R,monthlyExpenses:Ge,netFlow:xe,previousMonthIncome:re,incomeVariation:V})}catch(y){console.error("Erro ao carregar dashboard:",y)}finally{n(!1)}};if(s||!t)return e("div",{className:"text-center py-12 text-muted-foreground",children:a("div",{className:"inline-flex items-center gap-2",children:[e(ba,{className:"h-4 w-4 animate-spin"}),"Carregando dashboard..."]})});const u=d=>d>=80?"text-green-600 dark:text-green-400 bg-green-50 dark:bg-green-950/30 border-green-200 dark:border-green-800":d>=60?"text-yellow-600 dark:text-yellow-400 bg-yellow-50 dark:bg-yellow-950/30 border-yellow-200 dark:border-yellow-800":"text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-950/30 border-red-200 dark:border-red-800",i=d=>d>=80?"Excelente":d>
73=60?"Bom":d>=40?"Atenção":"CrÃtico";return a("div",{className:"space-y-6",children:[t.accountsPayable.overdue>0&&a(Fe,{variant:"destructive",className:"border-red-300 dark:border-red-800 bg-red-50 dark:bg-red-950/30",children:[e(Me,{className:"h-5 w-5"}),e(Ar,{className:"font-bold",children:" Atenção: Contas Vencidas!"}),a(Ie,{children:["Você tem ",a("strong",{children:[t.accountsPayable.overdue," ",t.accountsPayable.overdue===1?"conta vencida":"contas vencidas"]})," no valor de"," ",e("strong",{className:"text-red-700",children:ie(t.accountsPayable.overdueAmount)}),". Regularize o quanto antes para manter seu crédito."]})]}),a(K,{className:`border-2 ${u(t.healthScore)}`,children:[a(te,{children:[a(ne,{className:"flex items-center gap-2",children:[e(Ca,{className:"h-5 w-5"}),o.get("healthScore")]}),e(Se,{children:o.t("Indicador consolidado baseado em fluxo de caixa, contas em dia e disponibilidade","Mostra como está a saúde do seu negócio")})]}),e(ee,{children:a("div",{className:"space-y-4",children:[a("div",{className:"flex items-center justify-between",children:[a("div",{className:"text-4xl font-bold",children:[t.healthScore,"/100"]}),e(ae,{className:u(t.healthScore),children:i(t.healthScore)})]}),e(Ia,{value:t.healthScore,className:"h-3"})]})})]}),a("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[a(K,{children:[a(te,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e(ne,{className:"text-sm font-medium",children:o.get("monthlyIncome")}),e(aa,{className:"h-4 w-4 text-green-600"})]}),a(ee,{children:[e("div",{className:"text-2xl font-bold text-green-600",children:ie(t.monthlyIncome)}),a("div",{className:"flex items-center justify-between mt-2",children:[e("p",{className:"text-xs text-muted-foreground",children:o.t("Vendas realizadas","Total de vendas")}),t.previousMonthIncome>0&&a(ae,{variant:"outline",className:`text-xs ${t.incomeVariation>0?"bg-green-50 dark:bg-green-950/30 text-green-700 dark:text-green-400 border-green-200 dark:border-green-800":t.incomeVariation<0?"bg-red-50 dark:bg-red-950/30 text-red-700 dark:text-red-400 border-red-200 dark:border-red-800":"bg-gray-50 dark:bg-gray-900/30 text-gray-700 dark:text-gray-400 border-gray-200 dark:border-gray-700"}`,children:[t.incomeVariation>0?"â":t.incomeVariation<0?"â":"â"," ",Math.abs(t.incomeVariation).toFixed(1),"%"]})]})]})]}),a(K,{children:[a(te,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e(ne,{className:"text-sm font-medium",children:o.get("monthlyExpenses")}),e(ta,{className:"h-4 w-4 text-red-600"})]}),a(ee,{children:[e("div",{className:"text-2xl font-bold text-red-600",children:ie(t.monthlyExpenses)}),e("p",{className:"text-xs text-muted-foreground mt-1",children:o.t("Contas pagas","O que já paguei")})]})]}),a(K,{children:[a(te,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e(ne,{className:"text-sm font-medium",children:o.get("netFlow")}),t.netFlow>=0?e(Oe,{className:"h-4 w-4 text-green-600"}):e(Qa,{className:"h-4 w-4 text-red-600"})]}),a(ee,{children:[e("div",{className:`text-2xl font-bold ${t.netFlow>=0?"text-green-600":"text-red-600"}`,children:ie(t.netFlow)}),e("p",{className:"text-xs text-muted-foreground mt-1",children:o.t("Receitas - Despesas","Entrou - Gastei")})]})]}),a(K,{children:[a(te,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e(ne,{className:"text-sm font-medium",children:o.get("cashProjection")}),e(ea,{className:"h-4 w-4 text-blue-600"})]}),a(ee,{children:[e("div",{className:`text-2xl font-bold ${t.cashFlow>=0?"text-blue-600":"text-red-600"}`,children:ie(t.cashFlow)}),e("p",{className:"text-xs text-muted-foreground mt-1",children:o.t("Caixa + bancos â contas pendentes do mês","Depois de pagar o que falta este mês")})]})]})]}),a(K,{children:[e(te,{children:a(ne,{className:"flex items-center gap-2",children:[e(ta,{className:"h-5 w-5 text-red-600"}),"Contas a Pagar - Visão Geral"]})}),a(ee,{children:[a("div",{className:"grid gap-4 md:grid-cols-4",children:[a("div",{className:"space-y-2",children:[a("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e($e,{className:"h-4 w-4 text-green-600"}),"Pagas"]}),e("div",{className:"text-2xl font-bold text-green-600",children:t.accountsPayable.paid}),e("div",{className:"text-sm text-muted-foreground",children:ie(t.accountsPayable.paidAmount)})]}),a("div",{className:"space-y-2",children:[a("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e(sa,{className:"h-4 w-4 text-yellow-600"}),"Pendentes"]}),e("div",{className:"text-2xl font-bold text-yellow-600",children:t.accountsPayable.pending}),e("div",{className:"text-sm text-muted-foreground",children:ie(t.accountsPayable.pendingAmount)})]}),a("div",{className:"space-y-2",children:[a("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e(Me,{className:"h-4 w-4 text-red-600"}),"Vencidas"]}),e("div",{className:"text-2xl font-bold text-red-600",children:t.accountsPayable.overdue}),e("div",{className:"text-sm text-muted-foreground",children:ie(t.accountsPayable.overdueAmount)})]}),a("div",{className:"space-y-2",children:[a("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e(ta,{className:"h-4 w-4"}),"Total"]}),e("div",{className:"text-2xl font-bold",children:t.accountsPayable.total}),e("div",{className:"text-sm text-muted-foreground",children:ie(t.accountsPayable.totalAmount)})]})]}),t.accountsPayable.total>0&&a("div",{className:"mt-6 space-y-2",children:[a("div",{className:"flex justify-between text-sm",children:[e("span",{children:"Progresso de Pagamento"}),e("span",{className:"font-medium",children:Te(t.accountsPayable.paidAmount/t.accountsPayable.totalAmount)})]}),e(Ia,{value:t.accountsPayable.paidAmount/t.accountsPayable.totalAmount*100,className:"h-2"})]})]})]}),a("div",{className:"grid gap-4 md:grid-cols-2",children:[a(K,{className:"border-blue-200 dark:border-blue-800 bg-gradient-to-br from-blue-50/50 to-cyan-50/50 dark:from-blue-950/30 dark:to-cyan-950/30",children:[a(te,{children:[a(ne,{className:"flex items-center gap-2 text-blue-700 dark:text-blue-400 text-base",children:[e(ea,{className:"h-5 w-5"}),o.get("cashBalance")]}),e(Se,{children:o.t("Movimentações do PDV / caixa fÃsico","Dinheiro na gaveta do caixa")})]}),a(ee,{children:[e("div",{className:`text-3xl font-bold ${t.cashRegister.balance>=0?"text-blue-600":"text-red-600"}`,children:ie(t.cashRegister.balance)}),e("p",{className:"text-sm text-muted-foreground mt-1",children:t.cashRegister.isOpen?"Caixa aberto":"Caixa fechado"})]})]}),a(K,{className:"border-indigo-200 dark:border-indigo-800 bg-gradient-to-br from-indigo-50/50 to-violet-50/50 dark:from-indigo-950/30 dark:to-violet-950/30",children:[a(te,{children:[a(ne,{className:"flex items-center gap-2 text-indigo-700 dark:text-indigo-400 text-base",children:[e(ea,{className:"h-5 w-5"}),o.get("bankBalance")]}),e(Se,{children:o.t("Soma das contas em Financeiro â Bancos","Contas cadastradas no app")})]}),a(ee,{children:[e("div",{className:`text-3xl font-bold ${t.bankAccounts.totalBalance>=0?"text-indigo-600":"text-red-600"}`,children:ie(t.bankAccounts.totalBalance)}),e("p",{className:"text-sm text-muted-foreground mt-1",children:t.bankAccounts.count===0?"Nenhuma conta cadastrada â use a aba Bancos":`${t.bankAccounts.count} ${t.bankAccounts.count===1?"conta ativa":"contas ativas"}`})]})]})]}),a("div",{className:"grid gap-4 md:grid-cols-2",children:[a(K,{className:"border-green-200 dark:border-green-800 bg-gradient-to-br from-green-50/50 to-emerald-50/50 dark:from-green-950/30 dark:to-emerald-950/30",children:[e(te,{children:a(ne,{className:"flex items-center gap-2 text-green-700 dark:text-green-400",children:[e(Ke,{className:"h-5 w-5"}),"Contas a Receber"]})}),e(ee,{children:a("div",{className:"space-y-2",children:[e("div",{className:"text-3xl font-bold text-green-600 dark:text-green-400",children:ie(t.accountsReceivable.totalAmount)}),a("p",{className:"text-sm text-muted-foreground",children:[t.accountsReceivable.total," ",t.accountsReceivable.total===1?"cliente":"clientes"," com saldo devedor"]})]})})]}),a(K,{className:"border-purple-200 dark:border-purple-800 bg-gradient-to-br from-purple-50/50 to-pink-50/50 dark:from-purple-950/30 dark:to-pink-950/30",children:[e(te,{children:a(ne,{className:"flex items-center gap-2 text-purple-700 dark:text-purple-300",children:[e(va,{className:"h-5 w-5"}),"Estoque"]})}),e(ee,{children:a("div",{className:"space-y-2",children:[e("div",{className:"text-3xl font-bold text-purple-600 dar
73k:text-purple-400",children:ie(t.inventory.totalValue)}),a("p",{className:"text-sm text-muted-foreground",children:[t.inventory.totalItems," ",t.inventory.totalItems===1?"produto":"produtos"," em estoque"]}),a("div",{className:"mt-3 p-2 bg-purple-50 dark:bg-purple-950/30 rounded text-xs text-purple-800 dark:text-purple-300",children:[e("p",{className:"font-medium",children:" Cálculo Inteligente:"}),e("p",{className:"mt-1",children:t.inventory.productsWithCost>0&&t.inventory.productsWithoutCost===0?`Baseado em custos reais de ${t.inventory.productsWithCost} produtos`:t.inventory.productsWithCost>0&&t.inventory.productsWithoutCost>0?`${t.inventory.productsWithCost} com custo real + ${t.inventory.productsWithoutCost} estimados (margem 60%)`:t.inventory.salesLast30Days>0?"Estimado: 15 dias de vendas recentes (turnover 2x/mês)":"Cadastre custos nos produtos para precisão"})]})]})})]})]})]})}Or.vfs=kt.pdfMake?kt.pdfMake.vfs:kt.vfs;const Ra={complete:{id:"unified_financial_analysis",title:"Análise Completa 360°",description:"Análise integrada de todos os aspectos financeiros com recomendações estratégicas",icon:$a,credits:12,color:"text-purple-600",bgColor:"bg-purple-50 dark:bg-purple-950/30 border-purple-200 dark:border-purple-800"},health:{id:"financial_health_analysis",title:"Saúde Financeira",description:"Diagnóstico profundo da saúde financeira, liquidez e solvência da empresa",icon:ma,credits:5,color:"text-green-600",bgColor:"bg-green-50 dark:bg-green-950/30 border-green-200 dark:border-green-800"},dre:{id:"dre_detailed_analysis",title:"Análise DRE Detalhada",description:"Análise aprofundada do Demonstrativo de Resultado com insights sobre receitas, custos e margens",icon:Ca,credits:5,color:"text-blue-600",bgColor:"bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-800"},breakeven:{id:"breakeven_analysis",title:"Ponto de EquilÃbrio",description:"Análise de viabilidade, margem de segurança e estratégias para melhorar o break-even",icon:pa,credits:4,color:"text-orange-600",bgColor:"bg-orange-50 dark:bg-orange-950/30 border-orange-200 dark:border-orange-800"},cashflow:{id:"cashflow_projection",title:"Projeção de Fluxo de Caixa",description:"Previsão detalhada para 30 dias com cenários e alertas preventivos",icon:ea,credits:6,color:"text-cyan-600",bgColor:"bg-cyan-50 dark:bg-cyan-950/30 border-cyan-200 dark:border-cyan-800"},trends:{id:"financial_trends_predictor",title:"Tendências e Previsões",description:"Análise de padrões históricos com previsão para os próximos 3 meses",icon:Oe,credits:6,color:"text-indigo-600",bgColor:"bg-indigo-50 dark:bg-indigo-950/30 border-indigo-200 dark:border-indigo-800"},optimization:{id:"financial_optimization",title:"Otimização de Custos",description:"Identificação de oportunidades de redução de custos e melhoria de eficiência",icon:zt,credits:4,color:"text-yellow-600",bgColor:"bg-yellow-50 dark:bg-yellow-950/30 border-yellow-200 dark:border-yellow-800"},benchmark:{id:"financial_benchmark",title:"Benchmarking vs Mercado",description:"Comparação com padrões do mercado e identificação de gaps competitivos",icon:Ca,credits:4,color:"text-pink-600",bgColor:"bg-pink-50 dark:bg-pink-950/30 border-pink-200 dark:border-pink-800"}};function So({dashboardStats:t,dreData:r,breakEvenData:s,cashFlowData:n}){const[o,m]=_.useState(!1),[u,i]=_.useState("complete"),[d,g]=_.useState(""),[x,y]=_.useState([]),[M,E]=_.useState(!1),[h,c]=_.useState("professional"),[b,N]=_.useState(!1),[C,A]=_.useState(null),[f,$]=_.useState([]),[S,Z]=_.useState(""),[z,X]=_.useState(!1),[me,we]=_.useState(!1),Y=_.useRef(null),[P,w]=_.useState([]),[O,H]=_.useState(0),{toast:I}=Wa();_.useEffect(()=>{(async()=>{try{const{data:F}=await v.auth.getUser();if(!F.user)return;await ut(F.user.id,{syncPayable:!0});const{data:W,error:D}=await v.from("prolabore_partners").select("*").eq("user_id",F.user.id).eq("active",!0).order("created_at",{ascending:!1});if(D)throw console.error(" Erro ao buscar pró-labore:",D),D;W&&w(W);const re=await Ot(F.user.id);H(re.reduce((k,ke)=>k+(Number(ke.amount)||0),0))}catch(F){console.error("Erro ao carregar contexto de pró-labore:",F)}})()},[]),_.useEffect(()=>{const B=localStorage.getItem("financialAIHistory");if(B)try{const F=JSON.parse(B),W=new Date;W.setDate(W.getDate()-90);const D=F.filter(re=>new Date(re.date)>W);y(D),D.length!==F.length&&localStorage.setItem("financialAIHistory",JSON.stringify(D))}catch(F){console.error("Erro ao carregar histórico:",F)}},[]);const U=(B,F,W)=>{const D=Ra[B],k=[{id:Date.now().toString(),type:B,typeName:D.title,date:new Date().toISOString(),result:F,creditsUsed:W,preview:F.substring(0,200)+"..."},...x].slice(0,20);y(k),localStorage.setItem("financialAIHistory",JSON.stringify(k))},se=B=>{const F=t.receita||0,W=((r==null?void 0:r.despesasFixas)||0)+((r==null?void 0:r.despesasVariaveis)||0);r!=null&&r.custosVariaveis;const D=t.lucro||0,re=Nr(P.filter(V=>V.active)),k=re>0?re:(r==null?void 0:r.prolabore)||0,ke=(s==null?void 0:s.contribution_margin_pct)??(r==null?void 0:r.margemContribuicaoPct)??50,Q=_r({receitas:F,despesasSemProlabore:W,margemContribuicaoPct:ke,prolaboreAtual:k,gastosPessoais:O}),p=Q.saudavel,oe={metodo_1_lucro:`R$ ${(D*.4).toFixed(2)} (40% do lucro MC)`,metodo_2_minimo:`R$ ${Q.minimo.toFixed(2)} (mÃnimo legal/pessoal)`,metodo_escolhido:"prolaboreService (fonte única)",valor_final:`R$ ${p.toFixed(2)}`,justificativa:Q.recomendacao},he=W,ye=((s==null?void 0:s.contribution_margin_pct)||93.95)/100,ge=(he+k)/ye,Pe=(he+p)/ye,Ue=P.map(V=>({nome:V.partner_name||"Sócio",prolabore_mensal:`R$ ${(V.amount||0).toFixed(2)}`,frequencia:V.frequency||"monthly",percentual_receita:`${((V.amount||0)/(t.receita||1)*100).toFixed(1)}%`,ativo:V.active,data_inicio:V.start_date})),Xe=P.filter(V=>V.active).reduce((V,l)=>V+(l.amount||0),0),Ge={resumo_geral:{score_saude:`${t.healthScore||0}/100`,status:t.healthStatus||"N/A",caixa_disponivel:`R$ ${(t.caixaDisponivel||0).toFixed(2)}`,contas_pendentes:`${t.contasPendentes||0} contas (R$ ${(t.valorPendente||0).toFixed(2)})`,contas_vencidas:`${t.contasVencidas||0} contas (R$ ${(t.valorVencido||0).toFixed(2)}
73)`,receita_mes:`R$ ${(t.receita||0).toFixed(2)}`,lucro_mes:`R$ ${(t.lucro||0).toFixed(2)}`,fluxo_liquido:`R$ ${(t.fluxoLiquido||0).toFixed(2)}`},prolabore_cenarios:{socios_ativos:Ue,total_prolabore_socios:`R$ ${Xe.toFixed(2)}`,quantidade_socios:P.filter(V=>V.active).length,cenario_1_atual:{prolabore:`R$ ${k.toFixed(2)}`,percentual_receita:`${(k/(t.receita||1)*100).toFixed(1)}%`,ponto_equilibrio:`R$ ${ge.toFixed(2)}`,status:k>(t.receita||0)*.15?" ACIMA DO RECOMENDADO (>15%)":" OK",alerta:k>(t.receita||0)?" PRÃ-LABORE MAIOR QUE A RECEITA!":k>(t.lucro||0)?" PRÃ-LABORE MAIOR QUE O LUCRO":""},cenario_2_saudavel:{prolabore:`R$ ${p.toFixed(2)}`,percentual_receita:`${(p/(F||1)*100).toFixed(1)}%`,ponto_equilibrio:`R$ ${Pe.toFixed(2)}`,economia_anual:`R$ ${((k-p)*12).toFixed(2)}`,status:" RECOMENDADO PELO SISTEMA",calculo_detalhado:oe,observacao:"Calculado considerando receita, lucro e capacidade de caixa da sua empresa"},diferenca:{valor_mensal:`R$ ${Math.abs(k-p).toFixed(2)}`,valor_anual:`R$ ${(Math.abs(k-p)*12).toFixed(2)}`,impacto_pe:`R$ ${Math.abs(ge-Pe).toFixed(2)}`,percentual_reducao:`${((k-p)/(k||1)*100).toFixed(1)}%`},recomendacao_sistema:k>F?"CRÃTICO: Pró-labore insustentável. Ajuste imediato necessário.":k>p?"ATENÃÃO: Pró-labore acima do saudável. Considere redução gradual.":"OK: Pró-labore dentro do recomendado."},dre:r?{receita_total:`R$ ${(r.receita||0).toFixed(2)}`,custos_variaveis:`R$ ${(r.custosVariaveis||0).toFixed(2)}`,margem_contribuicao:`R$ ${(r.margemContribuicao||0).toFixed(2)} (${(r.margemContribuicaoPct||0).toFixed(1)}%)`,custos_fixos:`R$ ${(r.custosFixos||0).toFixed(2)}`,despesas_fixas:`R$ ${(r.despesasFixas||0).toFixed(2)}`,despesas_variaveis:`R$ ${(r.despesasVariaveis||0).toFixed(2)}`,prolabore:`R$ ${(r.prolabore||0).toFixed(2)}`,lucro_operacional:`R$ ${(r.lucroOperacional||0).toFixed(2)} (${(r.lucroOperacionalPct||0).toFixed(1)}%)`}:null,ponto_equilibrio:s?{vendas_minimas:`R$ ${(s.break_even_revenue||0).toFixed(2)}`,vendas_atuais:`R$ ${(s.current_revenue||0).toFixed(2)}`,margem_seguranca:`${(s.safety_margin_pct||0).toFixed(1)}%`,margem_contribuicao:`${(s.contribution_margin_pct||0).toFixed(1)}%`,custos_fixos_total:`R$ ${(s.fixed_costs||0).toFixed(2)}`,custos_variaveis_total:`R$ ${(s.variable_costs||0).toFixed(2)}`}:null,fluxo_caixa:n?{saldo_atual:`R$ ${(n.saldoAtual||0).toFixed(2)}`,entradas_previstas:`R$ ${(n.entradasPrevistas||0).toFixed(2)}`,saidas_previstas:`R$ ${(n.saidasPrevistas||0).toFixed(2)}`,saldo_final_previsto:`R$ ${(n.saldoFinal||0).toFixed(2)}`}:null},xe={professional:"Tom profissional e técnico, focado em métricas e análises precisas.",optimistic:"Tom otimista e encorajador, destacando oportunidades e pontos positivos, mas sem ignorar problemas.",realistic:"Tom realista e direto, equilibrando pontos positivos e negativos sem exageros.",cautious:"Tom cauteloso e conservador, priorizando alertas de risco e medidas preventivas.",motivational:"Tom motivacional e inspirador, focando em crescimento e superação de desafios."},L=`Você é um CFO sênior especializado em PMEs brasileiras. Analise os dados e forneça insights acionáveis. 74 75TOM DA ANÃLISE: ${xe[h]||xe.professional} 76 77DADOS: 78${JSON.stringify(Ge,null,2)} 79 80DIRETRIZES: 81â Linguagem clara para não-especialistas 82â Foco em ações práticas 83â Use emojis estrategicamente 84â Formatação Markdown estruturada 85â Valores em R$ (Reais) 86â Mantenha o tom ${h} em toda a análise`;switch(B){case"complete":return`${L} 87 88TAREFA: Análise Financeira 360° - 9 Seções 89 90 ATENÃÃO ESPECIAL: 91- Analise os DOIS CENÃRIOS de pró-labore em 'prolabore_cenarios' 92- Há ${P.filter(V=>V.active).length} sócio(s) ativo(s) recebendo pró-labore 93- Total pró-labore: R$ ${Xe.toFixed(2)}/mês 94- Considere a recomendação do sistema em sua análise 95 96## 1⣠RESUMO EXECUTIVO 97Status: [Excelente/Boa/Regular/CrÃtica] 98Principal Problema | Principal Oportunidade 99 100## 2⣠SAÃDE FINANCEIRA 101Score: ${t.healthScore||0}/100 102⢠Liquidez vs Comprometimento 103⢠Risco de insolvência 104⢠Ações imediatas 105 106## 3⣠DRE - DESEMPENHO OPERACIONAL 107${r?`Receita: R$ ${(r.receita||0).toFixed(2)} | Lucro: ${(r.lucroOperacionalPct||0).toFixed(1)}% 108Margem Contribuição: ${(r.margemContribuicaoPct||0).toFixed(1)}% (Meta: >40%) 109Pró-labore Atual: R$ ${(r.prolabore||0).toFixed(2)} vs Recomendado: R$ ${p.toFixed(2)} 110⢠Eficiência operacional 111⢠Categorias problemáticas`:"Dados DRE indisponÃveis"} 112 113## 4⣠ANÃLISE DE PRÃ-LABORE (CRÃTICO!) 114 115**METODOLOGIA DE CÃLCULO DO PRÃ-LABORE RECOMENDADO:** 116O sistema utiliza a mesma metodologia da tela de análise de pró-labore: 117 **Pró-labore Saudável = Lucro Operacional** 118 Isso garante que a empresa NÃO terá prejuÃzo após as retiradas dos sócios. 119 120Cálculo baseado nos dados REAIS da sua empresa: 121⢠Receita: R$ ${F.toFixed(2)} 122⢠Despesas: R$ ${W.toFixed(2)} 123⢠Lucro Operacional: R$ ${D.toFixed(2)} 124⢠**Pró-labore Recomendado: R$ ${p.toFixed(2)}** (100% do lucro) 125 126**INFORMAÃÃES DOS SÃCIOS:** 127${Ue.length>0?Ue.map((V,l)=>
127`Sócio ${l+1}: ${V.nome} - ${V.prolabore_mensal} (${V.percentual_receita} da receita)`).join(` 128`):"Nenhum sócio cadastrado"} 129 130**CENÃRIO 1 - ATUAL:** 131Pró-labore Total: R$ ${k.toFixed(2)} (${(k/(F||1)*100).toFixed(1)}% da receita) 132PE necessário: R$ ${ge.toFixed(2)} 133${k>F?" ALERTA CRÃTICO: Pró-labore MAIOR que a receita!":k>D?" ATENÃÃO: Pró-labore MAIOR que o lucro":""} 134 135**CENÃRIO 2 - SAUDÃVEL (CALCULADO PARA VOCÃ):** 136Pró-labore Recomendado: R$ ${p.toFixed(2)} (${(p/(F||1)*100).toFixed(1)}% da receita) 137PE necessário: R$ ${Pe.toFixed(2)} 138Economia anual: R$ ${((k-p)*12).toFixed(2)} 139${P.filter(V=>V.active).length>1?` 140 SUGESTÃO: Dividir entre ${P.filter(V=>V.active).length} sócios = R$ ${(p/P.filter(V=>V.active).length).toFixed(2)}/sócio`:""} 141 142**IMPACTO DA DECISÃO:** 143⢠Explique DETALHADAMENTE como chegamos ao valor recomendado 144⢠Compare os dois cenários com base nos dados REAIS 145⢠Analise a viabilidade considerando: receita (R$ ${F.toFixed(2)}), despesas (R$ ${W.toFixed(2)}), lucro (R$ ${D.toFixed(2)}) 146⢠Se há múltiplos sócios, sugira distribuição justa 147⢠Recomende plano de transição do cenário 1 para 2 (se necessário) 148 149## 5⣠PONTO DE EQUILÃBRIO 150${s?`PE: R$ ${(s.break_even_revenue||0).toFixed(2)} | Atual: R$ ${(s.current_revenue||0).toFixed(2)} 151Margem Segurança: ${(s.safety_margin_pct||0).toFixed(1)}% (Meta: >25%) 152⢠Distância do break-even 153⢠Ações para reduzir PE`:"Dados PE indisponÃveis"} 154 155## 6⣠GESTÃO DE CAIXA 156DisponÃvel: R$ ${(t.caixaDisponivel||0).toFixed(2)} | Vencido: R$ ${(t.valorVencido||0).toFixed(2)} 157⢠Suficiência de caixa 158⢠Priorização de pagamentos 159 160## 7⣠FLUXO DE CAIXA (30d) 161${n?`Atual: R$ ${(n.saldoAtual||0).toFixed(2)} â Final: R$ ${(n.saldoFinal||0).toFixed(2)} 162⢠Gaps de caixa identificados 163⢠Alertas preventivos`:"Dados fluxo indisponÃveis"} 164 165## 8⣠TOP 5 RISCOS CRÃTICOS 166 167**IMPORTANTE:** Use listas numeradas, NÃO use tabelas! Formato: 168 1691. **[Nome do Risco]** 170 - Impacto Financeiro: R$ X.XXX,XX (ou: Médio/Alto/CrÃtico) 171 - Probabilidade: XX% (Alta/Média/Baixa) 172 - Mitigação: [ação especÃfica para reduzir o risco] 173 - Urgência: [Imediata/Curto prazo/Médio prazo] 174 1752. **[Segundo Risco]** 176 - Impacto: ... 177 - Probabilidade: ... 178 - Mitigação: ... 179 - Urgência: ... 180 181(Continue para os 5 riscos mais crÃticos identificados nos dados) 182 183## 9⣠PLANO DE AÃÃO INTEGRADO 184**URGENTE (7 dias):** 1851. [Ação especÃfica 1, incluindo decisão sobre pró-labore se aplicável] 1862. [Ação especÃfica 2] 1873. [Ação especÃfica 3] 188 189**CURTO PRAZO (30d):** 1901. [Ação 1] 1912. [Ação 2] 1923. [Ação 3] 193 194**ESTRUTURAL (90d):** 1951. [Ação estratégica 1] 1962. [Ação estratégica 2] 197 198Use listas, emojis e seja direto. SEMPRE mencione os dois cenários de pró-labore.`;case"health":return`${L} 199 200TAREFA: Diagnóstico de Saúde Financeira 201 202## 1⣠SCORE ATUAL 203${t.healthScore||0}/100 - ${t.healthStatus||"N/A"} 204>85: Excelente | 70-85: Bom | 50-70: Regular | <50: CrÃtico 205Fatores que influenciam o score 206 207## 2⣠LIQUIDEZ 208DisponÃvel: R$ ${(t.caixaDisponivel||0).toFixed(2)} | Pendente: R$ ${(t.valorPendente||0).toFixed(2)} 209Ãndice: ${((t.caixaDisponivel||0)/(t.valorPendente||1)).toFixed(2)} (Meta: >1.5) 210Capacidade de pagamento 211 212## 3⣠GESTÃO DE CONTAS 213${t.contasPendentes||0} pendentes | ${t.contasVencidas||0} vencidas (R$ ${(t.valorVencido||0).toFixed(2)}) 214Inadimplência: ${((t.contasVencidas||0)/(t.contasPendentes||1)*100).toFixed(1)}% 215Priorização 216 217## 4⣠RENTABILIDADE 218Receita: R$ ${(t.receita||0).toFixed(2)} | Lucro: R$ ${(t.lucro||0).toFixed(2)} 219Margem: ${((t.lucro||0)/(t.receita||1)*100).toFixed(1)}% 220Geração de caixa 221 222## 5⣠PLANO DE AÃÃO 223URGENTE (7d): 3 ações | CURTO (30d): 3 ações | ESTRUTURAL (90d): 2 ações`;case"dre":return r?`${L} 224 225TAREFA: Análise DRE Detalhada 226 227## 1⣠RECEITAS & CUSTOS 228Receita: R$ ${(r.receita||0).toFixed(2)} 229Custos Variáveis: R$ ${(r.custosVariaveis||0).toFixed(2)} (${((r.custosVariaveis||0)/(r.receita||1)*100).toFixed(1)}%) 230Meta CV: <30% serviços, <60% comércio 231 232## 2⣠MARGEM CONTRIBUIÃÃO 233R$ ${(r.margemContribuicao||0).toFixed(2)} | ${(r.margemContribuicaoPct||0).toFixed(1)}% (Meta: >40%) 234Status: ${(r.margemContribuicaoPct||0)>40?"Excelente":(r.margemContribuicaoPct||0)>30?"Bom":"CrÃtico"} 235Melhorias possÃveis 236 237## 3⣠DESPESAS 238Fixas: R$ ${(r.despesasFixas||0).toFixed(2)} | Variáveis: R$ ${(r.despesasVariaveis||0).toFixed(2)} 239Total: R$ ${((r.despesasFixas||0)+(r.despesasVariaveis||0)).toFixed(2)} (${(((r.despesasFixas||0)+(r.despesasVariaveis||0))/(r.receita||1)*100).toFixed(1)}%) 240Oportunidades de corte 241 242## 4⣠PRÃ-LABORE 243R$ ${(r.prolabore||0).toFixed(2)} (${((r.prolabore||0)/(r.receita||1)*100).toFixed(1)}% - Meta: 10-15%) 244Equilibrado? 245 246## 5⣠RESULTADO 247Lucro: R$ ${(r.lucroOperacional||0).toFixed(2)} | Margem: ${(r.lucroOperacionalPct||0).toFixed(1)}% (Meta: >20%) 248 249## 6⣠COMPARATIVO VS METAS 250**Margem de Contribuição:** 251- Atual: ${(r.margemContribuicaoPct||0).toFixed(1)}% 252- Meta: >40% 253- ${(r.margemContribuicaoPct||0)>=40?" Atingiu a meta!":" Abaixo da meta"} 254 255**Margem de Lucro:** 256- Atual: ${(r.lucroOperacionalPct||0).toFixed(1)}% 257- Meta: >20% 258- ${(r.lucroOperacionalPct||0)>=20?" Atingiu a meta!":" Abaixo da meta"} 259 260## 7⣠OTIMIZAÃÃO 261â Receita | â Custos | â Despesas | Meta próximo mês`:`${L} 262 263 Dados DRE indisponÃveis`;case"breakeven":return s?`${L} 264 265TAREFA: Análise Ponto de EquilÃbrio e Estratégias Recomendadas 266 267 ATENÃÃO ESPECIAL: 268- Analise os DOIS CENÃRIOS de pró-labore em 'prolabore_cenarios' 269- O pró-labore IMPACTA DIRETAMENTE o Ponto de EquilÃbrio! 270- Há ${P.filter(V=>V.active).length} sócio(s) ativo(s) recebendo pró-labore 271- Total pró-labore atual: R$ ${Xe.toFixed(2)}/mês 272 273**DADOS PARA ANÃLISE:** 274Vendas Atuais: R$ ${(s.current_revenue||0).toFixed(2)} 275Margem de Contribuição: ${(s.contribution_margin_pct||0).toFixed(1)}% 276Custos Fixos (sem pró-labore): R$ ${(s.fixed_costs||0).toFixed(2)} 277Custos Variáveis: R$ ${(s.variable_costs||0).toFixed(2)} 278 279**CENÃRIO 1 - PRÃ-LABORE ATUAL:** 280Pró-labore: R$ ${k.toFixed(2)} (${(k/(F||1)*100).toFixed(1)}% da receita) 281Custos Fixos TOTAIS: R$ ${((s.fixed_costs||0)+k).toFixed(2)} 282PE necessário: R$ ${ge.toFixed(2)} 283Gap vs Vendas Atuais: R$ ${Math.abs((s.current_revenue||0)-ge).toFixed(2)} ${(s.current_revenue||0)>=ge?" ACIMA do PE":" ABAIXO do PE"} 284Margem de Segurança: ${(((s.current_revenue||0)-ge)/(s.current_revenue||1)*100).toFixed(1)}% 285 286**CENÃRIO 2 - PRÃ-LABORE SAUDÃVEL (RECOMENDADO):** 287Pró-labore Sugerido: R$ ${p.toFixed(2)} (${(p/(F||1)*100).toFixed(1)}% da receita) 288Custos Fixos TOTAIS: R$ ${((s.fixed_costs||0)+p).toFixed(2)} 289PE necessário: R$ ${Pe.toFixed(2)} 290Gap vs Vendas Atuais: R$ ${Math.abs((s.current_revenue||0)-Pe).toFixed(2)} ${(s.current_revenue||0)>=Pe?" ACIMA do PE":" ABAIXO do PE"} 291Margem de Segurança: ${(((s.current_revenue||0)-Pe)/(s.current_revenue||1)*100).toFixed(1)}% 292 293**IMPACTO DA MUDANÃA:** 294Redução no PE: R$ ${Math.abs(ge-Pe).toFixed(2)} 295Melhoria na Margem de Segurança: ${Math.abs(((s.current_revenue||0)-Pe)/(s.current_revenue||1)*100-((s.current_revenue||0)-ge)/(s.current_revenue||1)*100).toFixed(1)}% pontos percentuais 296Economia mensal: R$ ${(k-p).toFixed(2)} 297Economia anual: R$ ${((k-p)*12).toFixed(2)} 298 299## 1⣠SITUAÃÃO 300Atualmente, a empresa apresenta um Ponto de EquilÃbrio (PE) variável dependendo do cenário de pró-labore: 301- **Cenário Atual:** PE de R$ ${ge.toFixed(2)} 302- **Cenário Saudável:** PE de R$ ${Pe.toFixed(2)} 303 304As vendas atuais estão em R$ ${(s.current_revenue||0).toFixed(2)}. 305 306**Analise DETALHADAMENTE:** 307- No cenário atual, estamos ${(s.current_revenue||0)>=ge?"ACIMA":"ABAIXO"} do PE 308- No cenário saudável, estamos ${(s.current_revenue||0)>=Pe?"ACIMA":"ABAIXO"} do PE 309- Qual o impacto financeiro dessa diferença? 310- O pró-labore atual é sustentável considerando o PE? 311 312## 2⣠MARGEM DE SEGURANÃA 313Compare os DOIS cenários: 314 315**Cenário 1 (Pró-labore Atual):** 316Margem de Segurança: ${(((s.current_revenue||0)-ge)/(s.current_revenue||1)*100).toFixed(1)}% ${((s.current_revenue||0)-ge)/(s.current_revenue||1)*100>25||((s.current_revenue||0)-ge)/(s.current_revenue||1)*100>15,""} 317 318**Cenário 2 (Pró-labore Saudável):** 319Margem de Segurança: ${(((s.current_revenue||0)-Pe)/(s.current_revenue||1)*100).toFixed(1)}% ${((s.current_revenue||0)-Pe)/(s.current_revenue||1)*100>25||((s.current_revenue||0)-Pe)/(s.current_revenue||1)*100>15,""} 320 321Meta: >25% | Idealmente, buscamos uma margem superior a 25%, o que proporciona um buffer financeiro confortável. 322 323**Explique:** Como o ajuste no pró-labore melhora (ou não) a margem de segurança? 324 325## 3⣠ESTRUTURA 326Custos Fixos (sem pró-labore): R$ ${(s.fixed_costs||0).toFixed(2)} 327Custos Variáveis: R$ ${(s.variable_costs||0).toFixed(2)} 328Margem de Contribuição: ${(s.contribution_margin_pct||0).toFixed(1)}% (Meta: >40%) 329 330**Pró-labore Atual vs Saudável:** 331- Atual: R$ ${k.toFixed(2)} (${(k/(F||1)*100).toFixed(1)}% da receita) 332- Saudável: R$ ${p.toFixed(2)} (${(p/(F||1)*100).toFixed(1)}% da receita) 333 334**Analise:** A estrutura de custos fixos está equilibrada? O pró-labore está proporcionalmente correto em relação aos outros custos fixos? 335 336## 4⣠SIMULAÃÃES 337Considere os DOIS cenários de pró-labore e simule: 338 339**Simulação A: Redução de 10% nos Custos Fixos (mantendo cenário de pró-labore)** 340- Cenário 1 (pró-labore atual): Novo PE? Nova MS? 341- Cenário 2 (pró-labore saudável): Novo PE? Nova MS? 342 343**Simulação B: Aumento de 5% na Margem de Contribuição** 344- Cenário 1: Novo PE? Nova MS?
345- Cenário 2: Novo PE? Nova MS? 346 347**Simulação C: Combinado (Redução CF + Aumento MC)** 348- Cenário 1: Novo PE? Nova MS? 349- Cenário 2: Novo PE? Nova MS? 350 351**Importante:** Mostre com NÃMEROS REAIS o impacto de cada simulação nos dois cenários! 352 353## 5⣠5 AÃÃES PRÃTICAS 3541. **Aumentar a Margem de Contribuição (MC):** Focar em estratégias para melhorar a MC, seja através do aumento dos preços de venda (com cuidado para não afetar a demanda negativamente) ou pela redução dos custos variáveis por meio de negociações com fornecedores ou eficiências operacionais. 355 3562. **Reduzir Custos Fixos:** Reavaliar despesas fixas e identificar áreas onde cortes podem ser feitos sem prejudicar as operações essenciais. Isso pode incluir renegociação de aluguéis, revisão de contratos de serviços e otimização do uso de recursos. 357 3583. **Aumentar o Volume de Vendas:** Implementar estratégias de marketing e vendas para aumentar a receita. Isso pode envolver campanhas promocionais, expansão de canais de venda, ou diversificação do portfólio de produtos/serviços. 359 3604. **Revisão do Pró-labore:** ${k>F?"Dada a situação CRÃTICA identificada (pró-labore acima da receita), é IMPERATIVO ajustar imediatamente este valor para um patamar sustentável, conforme sugerido pelo cenário saudável.":k>p?"Considere implementar gradualmente o cenário 2 (pró-labore saudável) para melhorar a margem de segurança e reduzir o PE necessário.":"O pró-labore atual está dentro do recomendado. Mantenha o monitoramento mensal."} 361 3625. **Monitoramento e Controle Financeiro:** Implementar um sistema rigoroso de monitoramento financeiro para acompanhar de perto a evolução das receitas, custos e despesas, permitindo ajustes rápidos conforme necessário para manter a saúde financeira da empresa. 363 364**Implementando estas ações com cautela e foco estratégico, a empresa pode trabalhar para alcançar um ponto de equilÃbrio mais sustentável e construir uma margem de segurança saudável, garantindo assim sua viabilidade financeira a longo prazo.**`:`${L} 365 366 Dados PE indisponÃveis`;case"cashflow":return n?`${L} 367 368TAREFA: Previsão Fluxo de Caixa 30 dias 369 370 IMPORTANTE - COMO FUNCIONA O FLUXO DE CAIXA: 371O Fluxo de Caixa mostra quanto dinheiro você terá daqui a 30 dias. 372 373**FÃRMULA BÃSICA:** 374Saldo Final = Saldo Atual + Entradas - SaÃdas 375 376**EXPLICAÃÃO SIMPLES:** 3771. Você tem R$ X hoje (Saldo Atual) 3782. Vai RECEBER R$ Y nos próximos 30 dias (Entradas) 3793. Vai PAGAR R$ Z nos próximos 30 dias (SaÃdas) 3804. Resultado: Saldo Final = X + Y - Z 381 382**CONFERÃNCIA DO CÃLCULO:** 383Saldo Atual: R$ ${(n.saldoAtual||0).toFixed(2)} (o que você TEM hoje) 384(+) Entradas: R$ ${(n.entradasPrevistas||0).toFixed(2)} (o que vai RECEBER) 385(-) SaÃdas: R$ ${(n.saidasPrevistas||0).toFixed(2)} (o que vai PAGAR) 386(=) Saldo Final: R$ ${(n.saldoFinal||0).toFixed(2)} (o que vai TER daqui a 30 dias) 387 388**VALIDAÃÃO MATEMÃTICA:** 389${(n.saldoAtual||0).toFixed(2)} + ${(n.entradasPrevistas||0).toFixed(2)} - ${(n.saidasPrevistas||0).toFixed(2)} = ${(n.saldoFinal||0).toFixed(2)} ${Math.abs((n.saldoAtual||0)+(n.entradasPrevistas||0)-(n.saidasPrevistas||0)-(n.saldoFinal||0))<.01?" CORRETO":" VERIFIQUE"} 390 391## 1⣠SITUAÃÃO ATUAL E PROJETADA 392**Hoje:** 393Saldo em caixa/bancos: R$ ${(n.saldoAtual||0).toFixed(2)} 394 395**Próximos 30 dias:** 396Dinheiro que vai ENTRAR: R$ ${(n.entradasPrevistas||0).toFixed(2)} 397Dinheiro que vai SAIR: R$ ${(n.saidasPrevistas||0).toFixed(2)} 398Resultado lÃquido: R$ ${((n.entradasPrevistas||0)-(n.saidasPrevistas||0)).toFixed(2)} ${(n.entradasPrevistas||0)-(n.saidasPrevistas||0)>=0?" POSITIVO":" NEGATIVO"} 399 400**Daqui a 30 dias você terá:** 401Saldo projetado: R$ ${(n.saldoFinal||0).toFixed(2)} ${(n.saldoFinal||0)>(n.saldoAtual||0)?" (aumento)":(n.saldoFinal||0)<(n.saldoAtual||0)?" (redução)":" (estável)"} 402 403## 2⣠ANÃLISE DA VARIAÃÃO 404Diferença entre hoje e daqui a 30 dias: R$ ${((n.saldoFinal||0)-(n.saldoAtual||0)).toFixed(2)} (${(((n.saldoFinal||0)-(n.saldoAtual||0))/(n.saldoAtual||1)*100).toFixed(1)}%) 405Tendência: ${(n.saldoFinal||0)>(n.saldoAtual||0)?" Crescimento do caixa":(n.saldoFinal||0)<(n.saldoAtual||0)?" Redução do caixa":" Estabilidade"} 406 407**Importante:** Explique claramente se essa variação é positiva ou negativa e o que significa na prática para o negócio. 408 409## 3⣠PROJEÃÃO DETALHADA 410**ENTRADAS PROJETADAS (R$ ${(n.entradasPrevistas||0).toFixed(2)}):** 411- Baseadas na média de vendas dos últimos 30 dias 412- Representa o que você provavelmente vai receber se mantiver o ritmo atual de vendas
413- NÃO inclui vendas extras não previstas 414 415**SAÃDAS PROJETADAS (R$ ${(n.saidasPrevistas||0).toFixed(2)}):** 416- Contas a pagar cadastradas com vencimento nos próximos 30 dias 417- Inclui apenas despesas já conhecidas e confirmadas 418- NÃO inclui imprevistos ou despesas não cadastradas 419 420**Dias crÃticos:** Identifique se há algum perÃodo onde o saldo ficará abaixo de R$ 1.000 421**Picos de entrada/saÃda:** Analise se há concentração de pagamentos ou recebimentos em datas especÃficas 422**Redistribuição:** Sugira redistribuição de pagamentos para evitar dias com saldo muito baixo 423 424## 4⣠CENÃRIOS ALTERNATIVOS 425**Cenário Otimista (20% de probabilidade):** 426- Se as vendas aumentarem 15% 427- Entradas: R$ ${((n.entradasPrevistas||0)*1.15).toFixed(2)} 428- Saldo final: R$ ${((n.saldoAtual||0)+(n.entradasPrevistas||0)*1.15-(n.saidasPrevistas||0)).toFixed(2)} 429 430**Cenário Realista (60% de probabilidade):** 431- Mantendo o ritmo atual 432- Entradas: R$ ${(n.entradasPrevistas||0).toFixed(2)} 433- Saldo final: R$ ${(n.saldoFinal||0).toFixed(2)} 434 435**Cenário Pessimista (20% de probabilidade):** 436- Se as vendas caÃrem 15% 437- Entradas: R$ ${((n.entradasPrevistas||0)*.85).toFixed(2)} 438- Saldo final: R$ ${((n.saldoAtual||0)+(n.entradasPrevistas||0)*.85-(n.saidasPrevistas||0)).toFixed(2)} 439- Risco: ${(n.saldoAtual||0)+(n.entradasPrevistas||0)*.85-(n.saidasPrevistas||0)<0?" SALDO NEGATIVO!":(n.saldoAtual||0)+(n.entradasPrevistas||0)*.85-(n.saidasPrevistas||0)<500?" Saldo crÃtico":" Saldo positivo"} 440 441## 5⣠ALERTAS IMPORTANTES 442**Datas crÃticas:** Liste datas especÃficas onde há concentração de pagamentos 443**Reserva emergencial:** Recomende manter reserva de 3-6 meses de despesas fixas 444**MÃnimo recomendado:** Sugira saldo mÃnimo operacional baseado nas despesas médias mensais 445 446## 6⣠5 AÃÃES PRÃTICAS 4471. **â Aumentar Entradas:** Estratégias para acelerar recebimentos ou aumentar vendas 4482. ** Pausar SaÃdas:** Identifique pagamentos que podem ser postergados sem juros 4493. **Antecipar RecebÃveis:** Avalie custo-benefÃcio de antecipação de recebÃveis 4504. **Renegociar Prazos:** Negocie com fornecedores para melhorar condições de pagamento 4515. **Plano B:** Desenvolva plano de contingência caso o cenário pessimista se confirme 452 453## 7⣠OPORTUNIDADES 454**Capacidade de Investimento:** ${(n.saldoFinal||0)>(n.saidasPrevistas||0)*3?"Boa capacidade para investimentos":"Capacidade limitada, priorize reserva de emergência"} 455**Compras com Desconto:** ${(n.saldoFinal||0)>(n.saidasPrevistas||0)*2?"Aproveite descontos para pagamento à vista se compensar":"Evite comprometer o caixa com compras antecipadas"} 456**Oportunidades de Mercado:** Analise se há margem para aproveitar oportunidades pontuais sem comprometer a saúde financeira 457 458**RESUMO EXECUTIVO:** 459Faça um resumo claro e objetivo explicando: 460- O caixa vai melhorar ou piorar nos próximos 30 dias? 461- Qual a principal recomendação (aumentar entradas ou reduzir saÃdas)? 462- Há risco de falta de caixa? Se sim, quando e quanto?`:`${L} 463 464 Dados Fluxo Caixa indisponÃveis`;case"trends":return`${L} 465 466TAREFA: Análise Tendências & Previsões (3 meses) 467 468## 1⣠TENDÃNCIA ATUAL 469Fluxo: R$ ${(t.fluxoLiquido||0).toFixed(2)} ${(t.fluxoLiquido||0)>0,""} 470Padrão últimos meses | Sazonalidade 471 472## 2⣠PREVISÃO TRIMESTRAL 473**Mês 1:** Receita | Despesa | Lucro | Confiança% 474**Mês 2:** Estimativas 475**Mês 3:** Estimativas 476 477## 3⣠FATORES INFLUENCIADORES 478Externos (economia, mercado) | Internos (expansão, contratações) 479 480## 4⣠PADRÃES 481Crescimento consistente? | Variabilidade? | Meses sazonais | Preparação 482 483## 5⣠CENÃRIOS 484**Otimista (25%):** Receita +20% â Impacto 485**Base (50%):** Manutenção â Impacto 486**Pessimista (25%):** Receita -15% â Contingência 487 488## 6⣠RECOMENDAÃÃES 489Aproveitar tendências â | Mitigar riscos â | Preparar sazonalidade | Ajustes orçamento`;case"optimization":return`${L} 490 491TAREFA: Oportunidades de Otimização & Redução de Custos 492 493 ATENÃÃO ESPECIAL: 494- Analise os DOIS CENÃRIOS de pró-labore em 'prolabore_cenarios' 495- O pró-labore é frequentemente a MAIOR oportunidade de otimização! 496- Há ${P.filter(V=>V.active).length} sócio(s) ativo(s) recebendo pró-labore 497- Total pró-labore atual: R$ ${Xe.toFixed(2)}/mês 498- Pró-labore recomendado: R$ ${p.toFixed(2)}/mês 499- **Economia potencial mensal: R$ ${(k-p).toFixed(2)}** 500- **Economia potencial anual: R$ ${((k-p)*12).toFixed(2)}** 501 502## 1⣠ESTRUTURA DE CUSTOS ATUAL 503**Total de Custos + Despesas:** 504R$ ${((t.custos||0)+(t.despesas||0)+k).toFixed(2)} (${(((t.custos||0)+(t.despesas||0)+k)/(t.receita||1)*100).toFixed(1)}% da receita) 505 506**Composição:** 507- Custos Fixos: R$ ${(t.custos||0).toFixed(2)}
508- Despesas Fixas: R$ ${(t.despesas||0).toFixed(2)} 509- Pró-labore (Atual): R$ ${k.toFixed(2)} (${(k/(t.receita||1)*100).toFixed(1)}% da receita) ${k>(t.receita||1)*.15?" ACIMA DO RECOMENDADO":""} 510- Custos Variáveis: R$ ${((r==null?void 0:r.custosVariaveis)||0).toFixed(2)} 511 512**Meta:** Manter custos abaixo de 70% da receita 513**Status:** ${((t.custos||0)+(t.despesas||0)+k)/(t.receita||1)*100<70?" Dentro da meta":" Acima da meta - AÃÃO NECESSÃRIA"} 514 515## 2⣠TOP 5 OPORTUNIDADES DE OTIMIZAÃÃO 516 517### OPORTUNIDADE #1: PRÃ-LABORE (MAIOR IMPACTO!) 518 519**CENÃRIO ATUAL:** 520- Valor mensal: R$ ${k.toFixed(2)} 521- % da Receita: ${(k/(t.receita||1)*100).toFixed(1)}% 522- Status: ${k>(t.receita||1)?" CRÃTICO - Acima da receita!":k>(t.lucro||0)?" ATENÃÃO - Acima do lucro":k>(t.receita||1)*.15?" Acima do recomendado (>15%)":" OK"} 523 524**CENÃRIO RECOMENDADO:** 525- Valor mensal: R$ ${p.toFixed(2)} 526- % da Receita: ${(p/(t.receita||1)*100).toFixed(1)}% 527- Economia mensal: R$ ${(k-p).toFixed(2)} 528- **Economia anual: R$ ${((k-p)*12).toFixed(2)}** 529 530**IMPACTO:** 531- Dificuldade: Média (requer alinhamento entre sócios) 532- Retorno: Alto (maior oportunidade de economia identificada)
533- Urgência: ${k>(t.receita||1)?"IMEDIATA":k>p?"Alta (30 dias)":"Baixa"} 534 535**AÃÃO RECOMENDADA:** 536${k>(t.receita||1)?"CRÃTICO: Reajustar IMEDIATAMENTE para valor sustentável. Empresa em prejuÃzo crÃtico.":k>p*1.5?"Implementar redução gradual em 3 meses para evitar impacto abrupto.":k>p?"Ajustar para o valor recomendado no próximo ciclo mensal.":"Manter monitoramento mensal e ajustar conforme crescimento."} 537 538${P.filter(V=>V.active).length>1?` 539**SUGESTÃO DE DISTRIBUIÃÃO (${P.filter(V=>V.active).length} sócios):** 540Pró-labore recomendado por sócio: R$ ${(p/P.filter(V=>V.active).length).toFixed(2)}/mês 541 542**Sócios atuais:** 543${P.filter(V=>V.active).map((V,l)=>`- ${V.partner_name||`Sócio ${l+1}`}: R$ ${(V.amount||0).toFixed(2)} (atual) â R$ ${(p/P.filter(T=>T.active).length).toFixed(2)} (sugerido)`).join(` 544`)} 545`:""} 546 547### OPORTUNIDADE #2-5: OUTRAS CATEGORIAS 548 549Analise as próximas 4 maiores oportunidades de redução de custos: 550- Custos Fixos (R$ ${(t.custos||0).toFixed(2)}) 551- Despesas Fixas (R$ ${(t.despesas||0).toFixed(2)}) 552- Custos Variáveis (R$ ${((r==null?void 0:r.custosVariaveis)||0).toFixed(2)}) 553- Fluxo de Caixa (otimização de prazos e negociações) 554 555Para cada categoria, forneça: 5561. **Valor atual** e % do total 5572. **Economia potencial** (em R$ e %) 5583. **Dificuldade** de implementação (Baixa/Média/Alta) 5594. **Impacto** no resultado (Baixo/Médio/Alto) 5605. **Ação especÃfica** recomendada 561 562## 3⣠OTIMIZAÃÃO DO FLUXO DE CAIXA 563**Contas Vencidas:** R$ ${(t.valorVencido||0).toFixed(2)} ${(t.valorVencido||0)>0?" Regularizar urgente":" Em dia"} 564**Contas Pendentes:** R$ ${(t.valorPendente||0).toFixed(2)} 565**Caixa DisponÃvel:** R$ ${(t.caixaDisponivel||0).toFixed(2)} 566 567**Ações Recomendadas:** 5681. Renegociação de prazos com fornecedores 5692. Buscar descontos para pagamentos antecipados 5703. Uso estratégico do caixa disponÃvel para reduzir custos financeiros 571 572## 4⣠MATRIZ DE PRIORIZAÃÃO (Urgência vs Impacto) 573 574** URGENTE + ALTO IMPACTO:** 575${k>p?`1. Reajuste do pró-labore (economia de R$ ${((k-p)*12).toFixed(2)}/ano)`:"1. [Identifique ação com maior retorno]"} 5762. [Segunda ação de maior retorno] 577 578** URGENTE + BAIXO IMPACTO:** 579- Delegar para equipe: pequenas otimizações operacionais 580 581** PLANEJADO + ALTO IMPACTO:** 5821. Revisão estrutural de contratos e fornecedores 5832. Otimização de processos para redução de custos variáveis 584 585** BAIXO + BAIXO:** 586- Eliminar ou adiar investimentos não prioritários 587 588## 5⣠PLANO DE 90 DIAS 589 590**Meta de Economia:** Reduzir custos totais em 10-15% (R$ ${(((t.custos||0)+(t.despesas||0)+k)*.1).toFixed(2)} a R$ ${(((t.custos||0)+(t.despesas||0)+k)*.15).toFixed(2)}) 591 592**Mês 1 (Dias 1-30):** 593${k>p?`- Reajuste do pró-labore (economia: R$ ${(k-p).toFixed(2)}/mês)`:"- Revisar contratos fixos maiores"} 594- InÃcio das negociações com fornecedores principais 595- Identificação de despesas não essenciais 596 597**Mês 2 (Dias 31-60):** 598- Implementação das otimizações aprovadas 599- Revisão e ajuste do fluxo de caixa 600- Monitoramento dos resultados do Mês 1 601 602**Mês 3 (Dias 61-90):** 603- Avaliação dos resultados consolidados 604- Ajustes finais e correções de rota 605- Planejamento para manutenção das economias alcançadas 606 607**Métricas de Acompanhamento:** 608- Redução percentual dos custos totais (meta: -10-15%) 609- Lucro operacional mensal 610- Margem de lucro (meta: >20%) 611- Saldo do fluxo de caixa 612 613## 6⣠QUICK WINS (Primeiros 7 Dias) 614 6151. ${k>p?`**Reajuste do Pró-labore:** Iniciar discussões com sócios para reajuste, economizando R$ ${(k-p).toFixed(2)}/mês`:"**Renegociação de Contratos Menores:** Identificar contratos com vencimento próximo"} 616 6172. **Revisão Rápida de Despesas:** Identificar e cortar despesas não essenciais imediatamente 618 6193. **Negociação de Prazos:** Contatar principais fornecedores para melhorar condições de pagamento 620 621**Implementando estas ações com disciplina e foco, a empresa alcançará sustentabilidade financeira e crescimento saudável no longo prazo.**`;case"benchmark":return`${L} 622 623TAREFA: Benchmark com Padrões do Mercado Brasileiro 624 625 ATENÃÃO ESPECIAL: 626- Analise os DOIS CENÃRIOS de pró-labore em 'prolabore_cenarios' 627- O pró-labore impacta DIRETAMENTE os indicadores de custos/receita 628- Há ${P.filter(V=>V.active).length} sócio(s) ativo(s) recebendo pró-labore 629- Total pró-labore atual: R$ ${Xe.toFixed(2)}/mês (${(k/(F||1)*100).toFixed(1)}% da receita) 630- Pró-labore recomendado: R$ ${p.toFixed(2)}/mês (${(p/(F||1)*100).toFixed(1)}% da receita) 631 632## 1⣠SCORE VS MERCADO 633**Seu Score:** ${t.healthScore||0}/100 634**Benchmarks do Mercado:** 635- Top 25% (Excelência): >85 636- Média do Mercado: 70 637- Abaixo da Média: <50 638 639**Sua Posição:** ${(t.healthScore||0)>=85?" Top 25% - Excelência!":(t.healthScore||0)>=70?" Acima da Média":(t.healthScore||0)>=50?" Dentro da Média":" Abaixo da Média"} 640 641**Gap para Excelência:** ${(t.healthScore||0)>=85?"Você já está no topo! Foco em manter.":`Faltam ${(85-(t.healthScore||0)).toFixed(0)} pontos para alcançar o Top 25%`} 642 643## 2⣠INDICADORES VS BENCHMARKS DO MERCADO 644 645**IMPORTANTE:** Use listas numeradas, NÃO use tabelas! Formato: 646 647### Margem LÃquida 648- **Você:** ${((t.lucro||0)/(t.receita||1)*100).toFixed(1)}% 649- **Benchmark do Mercado:** 15-20% 650- **Status:** ${(t.lucro||0)/(t.receita||1)*100>=20?" Excelente (acima do mercado)":(t.lucro||0)/(t.receita||1)*100>=15?" Bom (dentro do benchmark)":(t.lucro||0)/(t.receita||1)*100>
650=10?" Regular (abaixo do ideal)":" CrÃtico (muito abaixo)"} 651- **Análise:** ${(t.lucro||0)/(t.receita||1)*100>=15?"Margem saudável, mantenha a eficiência operacional.":"Necessário aumentar margem através de otimização de custos ou aumento de preços."} 652 653### Liquidez Corrente 654- **Você:** ${((t.caixaDisponivel||0)/(t.valorPendente||1)).toFixed(2)} 655- **Benchmark do Mercado:** 1.5-2.0 656- **Status:** ${(t.caixaDisponivel||0)/(t.valorPendente||1)>=2?" Excelente (muita folga)":(t.caixaDisponivel||0)/(t.valorPendente||1)>=1.5?" Bom (dentro do ideal)":(t.caixaDisponivel||0)/(t.valorPendente||1)>=1?" Regular (liquidez justa)":" CrÃtico (risco de insolvência)"} 657- **Análise:** ${(t.caixaDisponivel||0)/(t.valorPendente||1)>=1.5?"Boa capacidade de pagamento.":"Necessário melhorar gestão de caixa e recebÃveis."} 658 659### Taxa de Inadimplência 660- **Você:** ${((t.contasVencidas||0)/(t.contasPendentes||1)*100).toFixed(1)}% 661- **Benchmark do Mercado:** <5% 662- **Status:** ${(t.contasVencidas||0)/(t.contasPendentes||1)*100<=5?" Ideal (dentro do benchmark)":(t.contasVencidas||0)/(t.contasPendentes||1)*100<=10?" Atenção (acima do ideal)":" CrÃtico (muito alto)"} 663- **Análise:** ${(t.contasVencidas||0)/(t.contasPendentes||1)*100<=5?"Excelente controle de contas a pagar.":"Priorize regularização de contas vencidas."} 664 665### Custos/Receita (CONSIDERANDO PRÃ-LABORE) 666 667**CENÃRIO 1 - COM PRÃ-LABORE ATUAL:** 668- **Você:** ${(((t.custos||0)+(t.despesas||0)+k)/(t.receita||1)*100).toFixed(1)}% 669- **Pró-labore incluÃdo:** R$ ${k.toFixed(2)} (${(k/(t.receita||1)*100).toFixed(1)}% da receita) 670- **Benchmark do Mercado:** <70% 671- **Status:** ${((t.custos||0)+(t.despesas||0)+k)/(t.receita||1)*100<=70?" Dentro do ideal":((t.custos||0)+(t.despesas||0)+k)/(t.receita||1)*100<=85?" Acima do ideal":" CrÃtico - Ação urgente necessária"} 672- **Análise:** ${((t.custos||0)+(t.despesas||0)+k)/(t.receita||1)*100>70?"Estrutura de custos comprometida, principalmente pelo pró-labore.":"Estrutura de custos saudável."} 673 674**CENÃRIO 2 - COM PRÃ-LABORE RECOMENDADO:** 675- **Você (projetado):** ${(((t.custos||0)+(t.despesas||0)+p)/(t.receita||1)*100).toFixed(1)}% 676- **Pró-labore recomendado:** R$ ${p.toFixed(2)} (${(p/(t.receita||1)*100).toFixed(1)}% da receita) 677- **Benchmark do Mercado:** <70% 678- **Status:** ${((t.custos||0)+(t.despesas||0)+p)/(t.receita||1)*100<=70?" Dentro do ideal":" Ainda acima, mas melhor"} 679- **Melhoria:** ${(((t.custos||0)+(t.despesas||0)+k)/(t.receita||1)*100-((t.custos||0)+(t.despesas||0)+p)/(t.receita||1)*100).toFixed(1)} pontos percentuais de redução 680 681### Pró-labore vs Benchmarks de Mercado 682- **Seu pró-labore atual:** ${(k/(t.receita||1)*100).toFixed(1)}% da receita 683- **Benchmark saudável:** 10-15% da receita 684- **Status:** ${k/(t.receita||1)*100<=15?" Dentro do recomendado":k/(t.receita||1)*100<=25?" Acima do ideal":" CrÃtico - Muito acima"} 685- **Recomendação:** ${k/(t.receita||1)*100>15?`Reduzir para ${(p/(t.receita||1)*100).toFixed(1)}% (R$ ${p.toFixed(2)})`:"Manter monitoramento mensal"} 686 687## 3⣠ANÃLISE DE GAPS (Distância do Ideal) 688 689${k>p?` 690### GAP #1: Pró-labore vs Receita (PRIORITÃRIO) 691- **Atual:** ${(k/(t.receita||1)*100).toFixed(1)}% 692- **Ideal:** <15% 693- **Diferença:** ${(k/(t.receita||1)*100-15).toFixed(1)} pontos percentuais 694- **Impacto:** ${k>(t.receita||1)?"CRÃTICO - Empresa em prejuÃzo estrutural":k>(t.lucro||0)?"ALTO - Comprometendo lucro":"MÃDIO - Reduzindo margem de segurança"} 695- **3 Ações Imediatas:** 696 1. Reajustar pró-labore para R$ ${p.toFixed(2)} (${(p/(F||1)*100).toFixed(1)}% da receita) 697 2. ${P.filter(V=>V.active).length>1?`Redistribuir entre ${P.filter(V=>V.active).length} sócios: R$ ${(p/P.filter(V=>V.active).length).toFixed(2)}/sócio`:"Implementar polÃtica de remuneração variável baseada em resultados"} 698 3. Revisar mensalmente e ajustar conforme crescimento da receita 699- **Prazo:** ${k>(t.receita||1)?"IMEDIATO (7 dias)":k>p*1.5?"Urgente (30 dias)":"Curto prazo (60 dias)"} 700- **Recursos Necessários:** Reunião com sócios, consultoria financeira (se necessário), planejamento de transição 701`:""} 702 703### Outros Gaps Identificados 704Analise os demais gaps em relação aos benchmarks e forneça para cada um: 705- Situação atual vs ideal 706- Diferença quantitativa 707- Impacto no negócio 708- 3 ações práticas 709- Prazo de implementação 710- Recursos necessários 711 712## 4⣠5 MELHORES PRÃTICAS DO MERCADO 713 714### 3 Práticas que Você Jà FAZ (Manter e Melhorar): 7151. [Identifique prática positiva 1] 7162. [Identifique prática positiva 2] 7173. [Identifique prática positiva 3] 718 719### 2 Erros Comuns que Você EVITA: 7201. [Erro comum do mercado que você não comete] 7212. [Outro erro que você evita] 722 723## 5⣠POSICIONAMENTO COMPETITIVO 724**Quartil:** ${(t.healthScore||0)>=85?"Top 25% ":(t.healthScore||0)>=70?"2º Quartil (Acima da média)":(t.healthScore||0)>=50?"3º Quartil (Média)":"4º Quartil (Abaixo da média)"} 725 726**Vantagens Competitivas:** 727- [Liste 2-3 vantagens identificadas nos indicadores] 728 729**Desvantagens:** 730${k>p?`- Pró-labore desproporcional (${(k/(F||1)*100).toFixed(1)}% vs ideal <15%)`:""} 731- [Liste outras desvantagens identificadas] 732 733**Tempo Estimado para Top 25%:** ${(t.healthScore||0)>=85?"Você já está lá! Foco em manter.":`${Math.ceil((85-(t.healthScore||0))/5)} a ${Math.ceil((85-(t.healthScore||0))/3)} meses com ações consistentes`} 734 735## 6⣠ROADMAP PARA A EXCELÃNCIA 736 737### Próximos 30 dias (Ações Urgentes): 7381. ${k>p?`Reajustar pró-labore para ${(p/(F||1)*100).toFixed(1)}% da receita`:"[Primeira ação prioritária]"}
7392. [Segunda ação com maior impacto] 740 741### Próximos 90 dias (Ações Estruturais): 7421. [Ação estrutural 1 - ex: revisão de processos] 7432. [Ação estrutural 2 - ex: renegociação de contratos] 744 745### Próximos 180 dias (Transformação): 746- **Objetivo:** ${(t.healthScore||0)>=85?"Manter score acima de 85 e superar 90":"Alcançar score de 85+ (Top 25%)"} 747- **Meta de Score:** ${Math.min(100,(t.healthScore||0)+15)} 748- **Transformações esperadas:** [Descreva mudanças estruturais previstas] 749 750**Acompanhamento:** Revisar este benchmark mensalmente e ajustar estratégias conforme necessário.`;default:return L}},le=async()=>{const B=Ra[u];try{m(!0),g("");const F=await Ja.hasEnoughCredits(B.id);if(!F.hasCredits){I({title:"Créditos insuficientes",description:`Esta análise requer ${B.credits} créditos. Você tem ${F.available} disponÃveis. Faltam ${F.missing} créditos.`,variant:"destructive"}),m(!1);return}const W=se(u),D=await ir({systemPrompt:"Você é um CFO e consultor financeiro sênior especializado em análise empresarial brasileira. Use formatação Markdown estruturada, linguagem clara e objetiva. Foque em insights acionáveis e recomendações práticas.",userMessage:W,temperature:.4,maxTokens:3500});await Ja.consume(B.id),g(D),U(u,D,B.credits),I({title:" Análise concluÃda!",de
750scription:`${B.credits} créditos consumidos. Análise gerada com sucesso.`})}catch(F){console.error("Erro na análise:",F),I({title:"Erro na análise",description:F instanceof Error?F.message:"Erro desconhecido",variant:"destructive"})}finally{m(!1)}},ce=async()=>{if(!S.trim()||z)return;const B={id:`msg-${Date.now()}`,role:"user",content:S,message_index:f.length,created_at:new Date().toISOString()};$(F=>[...F,B]),Z(""),X(!0);try{const F=await Ja.hasEnoughCredits("financial_ai_chat");if(!F.hasCredits){I({title:"Créditos insuficientes",description:`Você precisa de ${F.needed} créditos. DisponÃvel: ${F.available}`,variant:"destructive"}),$(k=>k.slice(0,-1));return}await Ja.consume("financial_ai_chat",{question:S});const W=`Você é um CFO sênior consultando sobre esta análise financeira: 751 752ANÃLISE ORIGINAL: 753${d} 754 755DADOS ADICIONAIS: 756${JSON.stringify({receita:t.receita,lucro:t.lucro,prolabore:r==null?void 0:r.prolabore,despesas:((r==null?void 0:r.despesasFixas)||0)+((r==null?void 0:r.despesasVariaveis)||0)},null,2)} 757 758Responda de forma clara, objetiva e sempre com base nos dados apresentados. Use exemplos com valores reais.`,D=await ir({systemPrompt:W,messages:f.map(k=>({role:k.role,content:k.content})),userMessage:B.content,temperature:.4,maxTokens:1e3}),re={id:`msg-${Date.now()}-assistant`,role:"assistant",content:D,message_index:f.length+1,created_at:new Date().toISOString()};$(k=>[...k,re]),setTimeout(()=>{var k;(k=Y.current)==null||k.scrollIntoView({behavior:"smooth"})},100),I({title:" Resposta recebida",description:"2 créditos consumidos"})}catch(F){console.error("Erro no chat:",F),I({title:"Erro no chat",description:F instanceof Error?F.message:"Erro desconhecido",variant:"destructive"}),$(W=>W.slice(0,-1))}finally{X(!1)}},R=B=>{const F=B?B.result:d;if(!F)return;const W=B?B.type:u,D=Ra[W],re=F.split(` 759`),k=[];re.forEach(p=>{if(p.startsWith("### "))k.push({text:p.replace("### ",""),style:"subsectionTitle",margin:[0,10,0,5]});else if(p.startsWith("## "))k.push({text:p.replace("## ",""),style:"sectionTitle",margin:[0,15,0,10]});else if(p.startsWith("# "))k.push({text:p.replace("# ",""),style:"mainTitle",margin:[0,0,0,20]});else if(p.includes("**")){const oe=p.replace(/\*\*(.*?)\*\*/g,"$1");k.push({text:oe,bold:!0,margin:[0,5,0,5],color:"#1a1a1a"})}else p.startsWith("- ")||p.startsWith("* ")?k.push({text:p.replace(/^[*-] /,"⢠"),margin:[20,2,0,2],color:"#374151"}):p.trim()===""?k.push({text:" ",margin:[0,5,0,0]}):p.trim()&&k.push({text:p,style:"normalText",margin:[0,2,0,2]})});const ke={content:[{text:"Análise Financeira Profissional com IA",style:"mainTitle",color:"#7c3aed"},{text:D.title,style:"sectionTitle",margin:[0,5,0,10]},{text:`Gerado em: ${er()}`,style:"date"},{canvas:[{type:"line",x1:0,y1:0,x2:515,y2:0,lineWidth:2,lineColor:"#7c3aed"}],margin:[0,10,0,20]},...k,...f.length>0?[{text:" ",pageBreak:"before"},{text:" Conversa com o CFO IA",style:"sectionTitle",margin:[0,20,0,15]},...f.map((p,oe)=>({stack:[{text:p.role==="user"?" Você":" CFO IA",style:"chatRole",bold:!0,color:p.role==="user"?"#2563eb":"#7c3aed",margin:[0,oe>0?10:0,0,3]},{text:p.content,style:"chatMessage",margin:[15,0,0,5],color:"#374151"},{text:ar(p.created_at),fontSize:8,color:"#9ca3af",margin:[15,0,0,0]}]}))]:[],{canvas:[{type:"line",x1:0,y1:0,x2:515,y2:0,lineWidth:1,lineColor:"#e5e7eb"}],margin:[0,30,0,10]},{text:[{text:"Powered by ",fontSize:9,color:"#9ca3af"},{text:"GPT-4 Turbo",fontSize:9,color:"#7c3aed",bold:!0},{text:` ⢠${D.credits} créditos consumidos`,fontSize:9,color:"#9ca3af"}],alignment:"center"}],styles:{mainTitle:{fontSize:22,bold:!0,alignment:"center",margin:[0,0,0,5]},sectionTitle:{fontSize:18,bold:!0,color:"#1f2937"},subsectionTitle:{fontSize:14,bold:!0,color:"#374151"},date:{fontSize:10,alignment:"center",color:"#6b7280",margin:[0,0,0,5]},normalText:{fontSize:11,color:"#374151"},chatRole:{fontSize:12,bold:!0},chatMessage:{fontSize:10,lineHeight:1.4},highlight:{fillColor:"#fef3c7",margin:[0,5,0,5]}},defaultStyle:{fontSize:11,lineHeight:1.5,color:"#1f2937"},pageMargins:[40,60,40,60],info:{title:`Análise Financeira - ${D.title}`,author:"Sistema Financeiro IA",subject:"Análise Financeira Profissional",keywords:"finanças, análise, IA, GPT-4 Turbo"}},Q=B?`analise-${W}-${new Date(B.date).getTime()}.pdf`:`analise-${W}-${Date.now()}.pdf`;
759Or.createPdf(ke).download(Q),I({title:" PDF exportado!",description:"Análise profissional salva com sucesso."})},pe=Ra[u];return a(K,{className:"border-2 border-purple-200 dark:border-purple-800 bg-gradient-to-br from-purple-50 via-blue-50 to-cyan-50 dark:from-purple-950/30 dark:via-blue-950/20 dark:to-cyan-950/20",children:[e(te,{children:a("div",{className:"flex items-start justify-between",children:[a("div",{className:"flex items-center gap-3",children:[e("div",{className:"p-3 bg-purple-600 rounded-lg",children:e($a,{className:"h-6 w-6 text-white"})}),a("div",{children:[a(ne,{className:"text-2xl text-purple-900 dark:text-purple-300 flex items-center gap-2",children:["Central de Análises Financeiras com IA",e(oa,{className:"h-5 w-5 text-yellow-500"})]}),e(Se,{className:"text-base mt-1",children:"Análises profissionais consolidadas utilizando GPT-4 Turbo - Escolha o tipo de análise que precisa"})]})]}),a("div",{className:"flex items-center gap-2",children:[a(j,{onClick:()=>E(!M),variant:"outline",size:"sm",className:"flex items-center gap-2",children:[e(Os,{className:"h-4 w-4"}),M?"Ocultar":"Ver"," Histórico",x.length>0&&e(ae,{variant:"secondary",className:"ml-1",children:x.length})]}),e(ae,{variant:"secondary",className:"text-sm",children:"Powered by GPT-4 Turbo"})]})]})}),a(ee,{className:"space-y-6",children:[a(pt,{value:u,onValueChange:B=>i(B),children:[e(gt,{className:"grid grid-cols-4 lg:grid-cols-8 gap-2 h-auto p-2 bg-white/60 dark:bg-card/60",children:Object.entries(Ra).map(([B,F])=>{const W=F.icon;return a(qe,{value:B,className:"flex flex-col items-center gap-2 py-3 px-2 data-[state=active]:bg-white dark:data-[state=active]:bg-card data-[state=active]:shadow-md",children:[e(W,{className:`h-5 w-5 ${F.color}`}),e("span",{className:"text-xs text-center leading-tight",children:F.title}),a(ae,{variant:"outline",className:"text-xs",children:[F.credits," créditos"]})]},B)})}),e("div",{className:`mt-6 p-6 rounded-lg border-2 ${pe.bgColor}`,children:a("div",{className:"flex items-start gap-4",children:[e("div",{className:"p-3 rounded-lg bg-white dark:bg-card shadow-sm",children:(()=>{const B=pe.icon;return e(B,{className:`h-8 w-8 ${pe.color}`})})()}),a("div",{className:"flex-1",children:[e("h3",{className:"text-xl font-bold text-gray-900 dark:text-gray-100 mb-2",children:pe.title}),e("p",{className:"text-gray-700 dark:text-gray-300 mb-4",children:pe.description}),a("div",{className:"flex items-center gap-4 text-sm",children:[a(ae,{variant:"secondary",className:"gap-1",children:[e(
759oa,{className:"h-3 w-3"}),pe.credits," créditos"]}),e("span",{className:"text-gray-600 dark:text-gray-400",children:"⢠Análise com GPT-4 Turbo"}),e("span",{className:"text-gray-600 dark:text-gray-400",children:"⢠Recomendações acionáveis"})]})]}),a("div",{className:"flex items-center gap-2 mb-4",children:[a(j,{onClick:()=>N(!b),variant:"outline",size:"sm",className:"flex items-center gap-2",children:[e($a,{className:"h-4 w-4"}),"Tom: ",h==="professional"?"Profissional":h==="optimistic"?"Otimista":h==="realistic"?"Realista":h==="cautious"?"Cauteloso":"Motivacional"]}),b&&a("div",{className:"absolute z-50 mt-2 w-72 bg-white dark:bg-card border dark:border-border rounded-lg shadow-lg p-4",children:[e("h3",{className:"font-semibold mb-3",children:"Escolha o Tom da Análise"}),e("div",{className:"space-y-2",children:[{value:"professional",label:"Profissional",desc:"Técnico e focado em métricas"},{value:"optimistic",label:"Otimista",desc:"Destaca oportunidades"},{value:"realistic",label:"Realista",desc:"Equilibrado e direto"},{value:"cautious",label:"Cauteloso",desc:"Prioriza alertas de risco"},{value:"motivational",label:"Motivacional",desc:"Focado em crescimento"}].map(B=>a("button",{onClick:()=>{c(B.value),N(!1)},className:`w-full text-left p-3 rounded-lg border transition-colors ${h===B.value?"bg-blue-50 dark:bg-blue-950/40 border-blue-500 dark:border-blue-600":"hover:bg-gray-50 dark:hover:bg-gray-800/50 border-gray-200 dark:border-gray-700"}`,children:[e("div",{className:"font-medium",children:B.label}),e("div",{className:"text-sm text-gray-600",children:B.desc})]},B.value))})]})]}),e(j,{onClick:le,disabled:o,size:"lg",className:"bg-gradient-to-r from-purple-600 via-blue-600 to-cyan-600 text-white hover:from-purple-700 hover:via-blue-700 hover:to-cyan-700 shadow-lg hover:shadow-xl transition-all duration-300 font-semibold",children:o?a(Ee,{children:[e($a,{className:"h-5 w-5 mr-2 animate-pulse"}),"Analisando..."]}
759):a(Ee,{children:[e(oa,{className:"h-5 w-5 mr-2"}),"Gerar Análise"]})})]})})]}),d&&a("div",{className:"space-y-4",children:[a("div",{className:"flex items-center justify-between",children:[a(Fe,{className:"flex-1 border-green-200 dark:border-green-800 bg-green-50 dark:bg-green-950/30",children:[e($e,{className:"h-5 w-5 text-green-600 dark:text-green-400"}),a(Ie,{className:"text-green-800 dark:text-green-400 font-medium",children:["Análise concluÃda com sucesso! ",pe.credits," créditos consumidos."]})]}),a(j,{onClick:()=>R(),variant:"outline",className:"ml-4",children:[e(et,{className:"h-4 w-4 mr-2"}),"Exportar PDF"]})]}),a(K,{className:"border-2",children:[a(te,{className:pe.bgColor,children:[a(ne,{className:"flex items-center gap-2",children:[(()=>{const B=pe.icon;return e(B,{className:`h-5 w-5 ${pe.color}`})})(),pe.title]}),a(Se,{children:["Gerado em ",er()," ⢠",pe.credits," créditos"]})]}),e(ee,{className:"pt-6",children:e("div",{className:"prose prose-sm max-w-none dark:prose-invert prose-headings:text-gray-900 dark:prose-headings:text-gray-100 prose-p:text-gray-700 dark:prose-p:text-gray-300 prose-strong:text-gray-900 dark:prose-strong:text-gray-100 prose-ul:text-gray-700 dark:prose-ul:text-gray-300 prose-ol:text-gray-700 dark:prose-ol:text-gray-300",children:e(Ts,{children:d})})})]}),a(K,{className:"border-2 border-blue-200 dark:border-blue-800 bg-gradient-to-br from-blue-50 to-white dark:from-blue-950/30 dark:to-card",children:[a(te,{children:[a(ne,{className:"flex items-center gap-2 text-blue-900 dark:text-blue-300",children:[e(Ft,{className:"h-5 w-5"}),"Continuar a Conversa com o CFO IA"]}),a("div",{className:"flex items-center gap-2 mt-2",children:[e(Se,{children:"Faça perguntas adicionais sobre a análise ou peça esclarecimentos"}),e(ae,{variant:"outline",className:"bg-blue-100 dark:bg-blue-950/40 text-blue-700 dark:text-blue-400 border-blue-300 dark:border-blue-700 shrink-0",children:"2 créditos por pergunta"})]})]}),a(ee,{className:"space-y-4",children:[f.length>0&&a("div",{className:"space-y-3 max-h-96 overflow-y-auto pr-2",children:[f.map((B,F)=>e("div",{className:`flex ${B.role==="user"?"justify-end":"justify-start"}`,children:a("div",{className:`max-w-[80%] rounded-lg p-3 ${B.role==="user"?"bg-blue-600 text-white":"bg-gray-100 dark:bg-gray-800 text-gray-900 dark:text-gray-100 border"}`,children:[e("p",{className:"text-sm whitespace-pre-wrap",children:B.content}),e("p",{className:`text-xs mt-1 ${B.role==="user"?"text-blue-100":"text-gray-500 dark:text-gray-400"}`,children:vs(B.created_at)})]})},F)),e("div",{ref:Y})]}),a("div",{className:"flex gap-2",children:[e(Ce,{placeholder:"Ex: Por que o pró-labore está tão alto?",value:S,onChange:B=>Z(B.target.value),onKeyPress:B=>{B.key==="Enter"&&!z&&S.trim()&&ce()},disabled:z,className:"flex-1"}),e(j,{onClick:ce,disabled:z||!S.trim(),className:"bg-blue-600 hover:bg-blue-700",children:z?a(Ee,{children:[e(ba,{className:"h-4 w-4 mr-2 animate-spin"}),"Pensando..."]}):a(Ee,{children:[e(qs,{className:"h-4 w-4 mr-2"}),"Enviar"]})})]}),f.length===0&&a("div",{className:"text-center py-6 text-gray-500",children:[e(Ft,{className:"h-12 w-12 mx-auto mb-3 opacity-30"}),e("p",{className:"text-sm",children:"Faça sua primeira pergunta sobre a análise"}),e("p",{className:"text-xs mt-1",children:"Custo: 2 créditos por pergunta"})]})]})]})]}),M&&x.length>0&&a(K,{className:"border-2 border-purple-200 dark:border-purple-800 bg-white/80 dark:bg-card/80",children:[a(te,{children:[a(ne,{className:"flex items-center gap-2 text-purple-900 dark:text-purple-300",children:[e(sa,{className:"h-5 w-5"}),"Histórico de Análises (",x.length,"/20)"]}),e(Se,{children:"Ãltimas análises realizadas - mantidas por 90 dias"})]}),e(ee,{className:"space-y-3",children:x.map(B=>{const F=Ra[B.type],W=(F==null?void 0:F.icon)||$a;return e(K,{className:"border hover:border-purple-300 transition-colors",children:e(ee,{className:"pt-4",children:a("div",{className:"flex items-start justify-between gap-4",children:[a("div",{className:"flex items-start gap-3 flex-1",children:[e("div",{className:`p-2 rounded-lg ${(F==null?void 0:F.bgColor)||"bg-purple-100"}`,children:e(W,{className:`h-4 w-4 ${(F==null?void 0:F.color)||"text-purple-600"}`})}),a("div",{className:"flex-1 min-w-0",children:[a("div",{className:"flex items-center gap-2 mb-1",children:[e("h4",{className:"font-semibold text-gray-900 dark:text-gray-100",children:B.typeName}),a(ae,{variant:"secondary",className:"text-xs",children:[B.creditsUsed," cr
759éditos"]})]}),e("p",{className:"text-sm text-gray-600 dark:text-gray-400 mb-2",children:ar(B.date)}),e("p",{className:"text-sm text-gray-700 dark:text-gray-300 line-clamp-2",children:B.preview})]})]}),a("div",{className:"flex gap-2 shrink-0",children:[a(j,{onClick:()=>R(B),variant:"outline",size:"sm",children:[e(et,{className:"h-4 w-4 mr-1"}),"PDF"]}),e(j,{onClick:()=>{i(B.type),g(B.result)},variant:"outline",size:"sm",children:"Ver Completo"})]})]})})},B.id)})})]}),!d&&a("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-6",children:[a(K,{className:"border-purple-200 dark:border-purple-800 bg-white/60 dark:bg-card/60",children:[e(te,{children:a(ne,{className:"text-lg flex items-center gap-2",children:[e(ma,{className:"h-5 w-5 text-purple-600"}),"Análises DisponÃveis"]})}),a(ee,{className:"space-y-3",children:[a("div",{className:"flex items-start gap-2",children:[e($e,{className:"h-5 w-5 text-green-600 mt-0.5"}),a("div",{children:[e("p",{className:"font-medium",children:"Análise Completa 360°"}),e("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Visão integrada de todos os aspectos financeiros"})]})]}),a("div",{className:"flex items-start gap-2",children:[e($e,{className:"h-5 w-5 text-green-600 mt-0.5"}),a("div",{children:[e("p",{className:"font-medium",children:"Análises EspecÃficas"}),e("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"DRE, Break-even, Fluxo de Caixa, Tendências"})]})]}),a("div",{className:"flex items-start gap-2",children:[e($e,{className:"h-5 w-5 text-green-600 mt-0.5"}),a("div",{children:[e("p",{className:"font-medium",children:"Otimização e Benchmarking"}),e("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Oportunidades de melhoria vs mercado"})]})]})]})]}),a(K,{className:"border-blue-200 dark:border-blue-800 bg-white/60 dark:bg-card/60",children:[e(te,{children:a(ne,{className:"text-lg flex items-center gap-2",children:[e(
759oa,{className:"h-5 w-5 text-blue-600"}),"O que você recebe"]})}),a(ee,{className:"space-y-3",children:[a("div",{className:"flex items-start gap-2",children:[e(Oe,{className:"h-5 w-5 text-blue-600 mt-0.5"}),a("div",{children:[e("p",{className:"font-medium",children:"Diagnósticos Precisos"}),e("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Análise profunda com IA GPT-4 Turbo"})]})]}),a("div",{className:"flex items-start gap-2",children:[e(pa,{className:"h-5 w-5 text-blue-600 mt-0.5"}),a("div",{children:[e("p",{className:"font-medium",children:"Recomendações Acionáveis"}),e("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Ações especÃficas com prazos e prioridades"})]})]}),a("div",{className:"flex items-start gap-2",children:[e(et,{className:"h-5 w-5 text-blue-600 mt-0.5"}),a("div",{children:[e("p",{className:"font-medium",children:"Exportação em PDF"}),e("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Salve e compartilhe as análises"})]})]})]})]})]})]})]})}function Po({period:t}){const[r,s]=_.useState(!0),[n,o]=_.useState(null),[m,u]=_.useState(null),[i,d]=_.useState(null),[g,x]=_.useState(null);_.useEffect(()=>{y()},[t]);const y=async()=>{var M,E,h;try{s(!0);const{data:{user:c}}=await v.auth.getUser();if(!c)return;const b=new Date,N=qa(b),C=Xa(b),{data:A}=await v.from("accounts_payable").select("*").eq("user_id",c.id).gte("due_date",de(N,"yyyy-MM-dd")).lte("due_date",de(C,"yyyy-MM-dd")),{data:f}=await v.from("accounts_payable").select("*").eq("user_id",c.id).eq("paid",!1).lt("due_date",de(b,"yyyy-MM-dd")),{data:$}=await v.from("accounts_payable").select("*").eq("user_id",c.id).eq("paid",!1).gte("due_date",de(N,"yyyy-MM-dd")).lte("due_date",de(C,"yyyy-MM-dd")),{data:S}=await v.from("prolabore_partners").select("amount, frequency, active").eq("user_id",c.id).eq("active",!0),Z=(S==null?void 0:S.reduce((xe,q)=>{let L=q.amount||0;return q.frequency==="weekly"?L=L*4.33:q.frequency==="biweekly"?L=L*2:q.frequency==="quarterly"?L=L/3:q.frequency==="semiannual"?L=L/6:q.frequency==="annual"&&(L=L/12),xe+L},0))||0,{data:z}=await wa(v.from("sales").select("subtotal").eq("user_id",c.id).gte("created_at",de(N,"yyyy-MM-dd")).lte("created_at",de(C,"yyyy-MM-dd"))),X=(z==null?void 0:z.reduce((xe,q)=>xe+(Number(q.subtotal)||0),0))||0,{data:me}=await Ua(v.from("cash_register").select("*").eq("user_id",c.id).in("type",["opening","closing"]).order("created_at",{ascending:!1}).limit(1)),Y=((M=me==null?void 0:me[0])==null?void 0:M.type)==="opening"&&Number((E=me==null?void 0:me[0])==null?void 0:E.amount)||0,P=((h=me==null?void 0:me[0])==null?void 0:h.created_at)||de(N,"yyyy-MM-dd"),{data:w}=await Ua(v.from("cash_register").select("*").eq("user_id",c.id).gte("created_at",P).neq("type","opening").neq("type","closing")),O=(w||[]).filter(xe=>xe.type==="entry").reduce((xe,q)=>xe+Number(q.amount),0),H=(w||[]).filter(xe=>xe.type==="withdrawal").reduce((xe,q)=>xe+Number(q.amount),0),I=Y+O-H,U=(A==null?void 0:A.filter(xe=>xe.paid))||[],se=U.reduce((xe,q)=>xe+(Number(q.monthly_equivalent??q.amount)||0),0),le=U.filter(xe=>{var Ne,J;const q=(Ne=xe.cost_classification)==null?void 0:Ne.toLowerCase(),L=((J=xe.category)==null?void 0:J.toLowerCase())||"",V=L.includes("prolabore")||L.includes("pró-labore");return(q==="custo_fixo"||q==="custo fixo"||(q==="despesa_fixa"||q==="despesa fixa"))&&!V}).reduce((xe,q)=>xe+(Number(q.monthly_equivalent??q.amount)||0),0),ce=U.filter(xe=>{var L;const q=(L=xe.cost_classification)==null?void 0:L.toLowerCase();return q==="custo_variavel"||q==="custo variavel"||q==="despesa_variavel"||q==="despesa variavel"}).reduce((xe,q)=>xe+(Number(q.monthly_equivalent??q.amount)||0),0),R=X-se,pe=X-ce,B=X>0?pe/X*100:0,F=B>0?(le+Z)/(B/100):0,W=X>0&&F>0?(X-F)/X*100:0;let D=50;R>0&&(D+=20),(f==null?void 0:f.length)===0&&(D+=15),I>=(($==null?void 0:$.reduce((xe,q)=>xe+(Number(q.monthly_equivalent??q.amount)||0),0))||0)&&(D+=15),W>35?D+=10:W<20&&(D-=10),((f==null?void 0:f.length)||0)>0&&A&&f.length/A.length>.2&&(D-=10),D=Math.min(100,Math.max(0,D));const re=D>=80?"Excelente":D>=60?"Bom":D>=40?"Atenção":"CrÃtico",k=(f==null?void 0:f.length)||0,ke=(f==null?void 0:f.reduce((xe,q)=>xe+(Number(q.monthly_equivalent??q.amount)||0),0))||0,Q=($==null?void 0:$.length)||0,p=($==null?void 0:$.reduce((xe,q)=>xe+(Number(q.monthly_equivalent??q.amount)||0),0))||0,oe={healthScore:D,healthStatus:re,caixaDisponivel:I,contasPendentes:Q,valorPendente:p,contasVencidas:k,valorVencido:ke,receita:X,custos:le+ce,despesas:se,lucro:R,pontoEquilibrio:
759F,fluxoLiquido:X-se},he={receita:X,custosVariaveis:ce,margemContribuicao:pe,margemContribuicaoPct:B,custosFixos:le,despesasFixas:le,despesasVariaveis:ce,prolabore:Z,lucroOperacional:R,lucroOperacionalPct:X>0?R/X*100:0},ye={break_even_revenue:F,current_revenue:X,safety_margin_pct:W,contribution_margin_pct:B,fixed_costs:le+Z,variable_costs:ce},ge=I,Pe=X,Ue=p,Xe=ge+Pe-Ue,Ge={saldoAtual:ge,entradasPrevistas:Pe,saidasPrevistas:Ue,saldoFinal:Xe,projecao30dias:[]};o(oe),u(he),d(ye),x(Ge)}catch(c){console.error("Erro ao carregar dados para IA:",c)}finally{s(!1)}};return r?e("div",{className:"flex items-center justify-center p-12",children:a("div",{className:"text-center space-y-4",children:[e(ba,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),e("p",{className:"text-muted-foreground",children:"Carregando dados financeiros para análise..."})]})}):n?a("div",{className:"space-y-6",children:[a(K,{className:"bg-gradient-to-br from-purple-600 to-blue-600 text-white border-0 shadow-lg",children:[a(te,{className:"pb-3",children:[a(ne,{className:"flex items-center gap-3 text-2xl",children:[e("div",{className:"p-2 bg-white/20 rounded-lg backdrop-blur-sm",children:e(oa,{className:"h-6 w-6"})}),"Central de Análises com IA"]}),e(Se,{className:"text-purple-100",children:"Análises financeiras avançadas alimentadas por GPT-4 Turbo"})]}),a(ee,{children:[a("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[a("div",{className:"bg-white/10 backdrop-blur-sm rounded-xl p-4 border border-white/20 hover:bg-white/20 transition-all",children:[a("div",{className:"flex items-center justify-between mb-2",children:[e(aa,{className:"h-5 w-5 text-green-300"}),e(lr,{className:"h-4 w-4 text-green-300"})]}),e("p",{className:"text-xs text-purple-100 mb-1",children:"Receita do Mês"}),a("p",{className:"text-2xl font-bold",children:["R$ ",n.receita.toLocaleString("pt-BR",{minimumFractionDigits:2})]})]}),a("div",{className:"bg-white/10 backdrop-blur-sm rounded-xl p-4 border border-white/20 hover:bg-white/20 transition-all",children:[a("div",{className:"flex items-center justify-between mb-2",children:[e(Oe,{className:`h-5 w-5 ${n.lucro>=0?"text-green-300":"text-red-300"}`}),n.lucro>=0?e(lr,{className:"h-4 w-4 text-green-300"}):e(Vs,{className:"h-4 w-4 text-red-300"})]}),e("p",{className:"text-xs text-purple-100 mb-1",children:"Lucro Operacional"}),a("p",{className:`text-2xl font-bold ${n.lucro>=0?"text-green-300":"text-red-300"}`,children:["R$ ",Math.abs(n.lucro).toLocaleString("pt-BR",{minimumFractionDigits:2})]})]}),a("div",{className:"bg-white/10 backdrop-blur-sm rounded-xl p-4 border border-white/20 hover:bg-white/20 transition-all",children:[a("div",{className:"flex items-center justify-between mb-2",children:[e(ma,{className:"h-5 w-5 text-yellow-300"}),n.healthScore>=80?e(nt,{className:"h-4 w-4 text-green-300"}):n.healthScore>=40?e(Me,{className:"h-4 w-4 text-yellow-300"}):e(jt,{className:"h-4 w-4 text-red-300"})]}),e("p",{className:"text-xs text-purple-100 mb-1",children:"Saúde Financeira"}),a("div",{className:"flex items-baseline gap-2",children:[e("p",{className:"text-2xl font-bold",children:n.healthScore}),e("p",{className:"text-sm text-purple-100",children:"/100"})]}),e("p",{className:"text-xs text-purple-200 mt-1",children:n.healthStatus})]}),a("div",{className:"bg-white/10 backdrop-blur-sm rounded-xl p-4 border border-white/20 hover:bg-white/20 transition-all",children:[a("div",{className:"flex items-center justify-between mb-2",children:[e(ea,{className:"h-5 w-5 text-blue-300"}),e(Ca,{className:"h-4 w-4 text-blue-300"})]}),e("p",{className:"text-xs text-purple-100 mb-1",children:"Caixa DisponÃvel"}),a("p",{className:"text-2xl font-bold text-blue-300",children:["R$ ",n.caixaDisponivel.toLocaleString("pt-BR",{minimumFractionDigits:2})]})]})]}),n.contasVencidas>0&&a(Fe,{className:"mt-4 bg-red-500/20 border-red-400/30 text-white",children:[e(Me,{className:"h-4 w-4 text-red-200"}),a(Ie,{className:"text-red-100",children:[e("strong",{children:n.contasVencidas})," contas vencidas no valor de"," ",a("strong",{children:["R$ ",n.valorVencido.toLocaleStr
759ing("pt-BR",{minimumFractionDigits:2})]})]})]})]})]}),e(So,{dashboardStats:n,dreData:m,breakEvenData:i,cashFlowData:g})]}):e(Fe,{variant:"destructive",children:e(Ie,{children:"Erro ao carregar dados financeiros. Tente novamente."})})}const Mo={home:za,zap:zt,droplet:Js,wifi:Dr,phone:$r,chart:Ca,scale:Qs,lock:os,sparkle:oa,wrench:it,shield:Ir,landmark:ht,package:va,truck:Fr,dollar:aa,file:da};function vr({iconKey:t,className:r="h-5 w-5 text-gray-500 dark:text-gray-400"}){const s=Mo[t]??da;return e(s,{className:r})}function Ae({icon:t,label:r,value:s,onChange:n}){return a("div",{className:"flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-200 dark:border-gray-700",children:[a(be,{className:"text-sm font-medium flex items-center gap-2 text-gray-700 dark:text-gray-300",children:[e(t,{className:"h-4 w-4 text-gray-500 dark:text-gray-400 shrink-0"}),r]}),e(Ce,{type:"number",placeholder:"R$ 0",value:s||"",onChange:o=>n(parseFloat(o.target.value)||0),className:"w-32 text-right"})]})}function Ro({onComplete:t}){const[r,s]=_.useState("welcome"),[n,o]=_.useState(!1),[m,u]=_.useState(!1),[i,d]=_.useState(0),[g,x]=_.useState([{name:"Aluguel",amount:0,category:"Infraestrutura",icon:"home"},{name:"Energia Elétrica",amount:0,category:"Infraestrutura",icon:"zap"},{name:"Ãgua",amount:0,category:"Infraestrutura",icon:"droplet"},{name:"Internet",amount:0,category:"Infraestrutura",icon:"wifi"},{name:"Telefone",amount:0,category:"Infraestrutura",icon:"phone"},{name:"Contador",amount:0,category:"Serviços",icon:"chart"},{name:"Advogado",amount:0,category:"Serviços",icon:"scale"},{name:"Segurança",amount:0,category:"Infraestrutura",icon:"lock"},{name:"Limpeza",amount:0,category:"Serviços",icon:"sparkle"},{name:"Manutenção",amount:0,category:"Serviços",icon:"wrench"},{name:"Seguros",amount:0,category:"Serviços",icon:"shield"},{name:"IPTU/Impostos Fixos",amount:0,category:"Impostos",icon:"landmark"}]),[y,M]=_.useState([{name:"Matéria-prima",amount:0,category:"Produção",icon:"package"},{name:"Embalagens",amount:0,category:"Produção",icon:"package"},{name:"Insumos",amount:0,category:"Produção",icon:"package"},{name:"Frete",amount:0,category:"LogÃstica",icon:"truck"},{name:"Comissões",amount:0,category:"Vendas",icon:"dollar"}]),[E,h]=_.useState([{name:"Comissões de Vendedores",amount:0,category:"vendas"},{name:"Anúncios (Facebook/Google Ads)",amount:0,category:"marketing"},{name:"Taxas Absorvidas (cartão)",amount:0,category:"taxas"},{name:"Custo de Frete Grátis",amount:0,category:"logistica"}]),[c,b]=_.useState({chatgpt:0,midjourney:0,gemini:0,canva:0,adobe:0,figma:0,davinci:0,filmora:0,capcut:0,inshot:0,lightroom:0,picsart:0,vsco:0,premiereRush:0,envato:0,artlist:0,shutterstock:0,adobeStock:0,googleWorkspace:0,microsoft365:0,dropbox:0,notion:0,trello:0,asana:0,slack:0,zoom:0,shopeePremium:0,mlPremium:0,elo7Premium:0,shopify:0,erp:0,crm:0,marketingAutomation:0,other1:0,other2:0,other3:0}),[N,C]=_.useState([{category:"Moradia (aluguel, condomÃnio, IPTU pessoal)",amount:0},{category:"Alimentação",amount:0},{category:"Transporte (combustÃvel, manutenção carro)",amount:0},{category:"Educação (filhos, cursos, mensalidades)",amount:0},{category:"Saúde (plano, medicamentos, consultas)",amount:0},{category:"Lazer (viagens, restaurantes, hobbies)",amount:0},{category:"Vestuário",amount:0},{category:"Contas Pessoais (água, luz, internet casa)",amount:0},{category:"Outros gastos pessoais",amount:0}]),[A,f]=_.useState({hoursPerDay:8,daysPerMonth:20}),[$,S]=_.useState(0),[Z,z]=_.useState(0),X=async()=>{try{const{data:Q,error:p}=await v.from("employees").select("salary");if(p)throw p;const oe=(Q==null?void 0:Q.reduce((he,ye)=>he+(ye.salary||0),0))||0;z(oe)}catch(Q){console.error("Erro ao buscar funcionários:",Q)}},me=_.useCallback(async()=>{try{const{data:{user:Q}}=await v.auth.getUser();if(!Q)return;const p=await Ot(Q.id);p.length>0&&C(p);const{data:oe,error:he}=await v.from("accounts_payable").select("*").eq("user_id",Q.id).in("source",["manual","assistant"]);if(he)throw he;if(!oe||oe.length===0)return;const ye=g.map(q=>{const L=oe.find(V=>{var l;return((l=V.description)==null?void 0:l.toLowerCase())===q.name.toLowerCase()});return L?{...q,amount:L.amount}:q});ye.some((q,L)=>q.amount!==g[L].amount)&&x(ye);{const q={...c};let L=!1;oe.forEach(V=>{var T;const l=((T=V.description)==null?void 0:T.toLowerCase())||"";(l.includes("chatgpt")||l.includes("openai"))&&(q.chatgpt=V.amount,L=!0),l.includes("midjourney")&&(q.midjourney=V.amount,L=!0),l.includes("gemini")&&(q.gemini=V.amount,L=!0),l.includes("canva")&&(q.canva=V.amount,L=!0),l.includes("adobe")&&!l.includes("stock")&&(q.adobe=V.amount,L=!0),l.includes("figma")&&(q.figma=V.amount,L=!0),l.includes("davinci")&&(q.davinci=V.amount,L=!0),l.includes("filmora")&&(q.filmora=V.amount,L=!0),l.includes("capcut")&&(q.capcut=V.amount,L=!0),l.includes("inshot")&&(q.inshot=V.amount,L=!0),l.includes("lightroom")&&(q.lightroom=V.amount,L=!0),l.includes("picsart")&&(q.picsart=V.amount,L=!0),l.includes("vsco")&&(q.vsco=V.amount,L=!0),l.includes("premiere")&&l.includes("rush")&&(q.premiereRush=V.amount,L=!0),l.includes("envato")&&(q.envato=V.amount,L=!0),l.includes("artlist")&&(q.artlist=V.amount,L=!0),l.includes("shutterstock")&&(q.shutterstock=V.amount,L=!0),l.includes("adobe")&&l.includes("stock")&&(q.adobeStock=V.amount,L=!0),l.includes("google")&&l.includes("workspace")&&(q.googleWorksp
759ace=V.amount,L=!0),(l.includes("microsoft")||l.includes("365"))&&(q.microsoft365=V.amount,L=!0),l.includes("dropbox")&&(q.dropbox=V.amount,L=!0),l.includes("notion")&&(q.notion=V.amount,L=!0),l.includes("trello")&&(q.trello=V.amount,L=!0),l.includes("asana")&&(q.asana=V.amount,L=!0),l.includes("slack")&&(q.slack=V.amount,L=!0),l.includes("zoom")&&(q.zoom=V.amount,L=!0),l.includes("shopee")&&l.includes("premium")&&(q.shopeePremium=V.amount,L=!0),l.includes("mercado")&&l.includes("livre")&&(q.mlPremium=V.amount,L=!0),l.includes("elo7")&&(q.elo7Premium=V.amount,L=!0),l.includes("shopify")&&(q.shopify=V.amount,L=!0),l.includes("erp")&&!l.includes("crm")&&(q.erp=V.amount,L=!0),l.includes("crm")&&(q.crm=V.amount,L=!0),l.includes("automação")&&l.includes("marketing")&&(q.marketingAutomation=V.amount,L=!0)}),L&&b(q)}const Pe=oe.find(q=>{var L,V,l;return q.expense_category==="prolabore"||q.account_type==="prolabore"||((L=q.description)==null?void 0:L.toLowerCase().includes("pró-labore"))||((V=q.description)==null?void 0:V.toLowerCase().includes("pro-labore"))||((l=q.description)==null?void 0:l.toLowerCase().includes("prolabore"))});Pe&&S(Pe.amount);const Ue=y.map(q=>{const L=oe.find(V=>{var l;return((l=V.description)==null?void 0:l.toLowerCase())===q.name.toLowerCase()&&V.cost_classification==="custo_variavel"});return L?{...q,amount:L.amount}:q});Ue.some((q,L)=>q.amount!==y[L].amount)&&M(Ue);const Ge=E.map(q=>{const L=oe.find(V=>{var l;return((l=V.description)==null?void 0:l.toLowerCase())===q.name.toLowerCase()&&V.cost_classification==="custo_variavel"});return L?{...q,amount:L.amount}:q});Ge.some((q,L)=>q.amount!==E[L].amount)&&h(Ge)}catch(Q){console.error(" Erro ao carregar despesas existentes:",Q)}},[]);_.useEffect(()=>{X(),me()},[me]);const we=g.reduce((Q,p)=>Q+p.amount,0),Y=Object.values(c).reduce((Q,p)=>Q+p,0),P=N.reduce((Q,p)=>Q+p.amount,0),w=y.reduce((Q,p)=>Q+p.amount,0),O=E.reduce((Q,p)=>Q+p.amount,0),H=A.hoursPerDay*A.daysPerMonth,I=H>0?P/H:0,U=Rt(P),se=()=>{x([...g,{name:"",amount:0,category:"Outros",icon:"file"}])},le=()=>{M([...y,{name:"",amount:0,category:"Outros",icon:"file"}])},ce=()=>{h([...E,{name:"",amount:0,category:"outros"}])},R=Q=>{x(g.filter((p,oe)=>oe!==Q))},pe=Q=>{M(y.filter((p,oe)=>oe!==Q))},B=Q=>{h(E.filter((p,oe)=>oe!==Q))},F=["welcome","fixed-costs","variable-costs","variable-extras","subscriptions","personal","labor-cost","prolabore","summary"],W=F.indexOf(r),D=()=>{W<F.length-1&&s(F[W+1])},re=()=>{W>0&&s(F[W-1])},k=async()=>{try{o(!0);const{data:{user:Q}}=await v.auth.getUser();if(!Q)throw new Error("Usuário não autenticado");const p=new Date,oe=p.getMonth(),he=p.getFullYear(),ye=p.getDate(),ge=new Date(he,oe,1).toISOString().split("T")[0],Pe=new Date(he,oe+1,0).toISOString().split("T")[0],Ue=p.toISOString().split("T")[0],{data:Xe}=await v.from("accounts_payable").select("id, due_date, recurrence_day").eq("user_id",Q.id).eq("recurrence_type","monthly").eq("paid",!1).lt("due_date",Ue);if(Xe&&Xe.length>0)for(const J of Xe){const Re=new Date(p);Re.setDate(Re.getDate()+3),await v.from("accounts_payable").update({due_date:Re.toISOString().split("T")[0]}).eq("id",J.id)}const Ge=J=>{if(ye<=J)return new Date(he,oe,J);{const Re=new Date(p);return Re.setDate(Re.getDate()+3),Re}};await v.from("fixed_costs").delete().eq("user_id",Q.id).is("is_employee_cost",!1);const xe=g.filter(J=>J.amount>0).map(J=>({user_id:Q.id,name:J.name,amount:J.amount,category:J.category,is_active:!0}));if(xe.length>0){const{error:J}=await v.from("fixed_costs").insert(xe);if(J)throw J}const L=[{key:"chatgpt",name:"ChatGPT",category:"IA"},{key:"midjourney",name:"Midjourney",category:"IA"},{key:"gemini",name:"Gemini Advanced",category:"IA"},{key:"canva",name:"Canva Pro",category:"Design"},{key:"adobe",name:"Adobe Creative Cloud",category:"Design"},{key:"figma",name:"Figma Professional",category:"Design"},{key:"davinci",name:"DaVinci Resolve Studio",category:"Design"},{key:"filmora",name:"Filmora",category:"Design"},{key:"capcut",name:"CapCut Pro",category:"Design Mobile"},{key:"inshot",name:"InShot Pro",category:"Design Mobile"},{key:"lightroom",name:"Lightroom Mobile",category:"Design Mobile"},{key:"picsart",name:"PicsArt Gold",category:"Design Mobile"},{key:"vsco",name:"VSCO Membership",category:"Design Mobile"},{key:"premiereRush",name:"Premiere Rush",category:"Design Mobile"},{key:"envato",name:"Envato Elements",category:"MÃdia"},{key:"artlist",name:"Artlist Max",category:"MÃdia"},{key:"shutterstock",name:"Shutterstock",category:"MÃdia"},{key:"adobeStock",name:"Adobe Stock",category:"MÃdia"}
759,{key:"googleWorkspace",name:"Google Workspace",category:"Produtividade"},{key:"microsoft365",name:"Microsoft 365",category:"Produtividade"},{key:"dropbox",name:"Dropbox Business",category:"Produtividade"},{key:"notion",name:"Notion Team",category:"Produtividade"},{key:"trello",name:"Trello Premium",category:"Produtividade"},{key:"asana",name:"Asana Premium",category:"Produtividade"},{key:"slack",name:"Slack Pro",category:"Produtividade"},{key:"zoom",name:"Zoom Pro",category:"Produtividade"},{key:"shopeePremium",name:"Shopee Premium",category:"E-commerce"},{key:"mlPremium",name:"Mercado Livre Premium",category:"E-commerce"},{key:"elo7Premium",name:"Elo7 Premium",category:"E-commerce"},{key:"shopify",name:"Shopify",category:"E-commerce"},{key:"erp",name:"Sistema ERP",category:"Gestão"},{key:"crm",name:"Sistema CRM",category:"Gestão"},{key:"marketingAutomation",name:"Automação de Marketing",category:"Gestão"},{key:"other1",name:"Outra Assinatura 1",category:"Outros"},{key:"other2",name:"Outra Assinatura 2",category:"Outros"},{key:"other3",name:"Outra Assinatura 3",category:"Outros"}].filter(J=>c[J.key]>0).map(J=>({user_id:Q.id,name:J.name,amount:c[J.key],category:J.category,is_active:!0}));if(L.length>0){const{error:J}=await v.from("fixed_costs").insert(L);if(J)throw J}const l=[...xe,...L].map(J=>{const Re=J.category==="IA"||J.category==="Design Desktop"||J.category==="Design Mobile"||J.category==="MÃdia"||J.category==="Produtividade"||J.category==="E-commerce"||J.category==="Gestão"||J.category==="Outros"?10:5,ia=Ge(Re),la=J.category==="IA"||J.category==="Design Desktop"||J.category==="Design Mobile"||J.category==="MÃdia"||J.category==="Produtividade"||J.category==="E-commerce"||J.category==="Gestão"||J.category==="Outros";return{name:J.name,amount:J.amount,cost_classification:"despesa_fixa",cost_center:"administrativo",account_type:"expense",defaults:{due_date:ia.toISOString().split("T")[0],recurrence_day:Re,payment_method:"pix",alert_days_before:3}}}),T=await Kt(Q.id,l);ue.success(` Contas processadas: ${T.created} criadas, ${T.updated} atualizadas, ${T.deleted} removidas`,{duration:5e3}),d(T.created+T.updated);const Ne=[...y.filter(J=>J.name.trim()!==""),...E.filter(J=>J.name.trim()!=="")].map(J=>{const Re=Ge(5);return{name:J.name,amount:J.amount,cost_classification:"custo_variavel",cost_center:"producao",account_type:"expense",defaults:{due_date:Re.toISOString().split("T")[0],recurrence_day:5,payment_method:"pix",alert_days_before:3}}});Ne.length>0&&await Kt(Q.id,Ne),await fs(Q.id,N),$>0?(await wr({userId:Q.id,totalAmount:$,syncPayable:!0,personalExpenses:N}),ue.success(`Pró-labore configurado: ${ve($)}`)):await ut(Q.id,{syncPayable:!1}),await xs(Q.id),u(!0)}catch(Q){console.error("Erro ao salvar configuração:",Q),ue.error("Erro ao salvar configuração. Verifique os logs.")}finally{o(!1)}},ke=()=>{var Q;switch(r){case"welcome":return a(K,{className:"border-2 border-blue-200 dark:border-blue-800 bg-gradient-to-br from-blue-50 to-purple-50 dark:from-blue-950/30 dark:to-purple-950/30",children:[a(te,{className:"text-center pb-3",children:[e("div",{className:"flex justify-center mb-4",children:e("div",{className:"h-20 w-20 rounded-full bg-blue-500 flex items-center justify-center",children:e(oa,{className:"h-10 w-10 text-white"})})}),e(ne,{className:"text-3xl",children:"Bem-vindo ao Assistente Financeiro!"}),e(Se,{className:"text-base mt-2",children:"Vou te ajudar a configurar seu sistema financeiro de forma simples e rápida"})]}),e(ee,{children:a("div",{className:"space-y-4",children:[a("div",{className:"bg-white dark:bg-card/60 rounded-lg p-4 border border-gray-200 dark:border-gray-700",children:[a("h3",{className:"font-semibold mb-2 flex items-center gap-2 text-gray-900 dark:text-gray-100",children:[e($e,{className:"h-5 w-5 text-green-500"}),"O que vamos configurar:"]}),a("ul",{className:"space-y-2 text-sm text-gray-700 dark:text-gray-300",children:[a("li",{className:"flex items-center gap-2",children:[e(za,{className:"h-4 w-4 text-blue-500"}),e("span",{children:"Custos fixos (aluguel, luz, água, internet...)"})]}),a("li",{className:"flex items-center gap-2",children:[e(va,{className:"h-4 w-4 text-orange-500"}),e("span",{children:"Custos variáveis (matéria-prima, insumos...)"})]}),a("li",{className:"flex items-center gap-2",children:[e(Ba,{className:"h-4 w-4 text-purple-500"}),e("span",{children:"Assinaturas mensais/anuais"})]}),a("li",{className:"flex items-center gap-2",children:[e(at,{className:"h-4 w-4 text-green-500"}),e("span",{children:"Seus gastos pessoais (para calcular pró-labore)"})]}),a("li",{className:"flex items-center gap-2",children:[e(Aa,{className:"h-4 w-4 text-indigo-500"}),e("span",{children:"Importar salários dos funcionários cadastrados"})]}),a("li",{className:"flex items-center gap-2",children:[e(aa,{className:"h-4 w-4 text-emerald-500"}),e("span",{children:"Definir seu pró-labore ideal"})]})]})]}),e("div",{className:"bg-yellow-50 dark:bg-yellow-950/30 rounded-lg p-4 border border-yellow-200 dark:border-yellow-800",children:a("div",{className:"flex items-start gap-2",children:[e(Me,{className:"h-5 w-5 text-yellow-600 dark:text-yellow-400 mt-0.5"}),a("div",{className:"text-sm text-yellow-800 dark:text-yellow-300",children:[a("p",{className:"font-semibold mb-1 flex items-center gap-1",children:[e(ca,{className:"h-4 w-4"})," Por que isso é importante?"]}),e("p",{children:"Com essas informações, o sistema vai calcular automaticamente sua margem de contribuição, DRE gerencial e indicar se sua empresa está lucrando ou tendo prejuÃzo."})]})]})}),a("p",{className:"text-center text-sm text-gray-600 dark:text-gray-400 flex items-center justify-center gap-1",children:[e(Ws,{className:"h-4 w-4"})," Tempo estimado: ",e("span",{className:"font-semibold",children:"5-10 minutos"})]})]})})]});case"fixed-costs":return a(K,{children:[a(te,{children:[a(ne,{className:"flex items-center gap-2",children:[e(za,{className:"h-6 w-6 text-blue-500"}),"Custos Fixos Mensais DA EMPRESA"]}),e(Se,{children:"Gastos da EMPRESA que você tem todo mês, independente de quantas vendas fizer"})]}),e(ee,{children:a("div",{className:"space-y-4",children:[a("div",{className:"bg-amber-50 dark:bg-amber-950/30 border-2 border-amber-200 dark:border-amber-800 rounded-lg p-4 mb-4",children:[a("p",{className:"text-sm font-semibold text-amber-900 dark:text-amber-200 flex items-center gap-2",children:[e(Me,{className:"h-4 w-4"}),"IMPORTANTE: Custos DA EMPRESA (não seus gastos pessoais!)"]}),e("p",{className:"text-xs text-amber-800 dark:text-amber-300 mt-2",children:"Aqui você cadastra APENAS os custos que a empresa tem (aluguel do estabelecimento, luz da loja, internet comercial, etc.). Seus gastos pessoais vão na etapa 5!"})]}),g.map((p,oe)=>a("div",{className:"flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-200 dark:border-gray-700",children:[e("div",{className:"p-1.5 rounded-md bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 text-gray-500 dark:text-gray-400",children:e(vr,{iconKey:p.icon})}),a("div",{className:"flex-1",children:[e(Ce,{type:"text",placeholder:"Nome do custo",value:p.name,onChange:he=>{const ye=[...g];ye[oe].name=he.target.value,x(ye)},className:"font-medium mb-1"}),e("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:p.category})]}),e("div",{className:"w-32",children:e(Ce,{type:"number",placeholder:"R$ 0,00",value:p.amount||"",onChange:he=>{const ye=[...g];ye[oe].amount=parseFloat(he.target.value)||0,x(ye)},className:"text-right"})}),g.length>6&&e(j,{size:"sm",variant:"ghost",onClick:()=>R(oe),children:e(ya,{className:"h-4 w-4 text-red-500"})})]},oe)),a(j,{variant:"outline",onClick:se,className:"w-full border-dashed border-2",children:[e(ga,{className:"h-4 w-4 mr-2"}),"Adicionar Outro Custo Fixo"]}),e(He,{}),a("div",{className:"flex items-center justify-between p-4 bg-blue-50 dark:bg-blue-950/30 rounded-lg border border-blue-200 dark:border-blue-800",children:[e("span",{className:"font-semibold text-blue-900 dark:text-blue-200",children:"Total de Custos Fixos/Mês:"}
759),e("span",{className:"text-xl font-bold text-blue-600 dark:text-blue-400",children:ve(we)})]}),e("div",{className:"bg-blue-50 dark:bg-blue-950/30 rounded-lg p-3 border border-blue-200 dark:border-blue-800",children:a("p",{className:"text-sm text-blue-800 dark:text-blue-300 flex items-start gap-2",children:[e(ca,{className:"h-4 w-4 mt-0.5 shrink-0"}),a("span",{children:[e("strong",{children:"Dica:"})," Custos fixos são aqueles que a EMPRESA paga mesmo se não vender nada (aluguel do estabelecimento, luz, internet, salários, etc.). Eles não variam com vendas."]})]})})]})})]});case"variable-costs":return a(K,{children:[a(te,{children:[a(ne,{className:"flex items-center gap-2",children:[e(va,{className:"h-6 w-6 text-orange-500"}),"Custos Variáveis DA EMPRESA (Estimativa Mensal)"]}),e(Se,{children:"Gastos da EMPRESA que variam conforme suas vendas (matéria-prima, embalagens, comissões...)"})]}),e(ee,{children:a("div",{className:"space-y-4",children:[y.map((p,oe)=>a("div",{className:"flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-200 dark:border-gray-700",children:[e("div",{className:"p-1.5 rounded-md bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 text-gray-500 dark:text-gray-400",children:e(vr,{iconKey:p.icon})}),a("div",{className:"flex-1",children:[e(Ce,{type:"text",placeholder:"Nome do custo variável",value:p.name,onChange:he=>{const ye=[...y];ye[oe].name=he.target.value,M(ye)},className:"font-medium mb-1"}),e("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Média mensal estimada"})]}),e("div",{className:"w-32",children:e(Ce,{type:"number",placeholder:"R$ 0,00",value:p.amount||"",onChange:he=>{const ye=[...y];ye[oe].amount=parseFloat(he.target.value)||0,M(ye)},className:"text-right"})}),y.length>3&&e(j,{size:"sm",variant:"ghost",onClick:()=>pe(oe),children:e(ya,{className:"h-4 w-4 text-red-500"})})]},oe)),a(j,{variant:"outline",onClick:le,className:"w-full border-dashed border-2",children:[e(ga,{className:"h-4 w-4 mr-2"}),"Adicionar Outro Custo Variável"]}),e(He,{}),a("div",{className:"flex items-center justify-between p-4 bg-orange-50 dark:bg-orange-950/30 rounded-lg border border-orange-200 dark:border-orange-800",children:[e("span",{className:"font-semibold text-orange-900 dark:text-orange-200",children:"Total Estimado/Mês:"}),e("span",{className:"text-xl font-bold text-orange-600 dark:text-orange-400",children:ve(w)})]}),e("div",{className:"bg-orange-50 dark:bg-orange-950/30 rounded-lg p-3 border border-orange-200 dark:border-orange-800",children:a("p",{className:"text-sm text-orange-800 dark:text-orange-300 flex items-start gap-2",children:[e(ca,{className:"h-4 w-4 mt-0.5 shrink-0"}),a("span",{children:[e("strong",{children:"Dica:"})," Custos variáveis DA EMPRESA são aqueles que aumentam quando você vende mais (matéria-prima, embalagens, comissões, frete). Informe uma média mensal estimada."]})]})})]})})]});case"variable-extras":return a(K,{children:[a(te,{children:[a(ne,{className:"flex items-center gap-2",children:[e(Oe,{className:"h-6 w-6 text-pink-500"}),"Despesas Variáveis EXTRAS da Empresa"]}),e(Se,{children:"Comissões, anúncios, taxas absorvidas e outros gastos variáveis especiais"})]}),e(ee,{children:a("div",{className:"space-y-4",children:[a("div",{className:"bg-blue-50 dark:bg-blue-950/30 rounded-lg p-4 border-2 border-blue-200 dark:border-blue-800",children:[a("div",{className:"flex items-center gap-2 mb-2",children:[e(Me,{className:"h-5 w-5 text-blue-600 dark:text-blue-400"}),e("h4",{className:"font-semibold text-blue-900 dark:text-blue-200",children:"O que incluir aqui?"})]}),a("div",{className:"space-y-2 text-sm text-blue-800 dark:text-blue-300",children:[a("p",{className:"flex items-start gap-2",children:[e($e,{className:"h-4 w-4 text-green-600 dark:text-green-400 mt-0.5 shrink-0"})," ",a("span",{children:[e("strong",{children:"INCLUA:"})," Comissões de vendedores, anúncios pagos (Facebook/Google), taxas de cartão que você absorve, custo de frete grátis"]})]}),a("p",{className:"flex items-start gap-2",children:[e(jt,{className:"h-4 w-4 text-red-600 dark:text-red-400 mt-0.5 shrink-0"})," ",a("span",{children:[e("strong",{children:"NÃO INCLUA:"}),' Matéria-prima, embalagens (já estão em "Custos Variáveis"), salários fixos (já estão em "Custos Fixos")']})]})]})]}),E.map((p,oe)=>a("div",{className:"flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-200 dark:border-gray-700",children:[a("div",{className:"flex-1",children:[e(Ce,{type:"text",placeholder:"Nome da despesa",value:p.name,onChange:he=>{const ye=[...E];ye[oe].name=he.target.value,h(ye)},className:"font-medium mb-1"}),e("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Média mensal estimada"})]}),e("div",{className:"w-32",children:e(Ce,{type:"number",placeholder:"R$ 0,00",value:p.amount||"",onChange:he=>{const ye=[...E];ye[oe].amount=parseFloat(he.target.value)||0,h(ye)},className:"text-right"})}),E.length>4&&e(j,{size:"sm",variant:"ghost",onClick:()=>B(oe),children:e(ya,{className:"h-4 w-4 text-red-500"})})]},oe)),a(j,{variant:"outline",onClick:ce,className:"w-full border-dashed border-2",children:[e(ga,{className:"h-4 w-4 mr-2"}),"Adicionar Outra Despesa Extra"]}),e(He,{}),a("div",{className:"flex items-center justify-between p-4 bg-pink-50 dark:bg-pink-950/30 rounded-lg border border-pink-200 dark:border-pink-800",children:[e("span",{className:"font-semibold text-pink-900 dark:text-pink-200",children:"Total Estimado/Mês:"}),e("span",{className:"text-xl font-bold text-pink-600 dark:text-pink-400",children:ve(O)})]}),e("div",{className:"bg-pink-50 dark:bg-pink-950/30 rounded-lg p-3 border border-pink-200 dark:border-pink-800",children:a("p",{className:"text-sm text-pink-800 dark:text-pink-300 flex items-start gap-2",children:[e(ca,{className:"h-4 w-4 mt-0.5 shrink-0"}),a("span",{children:[e("strong",{children:"Exemplos:"})," Se você paga 5% de comissão aos vendedores e vende R$ 10mil/mês, isso dá R$ 500/mês. Ou se investe R$ 800/mês em anúncios no Facebook. Ou absorve R$ 400 em taxas de cartão."]})]})})]})})]});case"subscriptions":return a(K,{children:[a(te,{children:[a(ne,{className:"flex items-center gap-2",children:[e(Ba,{className:"h-6 w-6 text-purple-500"}),"Assinaturas e Serviços Recorrentes DA EMPRESA"]}),e(Se,{children:"Gastos mensais com softwares, ferramentas e serviços"})]}),e(ee,{children:a("div",{className:"space-y-6",children:[a("div",{className:"bg-amber-50 dark:bg-amber-950/30 rounded-lg p-4 border-2 border-amber-300 dark:border-amber-700",children:[a("div",{className:"flex items-center gap-2 mb-2",children:[e(Me,{className:"h-5 w-5 text-amber-600 dar
759k:text-amber-400"}),e("h4",{className:"font-semibold text-amber-900 dark:text-amber-200",children:"ASSINATURAS DA EMPRESA"})]}),e("p",{className:"text-sm text-amber-800 dark:text-amber-300",children:'Liste apenas assinaturas pagas pela empresa. Netflix, Spotify pessoal, etc. vão em "Gastos Pessoais".'})]}),a(pt,{defaultValue:"ia",className:"w-full",children:[a(gt,{className:"grid w-full grid-cols-5",children:[a(qe,{value:"ia",children:[e(lt,{className:"h-4 w-4 mr-2"}),"IA"]}),a(qe,{value:"design",children:[e(Ka,{className:"h-4 w-4 mr-2"}),"Design"]}),a(qe,{value:"produtividade",children:[e(cr,{className:"h-4 w-4 mr-2"}),"Produtividade"]}),a(qe,{value:"ecommerce",children:[e(dr,{className:"h-4 w-4 mr-2"}),"E-commerce"]}),e(qe,{value:"outros",children:"Outros"})]}),e(Je,{value:"ia",className:"space-y-3 mt-4",children:a("div",{className:"grid gap-3",children:[e(Ae,{icon:lt,label:"ChatGPT Plus/Team",value:c.chatgpt,onChange:p=>b({...c,chatgpt:p})}),e(Ae,{icon:Ka,label:"Midjourney",value:c.midjourney,onChange:p=>b({...c,midjourney:p})}),e(Ae,{icon:oa,label:"Gemini Advanced",value:c.gemini,onChange:p=>b({...c,gemini:p})})]})}),a(Je,{value:"design",className:"space-y-3 mt-4",children:[a("div",{className:"mb-4",children:[e(ae,{variant:"outline",className:"mb-2",children:"Design Desktop"}),a("div",{className:"grid gap-3",children:[e(Ae,{icon:Ka,label:"Canva Pro",value:c.canva,onChange:p=>b({...c,canva:p})}),e(Ae,{icon:Ls,label:"Adobe Creative Cloud",value:c.adobe,onChange:p=>b({...c,adobe:p})}),e(Ae,{icon:da,label:"Figma Professional",value:c.figma,onChange:p=>b({...c,figma:p})}),e(Ae,{icon:At,label:"DaVinci Resolve Studio",value:c.davinci,onChange:p=>b({...c,davinci:p})}),e(Ae,{icon:Bs,label:"Filmora",value:c.filmora,onChange:p=>b({...c,filmora:p})})]})]}),e(He,{}),a("div",{children:[e(ae,{variant:"outline",className:"mb-2",children:"Design Mobile"}),a("div",{className:"grid gap-3",children:[e(Ae,{icon:zs,label:"CapCut Pro",value:c.capcut,onChange:p=>b({...c,capcut:p})}),e(Ae,{icon:js,label:"InShot Pro",value:c.inshot,onChange:p=>b({...c,inshot:p})}),e(Ae,{icon:mr,label:"Lightroom Mobile",value:c.lightroom,onChange:p=>b({...c,lightroom:p})}),e(Ae,{icon:ur,label:"PicsArt Gold",value:c.picsart,onChange:p=>b({...c,picsart:p})}),e(Ae,{icon:mr,label:"VSCO Membership",value:c.vsco,onChange:p=>b({...c,vsco:p})}),e(Ae,{icon:At,label:"Premiere Rush",value:c.premiereRush,onChange:p=>b({...c,premiereRush:p})})]})]}),e(He,{}),a("div",{children:[e(ae,{variant:"outline",className:"mb-2",children:"Bancos de MÃdia"}),a("div",{className:"grid gap-3",children:[e(Ae,{icon:vn,label:"Envato Elements",value:c.envato,onChange:p=>b({...c,envato:p})}),e(Ae,{icon:Nn,label:"Artlist Max",value:c.artlist,onChange:p=>b({...c,artlist:p})}),e(Ae,{icon:ur,label:"Shutterstock",value:c.shutterstock,onChange:p=>b({...c,shutterstock:p})}),e(Ae,{icon:va,label:"Adobe Stock",value:c.adobeStock,onChange:p=>b({...c,adobeStock:p})})]})]})]}),e(Je,{value:"produtividade",className:"space-y-3 mt-4",children:a("div",{className:"grid gap-3",children:[e(Ae,{icon:Us,label:"Google Workspace",value:c.googleWorkspace,onChange:p=>b({...c,googleWorkspace:p})}),e(Ae,{icon:cr,label:"Microsoft 365",value:c.microsoft365,onChange:p=>b({...c,microsoft365:p})}),e(Ae,{icon:Gs,label:"Dropbox Business",value:c.dropbox,onChange:p=>b({...c,dropbox:p})}),e(Ae,{icon:da,label:"Notion Team",value:c.notion,onChange:p=>b({...c,notion:p})}),e(Ae,{icon:Hs,label:"Trello Premium",value:c.trello,onChange:p=>b({...c,trello:p})}),e(Ae,{icon:$e,label:"Asana Premium",value:c.asana,onChange:p=>b({...c,asana:p})}),e(Ae,{icon:Ft,label:"Slack Pro",value:c.slack,onChange:p=>b({...c,slack:p})}),e(Ae,{icon:At,label:"Zoom Pro",value:c.zoom,onChange:p=>b({...c,zoom:p})})]})}),e(Je,{value:"ecommerce",className:"space-y-3 mt-4",children:a("div",{className:"grid gap-3",children:[e(Ae,{icon:Xs,label:"Shopee Premium",value:c.shopeePremium,onChange:p=>b({...c,shopeePremium:p})}),e(Ae,{icon:Ys,label:"Mercado Livre Premium",value:c.mlPremium,onChange:p=>b({...c,mlPremium:p})}),e(Ae,{icon:Ka,label:"Elo7 Premium",value:c.elo7Premium,onChange:p=>b({...c,elo7Premium:p})}),e(Ae,{icon:dr,label:"Shopify",value:c.shopify,onChange:p=>b({...c,shopify:p})})]})}),a(Je,{value:"outros",className:"space-y-3 mt-4",children:[a("div",{className:"mb-4",children:[e(ae,{variant:"outline",className:"mb-2",children:"Gestão & ERP"}),a("div",{className:"grid gap-3",children:[e(Ae,{icon:ot,label:"Sistema ERP",value:c.erp,onChange:p=>b({...c,erp:p})}),e(Ae,{icon:Aa,label:"Sistema CRM",value:c.crm,onChange:p=>b({...c,crm:p})}),e(Ae,{icon:Ca,label:"Automação de Marketing",value:c.marketingAutomation,onChange:p=>b({...c,marketingAutomation:p})})]})]}),e(He,{}),a("div",{children:[e(ae,{variant:"outline",className:"mb-2",children:"Outras Assinaturas"}),a("div",{className:"grid gap-3",children:[a("div",{className:"flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-200 dark:border-gray-700",children:[e(Ce,{placeholder:"Nome da assinatura",value:"Outra Assinatura 1",className:"flex-1 mr-2",readOnly:!0}),e(Ce,{type:"number",placeholder:"R$ 0",value:c.other1||"",onChange:p=>b({...c,other1:parseFloat(p.target.value)||0}),className:"w-32 text-right"})]}),a("div",{className:"flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-200 dark:border-gray-700",children:[e(Ce,{placeholder:"Nome da assinatura",value:"Outra Assinatura 2",className:"flex-1 mr-2",readOnly:!0}),e(Ce,{type:"number",placeholder:"R$ 0",value:c.other2||"",onChange:p=>
759b({...c,other2:parseFloat(p.target.value)||0}),className:"w-32 text-right"})]}),a("div",{className:"flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-200 dark:border-gray-700",children:[e(Ce,{placeholder:"Nome da assinatura",value:"Outra Assinatura 3",className:"flex-1 mr-2",readOnly:!0}),e(Ce,{type:"number",placeholder:"R$ 0",value:c.other3||"",onChange:p=>b({...c,other3:parseFloat(p.target.value)||0}),className:"w-32 text-right"})]})]})]})]})]}),e(He,{}),a("div",{className:"flex items-center justify-between p-4 bg-purple-50 dark:bg-purple-950/30 rounded-lg border border-purple-200 dark:border-purple-800",children:[e("span",{className:"font-semibold text-purple-900 dark:text-purple-200",children:"Total Mensal em Assinaturas:"}),e("span",{className:"text-xl font-bold text-purple-600 dark:text-purple-400",children:ve(Y)})]})]})})]});case"personal":return a(K,{children:[a(te,{children:[a(ne,{className:"flex items-center gap-2",children:[e(at,{className:"h-6 w-6 text-green-500"}),"Seus Gastos Pessoais Mensais"]}),e(Se,{children:"Quanto você precisa tirar da empresa para viver?"})]}),e(ee,{children:a("div",{className:"space-y-4",children:[e("div",{className:"bg-yellow-50 dark:bg-yellow-950/30 rounded-lg p-3 border border-yellow-200 dark:border-yellow-800 mb-4",children:a("p",{className:"text-sm text-yellow-800 dark:text-yellow-300 flex items-start gap-2",children:[e(ca,{className:"h-4 w-4 mt-0.5 shrink-0"}),a("span",{children:[e("strong",{children:"Por que perguntamos isso?"}),' Para calcular seu pró-labore ideal (o "salário" que você deve retirar da empresa). Seja honesto, isso é confidencial!']})]})}),N.map((p,oe)=>a("div",{className:"flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg border border-gray-200 dark:border-gray-700",children:[e("div",{className:"flex-1",children:e(be,{className:"text-sm font-medium",children:p.category})}),e("div",{className:"w-40",children:e(Ce,{type:"number",placeholder:"R$ 0,00",value:p.amount||"",onChange:he=>{const ye=[...N];ye[oe].amount=parseFloat(he.target.value)||0,C(ye)},className:"text-right"})})]},oe)),e(He,{}),a("div",{className:"flex items-center justify-between p-4 bg-green-50 dark:bg-green-950/30 rounded-lg border border-green-200 dark:border-green-800",children:[e("span",{className:"font-semibold text-green-900 dark:text-green-200",children:"Total de Gastos Pessoais/Mês:"}),e("span",{className:"text-xl font-bold text-green-600 dark:text-green-400",children:ve(P)})]})]})})]});case"labor-cost":return a(K,{children:[a(te,{children:[a(ne,{className:"flex items-center gap-2",children:[e(sa,{className:"h-6 w-6 text-indigo-500"}),"Calcular seu Custo/Hora"]}),e(Se,{children:"Descubra quanto custa cada hora do seu trabalho (importante para precificação!)"})]}),e(ee,{children:a("div",{className:"space-y-6",children:[a("div",{className:"bg-indigo-50 dark:bg-indigo-950/30 rounded-lg p-4 border-2 border-indigo-200 dark:border-indigo-800",children:[a("div",{className:"flex items-center gap-2 mb-2",children:[e(Me,{className:"h-5 w-5 text-indigo-600 dark:text-indigo-400"}),e("h4",{className:"font-semibold text-indigo-900 dark:text-indigo-200",children:"Por que calcular isso?"})]}),a("p",{className:"text-sm text-indigo-800 dark:text-indigo-300",children:["Saber quanto custa cada hora do SEU trabalho é essencial para precificar serviços corretamente. Vamos calcular: ",e("strong",{children:"Gastos Pessoais ÷ Horas Trabalhadas"})]})]}),a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"space-y-2",children:[e(be,{children:"Horas trabalhadas por dia"}),e(Ce,{type:"number",placeholder:"8",value:A.hoursPerDay||"",onChange:p=>f({...A,hoursPerDay:parseFloat(p.target.value)||0}),className:"text-lg text-center"}),e("p",{className:"text-xs text-gray-500",children:"Normalmente 6-10 horas/dia"})]}),a("div",{className:"space-y-2",children:[e(be,{children:"Dias trabalhados por mês"}),e(Ce,{type:"number",placeholder:"20",value:A.daysPerMonth||"",onChange:p=>f({...A,daysPerMonth:parseFloat(p.target.value)||0}),className:"text-lg text-center"}),e("p",{className:"text-xs text-gray-500",children:"Normalmente 20-22 dias/mês"})]})]}),e(He,{}),e("div",{className:"bg-gradient-to-br from-indigo-50 to-purple-50 dark:from-indigo-950/30 dark:to-purple-950/30 rounded-xl p-6 border-2 border-indigo-200 dark:border-indigo-800",children:a("div",{className:"text-center space-y-3",children:[a("div",{className:"flex items-center justify-center gap-2 mb-2",children:[e(Ga,{className:"h-6 w-6 text-indigo-600"}),e("h3",{className:"font-semibold text-indigo-900 text-lg",children:"Seu Custo/Hora"})]}),a("div",{className:"bg-white dark:bg-gray-800 rounded-lg p-4 border border-indigo-300 dark:border-indigo-700",children:[e("p",{className:"text-sm text-gray-600 dark:text-gray-400 mb-1",children:"Total de horas mensais"}),a("p",{className:"text-2xl font-bold text-gray-800 dark:text-gray-100",children:[H," horas/mês"]})]}),a("div",{className:"bg-white dark:bg-gray-800 rounded-lg p-4 border-2 border-indigo-400 dark:border-indigo-600",children:[e("p",{className:"text-sm text-gray-600 dark:text-gray-400 mb-1",children:"Custo por hora do seu trabalho"}),a("p",{className:"text-4xl font-bold text-indigo-600",children:[ve(I),"/h"]})]}),a("p",{className:"text-sm text-indigo-700 dark:text-indigo-300 mt-3 flex items-center gap-1",children:[e(ca,{className:"h-4 w-4 shrink-0"})," Ao precificar serviços, considere este valor como MÃNIMO para cobrir seus custos pessoais!"]})]})}),I>0&&I<15&&e("div",{className:"bg-yellow-50 dark:bg-yellow-950/30 rounded-lg p-3 border border-yellow-300 dark:border-yellow-700",children:a("div",{className:"flex items-center gap-2",children:[e(Me,{className:"h-5 w-5 text-yellow-600 dark:text-yellow-400"}),a("p",{className:"text-sm text-yellow-800 dark:text-yellow-300",children:[e("strong",{children:"Atenção:"})," Seu custo/hora está abaixo de R$ 15/h (equivalente ao salário mÃnimo). Considere aumentar suas horas trabalhadas ou revisar seus gastos pessoais."]})]})}),P>0&&((Q=N.find(p=>p.category.includes("Outros")))==null?void 0:Q.amount)===0&&e("div",{className:"bg-blue-50 dark:bg-blue-950/30 rounded-lg p-3 border border-blue-300 dark:border-blue-700",children:a("div",{className:"flex items-center gap-2",children:[e(ca,{className:"h-5 w-5 text-blue-600 dar
759k:text-blue-400"}),a("p",{className:"text-sm text-blue-800 dark:text-blue-300",children:[e("strong",{children:"Dica:"})," Considere reservar 10-15% dos seus ganhos para poupança/investimentos!"]})]})})]})})]});case"prolabore":return a(K,{children:[a(te,{children:[a(ne,{className:"flex items-center gap-2",children:[e(Ga,{className:"h-6 w-6 text-emerald-500"}),"Definir Pró-labore"]}),e(Se,{children:'Quanto você vai retirar mensalmente da empresa como "salário"'})]}),e(ee,{children:a("div",{className:"space-y-4",children:[a("div",{className:"bg-emerald-50 dark:bg-emerald-950/30 rounded-lg p-4 border-2 border-emerald-200 dark:border-emerald-800",children:[a("div",{className:"flex items-center gap-3 mb-3",children:[e(Oe,{className:"h-6 w-6 text-emerald-600 dark:text-emerald-400"}),e("h3",{className:"font-semibold text-emerald-900 dark:text-emerald-200",children:"Pró-labore Sugerido"})]}),a("p",{className:"text-sm text-emerald-800 dark:text-emerald-300 mb-3",children:["Com base nos seus gastos pessoais (",ve(P),"), recomendamos um pró-labore de ",e("strong",{children:"+20% de margem de segurança"}),":"]}),a("div",{className:"text-center p-4 bg-white dark:bg-gray-800 rounded-lg border border-emerald-300 dark:border-emerald-700",children:[e("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Pró-labore Sugerido"}),e("p",{className:"text-3xl font-bold text-emerald-600 dark:text-emerald-400",children:ve(U)}),a("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:["(",ve(P)," + 20% de margem)"]})]})]}),e(He,{}),a("div",{children:[e(be,{className:"text-sm font-medium mb-2 block",children:"Definir Pró-labore Mensal (você pode alterar):"}),e(Ce,{type:"number",placeholder:"R$ 0,00",value:$||"",onChange:p=>S(parseFloat(p.target.value)||0),className:"text-right text-xl font-semibold"}),e("p",{className:"text-xs text-gray-500 mt-1",children:"Deixe 0 se não quiser configurar agora"})]}),e("div",{className:"bg-blue-50 dark:bg-blue-950/30 rounded-lg p-3 border border-blue-200 dark:border-blue-800",children:a("p",{className:"text-sm text-blue-800 dark:text-blue-300 flex items-start gap-2",children:[e(ca,{className:"h-4 w-4 mt-0.5 shrink-0"}),a("span",{children:[e("strong",{children:"Dica:"}),' O pró-labore é um custo fixo da empresa. Mesmo que você seja o dono, precisa "se pagar" para saber se o negócio é viável!']})]})}),Z>0&&a("div",{className:"bg-indigo-50 dark:bg-indigo-950/30 rounded-lg p-3 border border-indigo-200 dark:border-indigo-800",children:[a("div",{className:"flex items-center gap-2 mb-2",children:[e(Aa,{className:"h-4 w-4 text-indigo-600 dark:text-indigo-400"}),e("p",{className:"text-sm font-semibold text-indigo-900 dark:text-indigo-200",children:"Funcionários Cadastrados"})]}),a("p",{className:"text-sm text-indigo-800 dark:text-indigo-300",children:["Encontramos ",a("strong",{children:[ve(Z),"/mês"]})," em salários de funcionários. Vamos importar automaticamente para os custos fixos!"]})]})]})})]});case"summary":return a(K,{className:"border-2 border-green-200 dark:border-green-800 bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-950/30 dark:to-emerald-950/30",children:[a(te,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e("div",{className:"h-20 w-20 rounded-full bg-green-500 flex items-center justify-center",children:e($e,{className:"h-10 w-10 text-white"})})}),e(ne,{className:"text-3xl",children:"Resumo Completo da Configuração"}),e(Se,{className:"text-base mt-2",children:"Todos os custos da sua empresa mapeados!"})]}),e(ee,{children:a("div",{className:"space-y-4",children:[a("div",{className:"bg-white dark:bg-card/80 rounded-lg p-4 border border-gray-200 dark:border-gray-700",children:[a("div",{className:"flex items-center justify-between mb-2",children:[a("h3",{className:"font-semibold flex items-center gap-2",children:[e(za,{className:"h-4 w-4 text-blue-500"}),"Custos Fixos DA EMPRESA"]}),e(ae,{variant:"outline",children:ve(we)})]}),e("ul",{className:"text-sm text-gray-600 dark:text-gray-400 space-y-1",children:g.filter(p=>p.amount>0).map((p,oe)=>a("li",{children:[p.name,": ",ve(p.amount)]},oe))})]}),a("div",{className:"bg-white dark:bg-card/80 rounded-lg p-4 border border-gray-200 dark:border-gray-700",children:[a("div",{className:"flex items-center justify-between mb-2",children:[a("h3",{className:"font-semibold flex items-center gap-2",children:[e(va,{className:"h-4 w-4 text-orange-500"}),"Custos Variáveis DA EMPRESA (Estimativa)"]}),e(ae,{variant:"outline",children:ve(w)})]}),e("ul",{className:"text-sm text-gray-600 dark:text-gray-400 space-y-1",children:y.filter(p=>p.amount>0).map((p,oe)=>a("li",{children:[p.name,": ",ve(p.amount)]},oe))})]}),O>0&&a("div",{className:"bg-white dark:bg-card/80 rounded-lg p-4 border border-gray-200 dark:border-gray-700",children:[a("div",{className:"flex items-center justify-between mb-2",children:[a("h3",{className:"font-semibold flex items-center gap-2",children:[e(Oe,{className:"h-4 w-4 text-pink-500"}),"Despesas Variáveis EXTRAS (Comissões, Ads, Taxas)"]}),e(ae,{variant:"outline",children:ve(O)})]}),e("ul",{className:"text-sm text-gray-600 dark:text-gray-400 space-y-1",children:E.filter(p=>p.amount>0).map((p,oe)=>a("li",{children:[p.name,": ",ve(p.amount)]},oe))})]}),a("div",{className:"bg-white dark:bg-card/80 rounded-lg p-4 border border-gray-200 dark:border-gray-700",children:[a("div",{className:"flex items-center justify-between mb-2",children:[a("h3",{className:"font-semibold flex items-center gap-2",children:[e(Ba,{className:"h-4 w-4 text-purple-500"}),"Assinaturas DA EMPRESA"]}),e(ae,{variant:"outline",children:ve(Y)})]}),Y>0&&a("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:[Object.values(c).filter(p=>p>0).length," assinaturas ativas"]})]}),Z>0&&e("div",{className:"bg-white dark:bg-card/80 rounded-lg p-4 border border-gray-200 dark:border-gray-700",children:a("div",{className:"flex items-center justify-between mb-2",children:[a("h3",{className:"font-semibold flex items-center gap-2",children:[e(Aa,{className:"h-4 w-4 text-indigo-500"}),"Folha de Pagamento"]}),e(ae,{variant:"outline",children:ve(Z)})]})}),I>0&&a("div",{className:"bg-gradient-to-r from-indigo-50 to-purple-50 dark:from-indigo-950/30 dark:to-purple-950/30 rounded-lg p-4 border border-indigo-200 dark:border-indigo-800",children:[a("div",{className:"flex items-center justify-between mb-2",children:[a("h3",{className:"font-semibold flex items-center gap-2",children:[e(sa,{className:"h-4 w-4 text-indigo-500"}
759),"Seu Custo/Hora"]}),a(ae,{className:"bg-indigo-500",children:[ve(I),"/h"]})]}),a("p",{className:"text-xs text-indigo-700 dark:text-indigo-300",children:[H,"h/mês (",A.hoursPerDay,"h/dia à ",A.daysPerMonth," dias)"]})]}),a("div",{className:"bg-green-50 dark:bg-green-950/30 rounded-lg p-4 border border-green-200 dark:border-green-800",children:[a("div",{className:"flex items-center justify-between mb-2",children:[a("h3",{className:"font-semibold flex items-center gap-2",children:[e(at,{className:"h-4 w-4 text-green-500"}),"Seus Gastos Pessoais/Mês"]}),e(ae,{variant:"outline",className:"bg-white dark:bg-card",children:ve(P)})]}),e("p",{className:"text-xs text-green-700 dark:text-green-400",children:"Base para cálculo do pró-labore"})]}),$>0&&a("div",{className:"bg-emerald-50 dark:bg-emerald-950/30 rounded-lg p-4 border-2 border-emerald-300 dark:border-emerald-700",children:[a("div",{className:"flex items-center justify-between mb-2",children:[a("h3",{className:"font-semibold flex items-center gap-2",children:[e(aa,{className:"h-4 w-4 text-emerald-500"}),"Pró-labore Definido"]}),e(ae,{className:"bg-emerald-500",children:ve($)})]}),e("p",{className:"text-xs text-emerald-700 dark:text-emerald-400",children:"Retirada mensal do sócio"})]}),e(He,{}),a("div",{className:"bg-gradient-to-r from-blue-500 to-emerald-500 rounded-lg p-4 text-white",children:[a("div",{className:"flex items-center justify-between mb-2",children:[e("span",{className:"font-bold text-lg",children:"Custo Operacional Total/Mês:"}),e("span",{className:"text-2xl font-bold",children:ve(we+w+O+Y+Z+$)})]}),a("p",{className:"text-sm mt-2 opacity-90 flex items-center gap-1",children:[e(ca,{className:"h-4 w-4 shrink-0"})," Sua empresa precisa faturar mais que isso para ter lucro!"]}),a("div",{className:"mt-3 pt-3 border-t border-white/30 text-xs space-y-1",children:[a("p",{children:["⢠Fixos: ",ve(we)," | Variáveis: ",ve(w+O)]}),a("p",{children:["⢠Assinaturas: ",ve(Y)," | Folha: ",ve(Z+$)]})]})]}),a("div",{className:"bg-yellow-50 dark:bg-yellow-950/30 rounded-lg p-4 border border-yellow-300 dark:border-yellow-700",children:[a("div",{className:"flex items-center gap-2 mb-2",children:[e(
759oa,{className:"h-5 w-5 text-yellow-600 dark:text-yellow-400"}),e("h4",{className:"font-semibold text-yellow-900 dark:text-yellow-200",children:"Próximos Passos"})]}),a("ul",{className:"text-sm text-yellow-800 dark:text-yellow-300 space-y-1 ml-4 list-disc",children:[e("li",{children:"Esses dados serão salvos para análise financeira futura"}),a("li",{children:["Use o custo/hora (",ve(I),"/h) para precificar serviços"]}),e("li",{children:"Revise esses custos mensalmente para manter a precisão"})]})]})]})})]});default:return null}};return a("div",{className:"max-w-3xl mx-auto space-y-6",children:[a("div",{className:"bg-white dark:bg-card rounded-lg border border-gray-200 dark:border-gray-700 p-4",children:[a("div",{className:"flex items-center justify-between mb-2",children:[e("span",{className:"text-sm font-medium",children:"Progresso"}),a("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:["Etapa ",W+1," de ",F.length]})]}),e("div",{className:"h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden",children:e("div",{className:"h-full bg-gradient-to-r from-blue-500 to-emerald-500 transition-all duration-300",style:{width:`${(W+1)/F.length*100}%`}})})]}),ke(),a("div",{className:"flex items-center justify-between",children:[a(j,{variant:"outline",onClick:re,disabled:W===0,children:[e(ns,{className:"h-4 w-4 mr-2"}),"Voltar"]}),r==="summary"?a(j,{onClick:k,disabled:n,className:"bg-gradient-to-r from-blue-500 to-emerald-500 hover:from-blue-600 hover:to-emerald-600",children:[n?"Salvando...":"Finalizar Configuração",e($e,{className:"h-4 w-4 ml-2"})]}):a(j,{onClick:D,children:["Próximo",e(Er,{className:"h-4 w-4 ml-2"})]})]}),e(Ea,{open:m,onOpenChange:u,children:a(Sa,{className:"sm:max-w-md",children:[a(Pa,{children:[e("div",{className:"flex justify-center mb-4",children:e("div",{className:"h-16 w-16 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center",children:e($e,{className:"h-10 w-10 text-green-600 dark:text-green-400"})})}
759),a(Ma,{className:"text-center text-2xl",children:[e(oa,{className:"h-5 w-5 inline mr-2 text-green-500"}),"Configuração ConcluÃda!"]}),a("div",{className:"text-center space-y-3 pt-4",children:[a("p",{className:"text-base font-medium text-gray-900 dark:text-gray-100",children:[i," contas a pagar foram criadas com sucesso!"]}),e("div",{className:"bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-800 rounded-lg p-4 space-y-2",children:a("div",{className:"flex items-start gap-2",children:[e(Me,{className:"h-5 w-5 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0"}),a("div",{className:"text-left",children:[e("p",{className:"text-sm font-medium text-blue-900 dark:text-blue-200",children:"Próximos Passos:"}),a("ul",{className:"text-sm text-blue-800 dark:text-blue-300 mt-2 space-y-1",children:[a("li",{className:"flex items-center gap-2",children:[e(Tr,{className:"h-4 w-4 shrink-0"})," Vá para a aba ",e("strong",{children:"âA Pagarâ"})]}),a("li",{className:"flex items-center gap-2",children:[e(je,{className:"h-4 w-4 shrink-0"})," Edite as ",e("strong",{children:"datas de vencimento"})," de cada conta"]}),a("li",{className:"flex items-center gap-2",children:[e(it,{className:"h-4 w-4 shrink-0"})," Faça ",e("strong",{children:"ajustes finos"})," nos valores, se necessário"]}),a("li",{className:"flex items-center gap-2",children:[e(qr,{className:"h-4 w-4 shrink-0"})," Configure suas ",e("strong",{children:"contas bancárias"})," para controle"]})]})]})]})})]})]}),e(Tt,{className:"sm:justify-center",children:e(j,{onClick:()=>{u(!1),t==null||t()},className:"bg-gradient-to-r from-blue-500 to-emerald-500 hover:from-blue-600 hover:to-emerald-600 w-full sm:w-auto",children:'Entendi, ir para "A Pagar"'})})]})})]})}function Do({variant:t="inline",className:r}){const[s,n]=_.useState(!1);return a(Ee,{children:[e(j,{onClick:()=>n(!0),className:_e(t==="floating"&&"fixed bottom-6 right-6 h-14 w-14 rounded-full shadow-lg hover:shadow-xl transition-all z-50",t==="inline"&&"w-full",r),size:t==="floating"?"icon":"default",children:t==="floating"?e(lt,{className:"h-6 w-6"}):a(Ee,{children:[e(lt,{className:"h-4 w-4 mr-2"}),"Assistente Financeiro"]})}),e(Ea,{open:s,onOpenChange:n,children:a(Sa,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[a(Pa,{children:[a(Ma,{className:"flex items-center gap-2",children:[e(
759oa,{className:"h-5 w-5 text-purple-500"}),"Assistente de Configuração Financeira"]}),e(Oa,{children:"Configure custos fixos, variáveis, assinaturas e calcule seu pró-labore ideal"})]}),e(Ro,{onComplete:()=>{n(!1)}})]})})]})}const es=[{id:"dashboard",title:"Visão Geral (Dashboard)",subtitle:"Resumo rápido do mês",whatItDoes:["Mostra quanto você vendeu, quanto já pagou de contas e o que ainda falta pagar.","Exibe clientes que devem dinheiro (fiado) e uma nota de âsaúdeâ do negócio (0 a 100).","Separa dinheiro no caixa fÃsico (PDV) e saldo nas contas bancárias cadastradas."],dataFrom:["Vendas do PDV â tabela sales","Contas cadastradas em Contas a Pagar â accounts_payable","Quem deve â saldo dos clientes (customers.balance)","Caixa fÃsico â cash_register","Bancos â bank_accounts (se você cadastrou contas)"],whatYouNeed:["Registrar vendas no PDV.","Cadastrar e marcar contas como pagas nas datas corretas."],tips:["Confira aqui todo dia: contas vencidas aparecem em destaque vermelho.","âProjeção de caixaâ = saldo do caixa menos o que ainda falta pagar no mês."],helpCenterSection:{category:"financial",section:"financial-overview"}},{id:"payable",title:"Contas a Pagar",subtitle:"Tudo que sua empresa precisa pagar",whatItDoes:["Cadastra aluguel, energia, fornecedores, salários, parcelas e contas mensais.","Ao marcar como pago, registra data, valor e (opcional) de qual conta bancária saiu o dinheiro.","Despesas com âIncluir nos custosâ entram na precificação de produtos."],dataFrom:["Você preenche manualmente â accounts_payable","Salários de funcionários podem vir do botão âSincronizar Saláriosâ","Pagamento com conta bancária atualiza o saldo em bank_accounts"],whatYouNeed:["Cadastrar cada despesa com vencimento e categoria.","Marcar como paga quando pagar de verdade.","Opcional: escolher a conta bancária no pagamento para controlar saldo."],tips:["Use parcelamento para compras divididas (ex.: 12x).","Contas mensais: tipo âMensalâ + dia do vencimento.","Anexe comprovante no pagamento para organização."],helpCenterSection:{category:"financial",section:"accounts-payable"}},{id:"receivable",title:"Contas a Receber",subtitle:"Quem te deve dinheiro",whatItDoes:["Lista clientes com saldo devedor (vendas no fiado ou pagamento parcial).","Permite registrar recebimento e abrir o histórico do cliente."],dataFrom:["Vendas a prazo / fiado no PDV â aumenta customers.balance","Recebimentos registrados â diminui o saldo"],whatYouNeed:["Vender no fiado ou registrar sinal no PDV ou na ficha do cliente.","Registrar quando o cliente pagar."],tips:["Priorize clientes com valores maiores ou mais tempo sem pagar.","O âagingâ usa data de cadastro do cliente como referência aproximada."],helpCenterSection:{category:"financial",section:"accounts-receivable"}},{id:"history",title:"Histórico de Pagamentos",subtitle:"O que já foi pago",whatItDoes:["Consulta contas já quitadas, com filtros por perÃodo e classificação de custo.","Serve para conferência â alterações aqui não recriam contas pendentes."],dataFrom:["accounts_payable com paid = true"],whatYouNeed:["Ter marcado contas como pagas em Contas a Pagar."],tips:["Use para conferir se um fornecedor já foi pago no mês."],helpCenterSection:{category:"financial",section:"payment-history-help"}},{id:"indicators",title:"Indicadores Financeiros",subtitle:"Saúde do negócio (plano PRO)",whatItDoes:["Calcula liquidez, rentabilidade, endividamento e capital de giro com base em vendas e contas.","Compara com referências do setor (conceitos SEBRAE)."],dataFrom:["sales, accounts_payable, bank_accounts, cash_register, customers, products (estoque)"],whatYouNeed:["Dados consistentes no mês selecionado no topo da página.","Custos nos produtos para CMV mais preciso."],tips:["Escolha o mês/ano ou perÃodo customizado no cabeçalho.","Modo âSimplesâ troca nomes técnicos por linguagem fácil."],helpCenterSection:{category:"financial",section:"financial-indicators"}},{id:"dre",title:"DRE â Lucro e PrejuÃzo",subtitle:"Demonstração de resultados (plano PRO)",whatItDoes:["Monta receita, custos, despesas e lucro do perÃodo em etapas profissionais.","Usa custo real da venda (order_items) quando existir; senão estima pelo cadastro do produto."],dataFrom:["Receita: sales (data da venda)","CMV: order_items.unit_cost ou custos do produto","Despesas: accounts_payable por competência + fixed_costs + prolabore_partners"],whatYouNeed:["Vendas registradas e contas com vencimento/competência no perÃodo.","Categorizar despesas ao cadastrar."],tips:["Ajuste o % de impostos em Ponto de EquilÃbrio â Configurar Impostos (vale também para a DRE).","Despesas entram pelo mês de competência, não só quando pagas."],helpCenterSection:{category:"financial",section:"dre-report"}},{id:"breakeven",title:"Ponto de EquilÃbrio",subtitle:"Quanto precisa vender para empatar (plano PRO)",whatItDoes:["Calcula quanto faturar para cobrir custos fixos, margem de segurança e cenários."],dataFrom:["Mesmas fontes da DRE + volume de vendas do perÃodo"],whatYouNeed:["Custos fixos cadastrados e margem de contribuição das vendas."],tips:["Se o PE parecer alto, revise custos fixos e preços de venda."],helpCenterSection:{category:"financial",section:"break-even-analysis"}},{id:"ai-analysis",title:"Análise com IA",subtitle:"Resumo inteligente (plano PRO)",whatItDoes:["Gera insights automáticos sobre fluxo, contas e tendências do perÃodo."],dataFrom:["Agrega dados do dashboard, contas e vendas"],whatYouNeed:["Ter dados preenchidos nas outras abas primeiro."],tips:["Use como segunda opinião â confira números no Dashboard e na DRE."],helpCenterSection:{category:"financial",section:"ai-financial-analysis"}},{id:"banks",title:"Contas Bancárias",subtitle:"Cadastro de bancos e caixas",whatItDoes:["Cadastra cada conta (corrente, poupança, caixa interno).","Saldo é recalculado quando você paga contas informando a conta ou importa extrato.","Permite transferências entre contas (se configurado)."],dataFrom:["bank_accounts â saldo inicial + movimentações vinculadas","financial_transfers â transferências entre contas"],whatYouNeed:["Informar saldo inicial ao criar a conta.","Ao pagar contas, escolher âPago com qual conta?â"],tips:["Marque uma conta como principal para vincular vendas do PDV automaticamente.","Use âAtualizar saldoâ se algo não bater após vários lançamentos."],helpCenterSection:{category:"financial",section:"bank-accounts"}},{id:"import",title:"Importar Extrato",subtitle:"OFX, CSV ou Excel",whatItDoes:["Lê o extrato do banco e cria lançamentos já pagos na conta selecionada.","Entradas viram receita; saÃdas viram despesa â o saldo da conta é atualizado.","Ignora duplicatas que já existem no PDV ou no caixa."],dataFrom:["Arquivo que você envia â accounts_payable + bank_statement_imports"],whatYouNeed:["Ter cadastrado a conta bancária antes.","Baixar extrato em OFX (recomendado) ou CSV do seu banco."],tips:["Revise a pré-visualização antes de confirmar.","PDF ainda não é suportado â use OFX ou CSV.","Transferências entre suas contas podem ser marcadas como internas."],helpCenterSection:{category:"financial",section:"bank-accounts"}}],$o=["Vender no PDV (registra receita automaticamente)","Cadastrar c
759ontas fixas em Contas a Pagar com âIncluir nos custosâ","Marcar contas como pagas na data real do pagamento","Opcional: cadastrar bancos e informar a conta ao pagar ou importar extrato","Plano PRO: conferir DRE e Indicadores no fim do mês"];function Fo(t){return es.find(r=>r.id===t)}function Io({open:t,onOpenChange:r,activeTab:s}){const n=is(),o=Ut(),m=_.useMemo(()=>Fo(s),[s]),u=()=>{if(m!=null&&m.helpCenterSection){const{category:i,section:d}=m.helpCenterSection;n(`/help?category=${i}§ion=${d}`)}else n("/help?category=financial");r(!1)};return e(Ks,{open:t,onOpenChange:r,children:a(Zs,{className:"w-full sm:max-w-lg flex flex-col p-0",children:[a(en,{className:"px-6 pt-6 pb-2",children:[a(an,{className:"flex items-center gap-2 text-lg",children:[e(Vr,{className:"h-5 w-5 text-primary"}),"Ajuda â Financeiro"]}),e(tn,{children:o.t("Guia por aba: o que faz, de onde vêm os dados e o que preencher","Explicação simples de cada parte do seu dinheiro")})]}),e(Sr,{className:"flex-1 px-6",children:a("div",{className:"space-y-6 pb-8",children:[m?a("section",{className:"space-y-3",children:[a("div",{children:[e(ae,{variant:"secondary",className:"mb-2",children:"Aba atual"}),e("h3",{className:"font-semibold text-base",children:m.title}),e("p",{className:"text-sm text-muted-foreground",children:m.subtitle})]}),e(Za,{icon:yn,title:"O que esta aba faz",items:m.whatItDoes}),e(Za,{icon:rn,title:"De onde vêm os dados",items:m.dataFrom}),e(Za,{icon:$e,title:"O que você precisa preencher",items:m.whatYouNeed}),e(Za,{icon:ca,title:"Dicas",items:m.tips,variant:"tips"}),m.helpCenterSection&&a(j,{variant:"outline",size:"sm",className:"w-full",onClick:u,children:[e(sn,{className:"h-4 w-4 mr-2"}),"Ver guia completo na Central de Ajuda"]})]}):e("p",{className:"text-sm text-muted-foreground",children:"Selecione uma aba para ver a explicação especÃfica."}),e(He,{}),a("section",{className:"space-y-2",children:[a("h3",{className:"font-semibold text-sm flex items-center gap-2",children:[e($e,{className:"h-4 w-4 text-green-600"}),"Para o financeiro funcionar bem"]}),e("ol",{className:"list-decimal list-inside space-y-1.5 text-sm text-muted-foreground",children:$o.map((i,d)=>e("li",{children:i},d))})]}),e(He,{}),a("section",{className:"space-y-2",children:[e("h3",{className:"font-semibold text-sm",children:"Todas as abas"}),e("ul",{className:"space-y-2",children:es.map(i=>a("li",{className:`text-sm rounded-md border p-2 ${i.id===s?"border-primary bg-primary/5":"border-border"}`,children:[e("span",{className:"font-medium",children:i.title}),e("p",{className:"text-xs text-muted-foreground mt-0.5",children:i.subtitle})]},i.id))})]})]})}),e("div",{className:"px-6 py-4 border-t",children:e(j,{className:"w-full",variant:"secondary",onClick:()=>r(!1),children:"Fechar"})})]})})}function Za({icon:t,title:r,items:s,variant:n="default"}){return a("div",{className:n==="tips"?"rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50/50 dark:bg-amber-950/20 p-3":"space-y-1.5",children:[a("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e(t,{className:"h-3.5 w-3.5"}),r]}),e("ul",{className:"text-sm text-muted-foreground space-y-1 list-disc list-inside",children:s.map((o,m)=>e("li",{children:o},m))})]})}function Oo({accounts:t}){const{toast:r}=Wa(),[s,n]=_.useState([]),[o,m]=_.useState(!0),[u,i]=_.useState(!1),d=t.filter(h=>h.is_active),g=async()=>{try{m(!0);const[h,c,b]=await Promise.all([ln(d),cn(d),dn()]),N=[...h,...c];n(b.length>0?mn(N,b):N)}catch(h){console.error("Erro ao carregar roteamento:",h),r({title:"Erro",description:"Não foi possÃvel carregar o roteamento de pagamentos",variant:"destructive"})}finally{m(!1)}};_.useEffect(()=>{d.length>0?g():m(!1)},[t.length]);const x=(h,c,b)=>{n(N=>N.map(C=>C.source_type===h&&C.payment_method===c?{...C,bank_account_id:b}:C))},y=async()=>{try{i(!0),await un(s),r({title:"Roteamento salvo",description:"As movimentações passarão a usar estas contas"})}catch(h){console.error("Erro ao salvar roteamento:",h);const c=h instanceof Error?h.message:"Erro ao salvar";r({title:"Erro",description:c,variant:"destructive"})}finally{i(!1)}},M=s.filter(h=>h.source_type==="sale"),E=s.filter(h=>h.source_type!=="sale");return d.length===0?null:a(K,{className:"mt-6",children:[e(te,{children:a("div",{className:"flex items-start justify-between gap-4",children:[a("div",{children:[a(ne,{className:"flex items-center gap-2 text-lg",children:[e(pn,{className:"h-5 w-5"}),"Roteamento de movimentações"]}),e(Se,{className:"mt-1",children:"Defina em qual conta cada forma de pagamento entra. Vendas do PDV, OS e extensão seguem estas regras automaticamente."})]}),a(j,{onClick:y,disabled:u||o,children:[e(qr,{className:"h-4 w-4 mr-2"}),u?"Salvando...":"Salvar regras"]})]})}),a(ee,{className:"space-y-6",children:[a("div",{className:"flex gap-2 rounded-lg border border-blue-200 bg-blue-50 p-3 text-sm text-blue-900 dark:border-blue-900 dark:bg-blue-950/40 dark:text-blue-100",children:[e(Dt,{className:"h-4 w-4 shrink-0 mt-0.5"}),a("p",{children:["Escolha ",e("strong",{children:"Não receber"})," para formas que não entram no banco (ex.: dinheiro fÃsico). Enquanto não salvar regras aqui, vendas continuam indo para a conta principal."]})]}),o?e("p",{className:"text-sm text-muted-foreground",children:"Carregando regras..."}):a(Ee,{children:[a("div",{children:[e("h4",{className:"font-medium mb-3",children:"Vendas (PDV, OS, extensão)"}),e("div",{className:"grid gap-3 sm:grid-cols-2",children:nn.map(h=>{const c=M.find(b=>b.payment_method===h.value);return a("div",{className:"flex flex-col gap-1.5",children:[e(be,{className:"text-sm",children:h.label}),a(Ve,{value:pr(c==null?void 0:c.bank_account_id),onValueChange:b=>x("sale",h.value,gr(b)),children:[e(Le,{children:e(Be,{placeholder:"Selecione a conta"})}),a(ze,{children:[e(fe,{value:"__none__",children:e("span",{className:"text-muted-foreground",children:"Não receber no banco"})}),d.map(b=>a(fe,{value:b.id,children:[b.name,b.is_main&&" (Principal)"]},b.id))]})]})]},h.value)})})]}),a("div",{children:[e("h4",{className:"font-medium mb-1",children:"Sangrias e suprimentos de caixa"}),e("p",{className:"text-xs text-muted-foreground mb-3",children:"Conta padrão sugerida ao registrar movimentações manuais de caixa no financeiro."}),e("div",{className:"grid gap-3 sm:grid-cols-2",children:on.map(h=>{const c=E.find(b=>b.source_type===h.source&&b.payment_method===h.value);return a("div",{className:"flex flex-col gap-1.5",children:[e(be,{className:"text-sm",children:h.label}),a(Ve,{value:pr(c==null?void 0:c.bank_account_id),onValueChange:b=>x(h.source,h.value,gr(b)),children:[e(Le,{children:e(Be,{placeholder:"Selecione a conta"})}),a(ze,{children:[e(fe,{value:"__none__",children:e("span",{className:"text-muted-foreground",children:"Não movimentar banco"})}),d.map(b=>e(fe,{value:b.id,children:b.name},b.id))]})]})]},`${h.source}-${h.value}`)})})]}),e("div",{className:"flex flex-wrap gap-2 pt-2",children:d.map(h=>e(ae,{variant:"outline",style:{borderColor:h.color,color:h.color},children:h.name},h.id))})]})]})]})}const Pt=t=>new Intl.NumberFormat("pt-BR",{style:"currency",currency:"BRL"}).format(t);function To(){var f,$;const{toast:t}=Wa(),[r,s]=_.useState([]),[n,o]=_.useState(!0),[m,u]=_.useState(!1),[i,d]=_.useState(null),[g,x]=_.useState({name:"",account_type:"checking",bank_name:"",agency:"",account_number:"",initial_balance:0,is_main:!1,is_active:!0,color:"#3b82f6"}),y=async()=>{try{o(!0);const S=await Da.getBankAccounts();s(S)}catch(S){console.error("Erro ao carregar contas bancárias:",S),t({title:"Erro",description:"Não foi possÃvel carregar as contas bancárias",variant:"destructive"})}finally{o(!1)}};_.useEffect(()=>{y()},[]);const M=async()=>{try{if(!g.name||!g.bank_name){t({title:"Campos obrigatórios",description:"Preencha pelo menos o
759nome da conta e o banco",variant:"destructive"});return}i?(await Da.updateBankAccount(i.id,g),t({title:"Conta atualizada",description:"Conta bancária atualizada com sucesso"})):(await Da.createBankAccount(g),t({title:"Conta criada",description:"Nova conta bancária criada com sucesso"})),u(!1),b(),y()}catch(S){console.error("Erro ao salvar conta bancária:",S),t({title:"Erro",description:"Não foi possÃvel salvar a conta bancária",variant:"destructive"})}},E=S=>{d(S),x({name:S.name,account_type:S.account_type,bank_name:S.bank_name,agency:S.agency||"",account_number:S.account_number||"",initial_balance:S.initial_balance,is_main:S.is_main,is_active:S.is_active,color:S.color||"#3b82f6"}),u(!0)},h=async S=>{if(confirm("Tem certeza que deseja excluir esta conta? Esta ação não pode ser desfeita."))try{await Da.deleteBankAccount(S),t({title:"Conta excluÃda",description:"Conta bancária excluÃda com sucesso"}),y()}catch(Z){console.error("Erro ao excluir conta bancária:",Z);const z=Z instanceof Error?Z.message:"Não foi possÃvel excluir a conta bancária";t({title:"Erro ao excluir",description:z,variant:"destructive"})}},c=async S=>{try{await Da.refreshBankBalance(S),t({title:"Saldo atualizado",description:"Saldo recalculado com sucesso"}),y()}catch(Z){console.error("Erro ao atualizar saldo:",Z),t({title:"Erro",description:"Não foi possÃvel atualizar o saldo",variant:"destructive"})}},b=()=>{x({name:"",account_type:"checking",bank_name:"",agency:"",account_number:"",initial_balance:0,is_main:!1,is_active:!0,color:"#3b82f6"}),d(null)},N=r.filter(S=>S.is_active).reduce((S,Z)=>S+Number(Z.current_balance),0),C={checking:"Conta Corrente",savings:"Poupança",investment:"Investimento",cash:"Dinheiro em Espécie"},A={checking:ot,savings:Oe,investment:Oe,cash:ea};return a("div",{className:"space-y-4",children:[a("div",{className:"grid gap-4 md:grid-cols-3",children:[a(K,{children:[a(te,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e(ne,{className:"text-sm font-medium",children:"Saldo Total"}),e(ea,{className:"h-4 w-4 text-muted-foreground"})]}),a(ee,{children:[e("div",{className:"text-2xl font-bold",children:Pt(N)}),a("p",{className:"text-xs text-muted-foreground",children:[r.filter(S=>S.is_active).length," contas ativas"]})]})]}),a(K,{children:[a(te,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e(ne,{className:"text-sm font-medium",children:"Contas Totais"}),e(ot,{className:"h-4 w-4 text-muted-foreground"})]}),a(ee,{children:[e("div",{className:"text-2xl font-bold",children:r.length}),a("p",{className:"text-xs text-muted-foreground",children:[r.filter(S=>!S.is_active).length," inativas"]})]})]}),a(K,{children:[a(te,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e(ne,{className:"text-sm font-medium",children:"Conta Principal"}),e(Oe,{className:"h-4 w-4 text-muted-foreground"})]}),a(ee,{children:[e("div",{className:"text-2xl font-bold",children:Pt(((f=r.find(S=>S.is_main))==null?void 0:f.current_balance)||0)}),e("p",{className:"text-xs text-muted-foreground",children:(($=r.find(S=>S.is_main))==null?void 0:$.name)||"Nenhuma definida"})]})]})]}),a(K,{children:[e(te,{children:a("div",{className:"flex items-center justify-between",children:[a("div",{children:[a(ne,{className:"flex items-center gap-2",children:[e(ea,{className:"h-5 w-5"}),"Contas Bancárias"]}),e(Se,{children:"Gerencie suas contas bancárias e saldos"})]}),a(Ea,{open:m,onOpenChange:S=>{u(S),S||b()},children:[e(kr,{asChild:!0,children:a(j,{children:[e(ga,{className:"h-4 w-4 mr-2"}),"Nova Conta"]})}),a(Sa,{className:"max-w-2xl",children:[a(Pa,{children:[e(Ma,{children:i?"Editar Conta Bancária":"Nova Conta Bancária"}),e(Oa,{children:i?"Atualize as informações da conta bancária":"Cadastre uma nova conta bancária para gerenciar suas finanças"})]}),a("div",{className:"grid gap-4 py-4",children:[a("div",{className:"grid grid-cols-2 gap-4",children:[a("div",{className:"col-span-2 space-y-2",children:[e(be,{htmlFor:"name",children:"Nome da Conta *"}),e(Ce,{id:"name",placeholder:"Ex: Banco do Brasil - Principal",value:g.name,onChange:S=>x({...g,name:S.target.value})})]}),a("div",{className:"space-y-2",children:[e(be,{htmlFor:"bank_name",children:"Banco *"}),e(Ce,{id:"bank_name",placeholder:"Ex: Banco do Brasil",value:g.bank_name,onChange:S=>x({...g,bank_name:S.target.value})})]}),a("div",{className:"space-y-2",children:[e(be,{htmlFor:"account_type",children:"Tipo de Conta"}),a(Ve,{value:g.account_type,onValueChange:S=>x({...g,account_type:S}),children:[e(Le,{id:"account_type",children:e(Be,{})}),a(ze,{children:[e(fe,{value:"checking",children:"Conta Corrente"}),e(fe,{value:"savings",children:"Poupança"}),e(fe,{value:"investment",children:"Investimento"}),e(fe,{value:"cash",children:"Dinheiro em Espécie"})]})]})]}),a("div",{className:"space-y-2",children:[e(be,{htmlFor:"agency",children:"Agência"}),e(Ce,{id:"agency",placeholder:"0001",value:g.agency,onChange:S=>x({...g,agency:S.target.value})})]}),a("div",{className:"space-y-2",children:[e(be,{htmlFor:"account_number",children:"Número da Conta"}),e(Ce,{id:"account_number",placeholder:"12345-6",value:g.account_number,onChange:S=>x({...g,account_number:S.target.value})})]}),a("div",{className:"space-y-2",children:[e(be,{htmlFor:"initial_balance",children:"Saldo Inicial"}),e(Ce,{id:"initial_balance",type:"number",step:"0.01",placeholder:"0.00",value:g.initial_balance,onChange:S=>x({...g,initial_balance:parseFloat(S.target.value)||0})})]}),a("div",{className:"space-y-2",children:[e(be,{htmlFor:"is_main",children:"Conta Principal"}),a(Ve,{value:g.is_main?"true":"false",onValueChange:S=>x({...g,is_main:S==="true"}),children:[e(Le,{id:"is_main",children:e(Be,{})}),a(ze,{children:[e(fe,{value:"false",children:"Não"}),e(fe,{value:"true",children:"Sim"})]})]})]}),a("div",{className:"col-span-2 space-y-2",children:[e(be,{htmlFor:"is_active",children:"Status"}),a(Ve,{value:g.is_active?"true":"false",onValueChange:S=>x({...g,is_active:S==="true"}),children:[e(Le,{id:"is_active",children:e(Be,{})}),a(ze,{children:[e(fe,{value:"true",children:"Ativa"}),e(fe,{value:"false",children:"Inativa"})]})]})]})]}),e(j,{onClick:M,className:"w-full",children:i?"Atualizar Conta":"Criar Conta"})]})]})]})]})}),e(ee,{children:n?e("div",{className:"text-center py-8 text-muted-foreground",children:"Carregando contas..."}):r.length===0?a("div",{className:"text-center py-12",children:[e(ea,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e("h3",{className:"text-lg font-semibold mb-2",children:"Nenhuma conta cadastrada"}),e("p",{className:"text-sm text-muted-foreground mb-4",children:"Cadastre sua primeira conta bancária para começar a gerenciar suas finanças"}),a(j,{onClick:()=>u(!0),children:[e(ga,{className:"h-4 w-4 mr-2"}),"Nova Conta"]})]}):a(Vt,{children:[e(Lt,{children:a(_a,{children:[e(We,{children:"Conta"}),e(We,{children:"Banco"}),e(We,{children:"Tipo"}),e(We,{className:"text-right",children:"Saldo Atual"}),e(We,{children:"Status"}),e(We,{className:"text-right",children:"Ações"})]})}),e(Bt,{children:r.map(S=>{const Z=A[S.account_type];return a(_a,{children:[e(De,{children:a("div",{className:"flex items-center gap-2",children:[e(Z,{className:"h-4 w-4 text-muted-foreground"}),a("div",{children:[e("div",{className:"font-medium",children:S.name}),S.is_main&&e(ae,{variant:"secondary",className:"text-xs",children:"Principal"})]})]})}),a(De,{children:[e("div",{className:"text-sm",children:S.bank_name}),S.agency&&S.account_number&&a("div",{className:"text-xs text-muted-foreground",children:["Ag: ",S.agency," | Cc: ",S.account_number]})]}),e(De,{children:e(ae,{variant:"outline",children:C[S.account_type]})}),e(De,{className:"text-right",children:e("div",{className:`font-semibold ${S.current_balance>=0?"text-green-600":"text-red-600"}`,children:Pt(S.current_balance)})}),e(De,{children:S.is_active?a(ae,{variant:"default",className:"gap-1 bg-green-600",children:[e(Lr,{className:"h-3 w-3"}),"Ativa"]}):a(ae,{variant:"secondary",className:"gap-1",children:[e(Br,{className:"h-3 w-3"}),"Inativa"]})}),e(De,{className:"text-right",children:a("div",{className:"flex justify-end gap-2",children:[e(j,{size:"sm",variant:"ghost",onClick:()=>
759c(S.id),title:"Recalcular saldo",children:e(ha,{className:"h-4 w-4"})}),e(j,{size:"sm",variant:"ghost",onClick:()=>E(S),children:e(Tr,{className:"h-4 w-4"})}),e(j,{size:"sm",variant:"ghost",onClick:()=>h(S.id),className:"text-destructive hover:text-destructive",children:e(ya,{className:"h-4 w-4"})})]})})]},S.id)})})]})})]}),r.length>0&&e(Oo,{accounts:r})]})}const G={alert:{success:"border-green-200 bg-green-50 dark:border-green-800/80 dark:bg-green-950/45",successIcon:"text-green-600 dark:text-green-400",successDesc:"text-sm text-green-800 dark:text-green-200",successStrong:"[&_strong]:text-green-900 dark:[&_strong]:text-green-100",successList:"mt-2 space-y-1 text-xs text-green-800 dark:text-green-300",warning:"border-yellow-200 bg-yellow-50 dark:border-yellow-800/80 dark:bg-yellow-950/45",warningIcon:"text-yellow-600 dark:text-yellow-400",warningDesc:"text-sm text-yellow-800 dark:text-yellow-200",warningStrong:"[&_strong]:text-yellow-900 dark:[&_strong]:text-yellow-100",info:"border-blue-200 bg-blue-50 dark:border-blue-800/80 dark:bg-blue-950/45",infoIcon:"text-blue-600 dark:text-blue-400",infoDesc:"text-sm text-blue-800 dark:text-blue-200",infoStrong:"[&_strong]:text-blue-900 dark:[&_strong]:text-blue-100",infoList:"text-xs text-blue-800 dark:text-blue-300 space-y-1 ml-4",infoNested:"text-xs text-blue-700 dark:text-blue-300 mt-2 bg-blue-100 dark:bg-blue-950/60 p-2 rounded",danger:"border-red-200 bg-red-50 dark:border-red-800/80 dark:bg-red-950/45",dangerIcon:"text-red-600 dark:text-red-400",dangerDesc:"text-xs text-red-800 dark:text-red-200",dangerStrong:"[&_strong]:text-red-900 dark:[&_strong]:text-red-100",purple:"border-purple-200 bg-purple-50 dark:border-purple-800/80 dark:bg-purple-950/45",purpleIcon:"text-purple-600 dark:text-purple-400",purpleDesc:"text-xs text-purple-800 dark:text-purple-200",purpleStrong:"[&_strong]:text-purple-900 dark:[&_strong]:text-purple-100",warningNested:"text-xs text-yellow-700 dark:text-yellow-300 mt-2 bg-yellow-100 dark:bg-yellow-950/50 p-2 rounded border border-yellow-300 dark:border-yellow-800"},formatCard:{recommended:"p-4 rounded-lg border-2 bg-green-50 border-green-300 dark:bg-green-950/40 dark:border-green-800",default:"p-4 rounded-lg border-2 bg-muted/40 border-border",desc:"text-sm text-muted-foreground mb-3",ofxTitle:"font-medium text-green-900 dark:text-green-100",ofxList:"text-xs text-muted-foreground space-y-1 ml-4",ofxTip:"text-xs text-green-700 dark:text-green-300 mt-2 bg-green-100 dark:bg-green-950/60 p-2 rounded"},infoCard:"border-blue-200 bg-blue-50 dark:border-blue-800/80 dark:bg-blue-950/35",infoCardTitle:"text-lg flex items-center gap-2 text-blue-900 dark:text-blue-100",infoCardIcon:"h-5 w-5 text-blue-600 dark:text-blue-400",infoSectionTitle:"font-semibold text-blue-900 dark:text-blue-100 mb-1",infoSectionBody:"text-muted-foreground",infoList:"list-disc list-inside text-muted-foreground mt-1 ml-2 space-y-1",statCard:{neutralTitle:"text-sm text-muted-foreground",neutralValue:"text-2xl font-bold",subtext:"text-xs text-muted-foreground",green:"border-green-200 dark:border-green-800/80",red:"border-red-200 dark:border-red-800/80",yellow:"border-yellow-200 dark:border-yellow-800/80",titleGreen:"text-sm text-green-600 dark:text-green-400",titleRed:"text-sm text-red-600 dark:text-red-400",titleYellow:"text-sm text-yellow-600 dark:text-yellow-400",valueGreen:"text-2xl font-bold text-green-600 dark:text-green-400",valueRed:"text-2xl font-bold text-red-600 dark:text-red-400",valueYellow:"text-2xl font-bold text-yellow-600 dark:text-yellow-400"},txnRow:{excluded:"bg-muted/80 border-border opacity-40",internal:"bg-yellow-50 border-yellow-200 dark:bg-yellow-950/40 dark:border-yellow-800/80",credit:"bg-green-50 border-green-200 dark:bg-green-950/40 dark:border-green-800/80",debit:"bg-red-50 border-red-200 dark:bg-red-950/40 dark:border-red-800/80",internalLabel:"text-yellow-600 dark:text-yellow-400",creditAmount:"text-green-600 dark:text-green-400",debitAmount:"text-red-600 dark:text-red-400",excludedAmount:"text-muted-foreground",excludedIcon:"text-muted-foreground",iconInternal:"text-yellow-600 dark:text-yellow-400",iconCredit:"text-green-600 dark:text-green-400",iconDebit:"text-red-600 dark:text-red-400",meta:"text-xs text-muted-foreground",excludedLabel:"text-muted-foreground"},paymentBadge:{pix:"bg-purple-100 text-purple-700 dark:bg-purple-950/60 dark:text-purple-300",boleto:"bg-orange-100 text-orange-700 dark:bg-orange-950/60 dark:text-orange-300",credit_card:"bg-blue-100 text-blue-700 dark:bg-blue-950/60 dark:text-blue-300",debit_card:"bg-cyan-100 text-cyan-700 dark:bg-cyan-950/60 dark:text-cyan-300",transfer:"bg-muted text-muted-foreground",default:"bg-muted text-muted-foreground"},completeIcon:"h-20 w-20 rounded-full bg-green-600 dark:bg-green-500 flex items-center justify-center",completeCard:"border-2 border-green-200 bg-gradient-to-br from-green-50 to-emerald-50 dark:border-green-800 dark:from-green-950/50 dark:to-emerald-950/30",completeInner:"bg-card rounded-lg p-4 border border-border inline-block",completeCount:"text-4xl font-bold text-green-600 dark:text-green-400",fileOk:"text-sm text-green-600 dark:text-green-400",noAccount:"text-xs text-yellow-600 dark:text-yellow-400 mt-1"},yr=[{value:"ofx",label:"OFX (Recomendado)",description:"Padrão bancário internacional - Maior precisão e confiabilidade",icon:da,recommended:!0},{value:"csv",label:"CSV (Planilha)",description:"Arquivo de texto - Pode variar entre bancos",icon:et},{value:"xlsx",label:"XLSX (Excel)",description:"Planilha Microsoft Excel - Boa compatibilidade",icon:Oe},{value:"pdf",label:"PDF (em desenvolvimento)",description:"Extração de dados de PDF ainda em testes",icon:Me,disabled:!0}];function qo(){const[t,r]=_.useState("ofx"),[s,n]=_.useState(""),[o,m]=_.useState([]),[u,i]=_.useState(null),[d,g]=_.useState(!1),[x,y]=_.useState([]),[M,E]=_.useState("upload"),[h,c]=_.useState(!1),[b,N]=_.useState(new Set),[C,A]=_.useState(1),f=100,$=async()=>{try{const{data:{user:w}}=await v.auth.getUser();if(!w)throw new Error("Usuário não autenticado");const{data:O,error:H}=await v.from("bank_accounts").select("id, name, bank_name, account_type, current_balance").eq("user_id",w.id).eq("is_active",!0).order("is_main",{ascending:!1}).order("name");if(H)throw H;m(O||[])}catch(w){console.error("Erro ao carregar contas bancárias:",w)}};_.useEffect(()=>{$()},[]);const S=async w=>{var I,U;const O=(I=w.target.files)==null?void 0:I[0];if(!O)return;i(O);const H=(U=O.name.split(".").pop())==null?void 0:U.toUpperCase();if(!["PDF","CSV","OFX","XLSX"].includes(H||"")){ue.error("Formato não suportado. Use PDF, CSV, OFX ou XLSX");return}ue.success(`Arquivo ${O.name} carregado`)},Z=w=>{const O=w.split(` 760`).filter(U=>U.trim()),H=[],I=O[0].toLowerCase();if(I.includes("date")&&I.includes("amount"))for(let U=1;U<O.length;U++){const se=O[U].split(",");if(se.length<4)continue;const le=parseFloat(se[3].replace(/[^\d.-]/g,""));H.push({date:se[0],description:se[2]||se[1],amount:Math.abs(le),type:le>0?"credit":"debit"})}else if(I.includes("data")&&I.includes("valor"))for(let U=1;U<O.length;U++){const se=O[U].split(";");if(se.length<3)continue;const le=parseFloat(se[2].replace(/[^\d.-]/g,""));H.push({date:se[0],description:se[1],amount:Math.abs(le),type:le>0?"credit":"debit",balance:se[3]?parseFloat(se[3].replace(/[^\d.-]/g,"")):void 0})}return H},z=async w=>new Promise((O,H)=>{const I=new FileReader;I.onload=U=>{var se;try{const le=new Uint8Array((se=U.target)==null?void 0:se.result),ce=gn(le,{type:"array"}
760),R=ce.Sheets[ce.SheetNames[0]],B=hn.sheet_to_json(R).map(F=>{const W=Math.abs(parseFloat(String(F.Valor||F.valor||"0"))),D=String(F.Tipo||F.tipo||"");return{date:String(F.Data||F.data||""),description:String(F.Descrição||F.descrição||F.Descricao||""),amount:W,type:D.toLowerCase().includes("recebido")||W>0?"credit":"debit"}});O(B)}catch(le){H(le)}},I.onerror=H,I.readAsArrayBuffer(w)}),X=w=>{var I;const O=[],H=w.match(/<STMTTRN>[\s\S]*?<\/STMTTRN>/g)||[];for(const U of H)try{const se=U.match(/<DTPOSTED>(\d{8,14})/);if(!se){console.warn(" Bloco sem DTPOSTED:",U.substring(0,100));continue}const le=se[1],ce=`${le.slice(0,4)}-${le.slice(4,6)}-${le.slice(6,8)}`,R=U.match(/<TRNAMT>([-\d.]+)/);if(!R){console.warn(" Bloco sem TRNAMT:",U.substring(0,100));continue}const pe=parseFloat(R[1]),B=Math.abs(pe),F=pe>0?"credit":"debit";let W="",D="";const re=U.match(/<NAME>(.*?)<\/NAME>/s),k=U.match(/<MEMO>(.*?)<\/MEMO>/s),ke=U.match(/<PAYEE>(.*?)<\/PAYEE>/s),Q=re&&re[1].trim()?re[1].trim():"",p=k&&k[1].trim()?k[1].trim():"",oe=ke&&ke[1].trim()?ke[1].trim():"";if(Q&&p&&p.toLowerCase()!=="recebido"&&p.toLowerCase()!=="enviado"&&p.toLowerCase()!==Q.toLowerCase())W=`${Q} - ${p}`,D="NAME+MEMO";else if(Q&&Q.length>10)W=Q,D="NAME";else if(p&&p.length>10)W=p,D="MEMO";else if(Q)W=Q,D="NAME";else if(p)W=p,D="MEMO";else if(oe)W=oe,D="PAYEE";else{const ge=U.match(/<CHECKNUM>(.*?)<\/CHECKNUM>/s);ge&&ge[1].trim()&&(W=`Cheque/Ref: ${ge[1].trim()}`,D="CHECKNUM")}if(!W){const ge=U.match(/<REFNUM>(.*?)<\/REFNUM>/s);ge&&ge[1].trim()&&(W=`Ref: ${ge[1].trim()}`,D="REFNUM")}if(!W){const ge=U.match(/<TRNTYPE>(.*?)<\/TRNTYPE>/);W=ge?ge[1]:"Transação sem descrição",D="TRNTYPE"}W=W.replace(/\s+/g," ").replace(/[\r\n\t]/g," ").trim(),O.length<3;const he=U.match(/<BALAMT>([-\d.]+)/),ye=he?parseFloat(he[1]):void 0;O.push({date:ce,description:W,amount:B,type:F,balance:ye})}catch(se){console.warn("Erro ao processar bloco OFX:",se,U);continue}if(O.length===0){const U=w.split(` 761`);let se={};for(const le of U)if(le.includes("<DTPOSTED>")){const ce=(I=le.match(/\d{8}/))==null?void 0:I[0];ce&&(se.date=`${ce.slice(0,4)}-${ce.slice(4,6)}-${ce.slice(6,8)}`)}else if(le.includes("<TRNAMT>")){const ce=parseFloat(le.replace(/<\/?TRNAMT>/g,""));se.amount=Math.abs(ce),se.type=ce>0?"credit":"debit"}else if(le.includes("<MEMO>")||le.includes("<NAME>")){const ce=le.replace(/<\/?MEMO>/g,"").replace(/<\/?NAME>/g,"").trim();ce&&(se.description=ce)}else le.includes("</STMTTRN>")&&(se.date&&se.amount&&se.description&&O.push(se),se={})}return O},me=w=>{const O=["transferencia","transf","ted","doc","transferência"],H=["pix enviado","pix recebido","pix","pagamento pix"],I=["boleto","pagamento de boleto","titulo","cobrança"],U=["fatura","cartao","cartão","fatura cartao","credito","crédito","débito","debito"],se=["debito automatico","débito automático","cobrança"],le=["vendas - deposito","vendas - depósito","vendas deposito","vendas depósito","deposito infinitepay","depósito infinitepay","repasse de vendas","repasse pagbank","liquidacao pagbank","liquidação pagbank","liquidacao de vendas","liquidação de vendas","repasse mercado pago","repasse mp","credito de vendas","crédito de vendas","repasse stone","liquidacao stone","credito rede","repasse rede","credito cielo","repasse cielo","repasse adquirente","liquidacao adquirente","credito adquirente","antecipacao de recebiveis","antecipação de recebÃveis"];return w.map(ce=>{const R=ce.description.toLowerCase(),pe=H.some(ge=>R.includes(ge)),B=I.some(ge=>R.includes(ge)),F=U.some(ge=>R.includes(ge)),W=se.some(ge=>R.includes(ge)),D=O.some(ge=>R.includes(ge)),re=le.some(ge=>R.includes(ge)),k=R.includes("vendas")||R.includes("venda"),ke=R.includes("deposito")||R.includes("depósito")||R.includes("repasse")||R.includes("liquidacao")||R.includes("liquidação")||R.includes("credito adquirente")||R.includes("crédito adquirente"),p=re||k&&ke,oe=D&&!pe&&!B&&!F||p;let he;pe?he="pix":B?he="boleto":F?R.includes("debito")||R.includes("débito")?he="debit_card":he="credit_card":W?he="debit_card":D||p?he="transfer":he=ce.type==="credit"?"pix":"transfer";let ye=B?"Boleto":F?"Cartão":pe?"PIX":D?"Transferência":"Outros";return p&&(ye="Depósito Vendas (D+1)"),{...ce,isInternalTransfer:oe,category:ye,paymentMethod:he}})},we=async()=>{var w;if(!u||!t||!s){ue.error("Selecione formato, conta e arquivo");return}g(!0);try{let O=[];const H=(w=u.name.split(".").pop())==null?void 0:w.toUpperCase();if(H==="CSV"){const I=await u.text();O=Z(I)}else if(H==="XLSX")O=await z(u);else if(H==="OFX"||H==="QFX"){const I=await u.text();if(I.trim().startsWith("{")||I.trim().startsWith("[")){ue.error("Arquivo JSON detectado. Baixe o extrato em formato OFX (não pela API/JSON)."),g(!1);return}if(!I.includes("<OFX>")&&!I.includes("<STMTTRN>")){ue.error("Arquivo OFX inválido. Certifique-se de baixar o formato correto do banco."),g(!1);return}O=X(I),O.length>0||console.warn(" Nenhuma transação encontrada no OFX. Verifique o formato do arquivo.")}else if(H==="PDF"){ue.error("Parser de PDF em desenvolvimento. Use CSV/OFX/XLSX por enquanto."),g(!1);return}if(O.length===0){ue.error("Nenhuma transação encontrada no arquivo. Verifique o formato."),g(!1);return}O=me(O),y(O),E("preview"),ue.success(`${O.length} transações encontradas`)}catch(O){console.error("Erro ao processar arquivo:",O),ue.error(`Erro ao processar arquivo: ${O instanceof Error?O.message:"Erro desconhecido"}`)}finally{g(!1)}},Y=async()=>{var w;g(!0);try{const{data:{user:O}}=await v.auth.getUser();if(!O)throw new Error("Usuário não autenticado");const H=x.filter((D,re)=>!(b.has(re)||!h&&D.isInternalTransfer));if(H.length===0){ue.error("Nenhuma transação selecionada para importar"),g(!1);return}const I=[...new Set(H.map(D=>D.date))],{data:U}=await v.from("sales").select("id, total_amount, payment_date, payment_method").eq("user_id",O.id).in("payment_date",I),{data:se}=await v.from("cash_register").select("id, amount, date, type, description").eq("user_id",O.id).in("date",I).eq("type","in"),le=H.map(D=>{const re=U==null?void 0:U.find(Q=>Q.payment_date===D.date&&Math.abs(parseFloat(Q.total_amount.toString())-D.amount)<.01&&D.type==="credit"),k=se==null?void 0:se.find(Q=>Q.date===D.date&&Math.abs(parseFloat(Q.amount.toString())-D.amount)<.01&&D.type==="credit");return{...D,isDuplicate:!!(re||k),duplicateSource:re?"Venda (PDV)":k?"Caixa":void 0,duplicateId:(re==null?void 0:re.id)||(k==null?void 0:k.id)}}),ce=le.filter(D=>!D.isDuplicate),R=le.length-ce.length;if(R>0){const D=le.filter(k=>k.isDuplicate),re=[...new Set(D.map(k=>k.duplicateSource))].join(", ");ue.warning(`${R} transação(ões) ignorada(s) - já em: ${re}`)}if(R>
7610&&ue.warning(`${R} transação(ões) ignorada(s) - já registrada(s) no PDV`),ce.length===0){ue.error("Todas as transações já foram importadas anteriormente"),g(!1);return}const{data:pe,error:B}=await v.from("bank_statement_imports").insert({user_id:O.id,bank_account_id:s,file_name:u==null?void 0:u.name,file_type:(w=u==null?void 0:u.name.split(".").pop())==null?void 0:w.toUpperCase(),bank_name:"Importação Manual",total_transactions:x.length,transactions_imported:ce.length,transactions_skipped:x.length-ce.length+R,status:"processing"}).select().single();if(B)throw B;const F=ce.map(D=>({user_id:O.id,description:D.description,amount:Math.abs(D.amount),due_date:D.date,paid:!0,payment_date:D.date,payment_method:D.paymentMethod||(D.type==="credit"?"pix":"transfer"),bank_account_id:s,account_type:D.type==="credit"?"revenue":"expense",cost_classification:D.type==="credit"?null:"despesa_variavel"})),{error:W}=await v.from("accounts_payable").insert(F);if(W)throw W;await v.rpc("update_bank_balance",{p_account_id:s}),await v.from("bank_statement_imports").update({status:"completed"}).eq("id",pe.id),E("complete"),ue.success(`${ce.length} transações importadas!`)}catch(O){console.error("Erro ao importar:",O),ue.error("Erro ao importar transações")}finally{g(!1)}},P={total:x.length,credits:x.filter(w=>w.type==="credit").length,debits:x.filter(w=>w.type==="debit").length,internal:x.filter(w=>w.isInternalTransfer).length,totalCredits:x.filter(w=>w.type==="credit").reduce((w,O)=>w+O.amount,0),totalDebits:x.filter(w=>w.type==="debit").reduce((w,O)=>w+O.amount,0)};return a("div",{className:"space-y-6",children:[M==="upload"&&a(Ee,{children:[a(K,{children:[a(te,{children:[a(ne,{className:"flex items-center gap-2",children:[e(qt,{className:_e("h-6 w-6",G.alert.infoIcon)}),"Importar Extrato Bancário"]}),e(Se,{children:"Importe transações de PDF, CSV, OFX ou XLSX dos principais bancos"})]}),a(ee,{className:"space-y-4",children:[a("div",{children:[e(be,{children:"Formato do Arquivo"}),a(Ve,{value:t,onValueChange:r,children:[e(Le,{children:e(Be,{placeholder:"Selecione o formato"})}),e(ze,{children:yr.map(w=>a(fe,{value:w.value,disabled:w.disabled,children:[a("span",{className:"inline-flex items-center gap-2",children:[e(w.icon,{className:"h-4 w-4"}),w.label]}),w.recommended&&e(ae,{variant:"default",className:"ml-2 text-xs",children:"Recomendado"})]},w.value))})]}),t==="ofx"&&a(Fe,{className:_e("mt-3",G.alert.success),children:[e($e,{className:_e("h-4 w-4",G.alert.successIcon)}),a(Ie,{className:_e(G.alert.successDesc,G.alert.successStrong),children:[e("strong",{children:"Por que OFX é o melhor formato?"}),a("ul",{className:G.alert.successList,children:[a("li",{children:["â ",e("strong",{children:"Padrão Internacional:"})," Criado especificamente para dados financeiros"]}),a("li",{children:["â ",e("strong",{children:"Máxima Precisão:"})," Campos padronizados (data, valor, descrição, saldo)"]}),a("li",{children:["â ",e("strong",{children:"Sem Ambiguidade:"}),' Formato estruturado em XML, não há "interpretação"']}),a("li",{children:["â ",e("strong",{children:"Todos os Bancos:"})," Suportado por 100% dos bancos brasileiros"]}),a("li",{children:["â ",e("strong",{children:"Histórico Completo:"})," Inclui saldo anterior e posterior de cada transação"]})]})]})]}),t==="csv"&&a(Fe,{className:_e("mt-3",G.alert.warning),children:[e(Me,{className:_e("h-4 w-4",G.alert.warningIcon)}),a(Ie,{className:_e(G.alert.warningDesc,G.alert.warningStrong),children:[e("strong",{children:"CSV:"})," Cada banco usa seu próprio formato. Revise o preview antes de importar."]})]}),t==="xlsx"&&a(Fe,{className:_e("mt-3",G.alert.info),children:[e(Me,{className:_e("h-4 w-4",G.alert.infoIcon)}),a(Ie,{className:_e(G.alert.infoDesc,G.alert.infoStrong),children:[e("strong",{children:"XLSX:"})," Boa compatibilidade, mas verifique se as colunas estão corretas."]})]})]}),a("div",{children:[a("div",{className:"flex items-center justify-between mb-2",children:[e(be,{children:"Conta Bancária"}),a(j,{type:"button",variant:"ghost",size:"sm",onClick:$,className:"h-7 px-2",children:[e(ha,{
761className:"h-3.5 w-3.5 mr-1"}),"Atualizar"]})]}),a(Ve,{value:s,onValueChange:n,children:[e(Le,{children:e(Be,{placeholder:"Selecione a conta"})}),e(ze,{children:o.map(w=>a(fe,{value:w.id,children:[w.name," ",w.bank_name&&`(${w.bank_name})`]},w.id))})]}),o.length===0&&e("p",{className:_e("text-xs mt-1",G.noAccount),children:"Nenhuma conta encontrada. Crie uma conta bancária primeiro."})]}),a("div",{children:[e(be,{children:"Arquivo do Extrato"}),e(Ce,{type:"file",accept:".pdf,.csv,.ofx,.xlsx,.xls",onChange:S,className:"cursor-pointer"}),u&&a("div",{className:_e("flex items-center gap-2 mt-2",G.fileOk),children:[e(da,{className:"h-4 w-4"}),e("span",{children:u.name})]})]}),a(Fe,{children:[e(Me,{className:"h-4 w-4"}),a(Ie,{className:"text-sm",children:[e("strong",{children:"Dica:"})," Transferências entre suas próprias contas serão detectadas e ignoradas automaticamente para evitar duplicação."]})]}),a(Fe,{className:G.alert.info,children:[e(sa,{className:_e("h-4 w-4",G.alert.infoIcon)}),e(Ie,{className:_e(G.alert.infoDesc,G.alert.infoStrong),children:a("div",{className:"space-y-2",children:[e("p",{className:"font-semibold",children:"Quando importar extratos?"}),a("ul",{className:G.alert.infoList,children:[a("li",{children:["⢠",e("strong",{children:"Mês Corrente:"})," Importe semanalmente ou a cada venda grande"]}),a("li",{children:["⢠",e("strong",{children:"Mês Anterior:"})," Importe no inÃcio do mês seguinte (1ª semana)"]}),a("li",{children:["⢠",e("strong",{children:"Conciliação:"})," Compare com DRE mensalmente"]})]}),a("p",{className:G.alert.infoNested,children:[e("strong",{children:"Anti-duplicação Inteligente:"})," Vendas registradas no PDV (PIX, Cartão, Transferência, Débito, Dinheiro) e movimentações do Caixa são automaticamente detectadas e ignoradas ao importar extrato â mesmo valor + mesma data = não duplica!"]}),a("p",{className:G.alert.warningNested,children:[e("strong",{children:"Bancos com Pagamento D+1:"}),' Depósitos de vendas do dia anterior (exemplo: "Vendas - Depósito", "Repasse de Vendas") são automaticamente detectados e marcados como transferência interna para não duplicar receitas já registradas no PDV.']})]})})]}),a(Fe,{className:G.alert.danger,children:[e(Me,{className:_e("h-4 w-4",G.alert.dangerIcon)}),a(Ie,{className:_e(G.alert.dangerDesc,G.alert.dangerStrong),children:[e("strong",{children:"Dica Importante:"})," Caso tenha erro na leitura do OFX, baixe o extrato ",e("strong",{children:"pelo site oficial do banco"}),' (Internet Banking) ao invés do aplicativo. Procure opção "Exportar â OFX" no menu do extrato.']})]}),e(j,{onClick:we,disabled:!u||!t||!s||d,className:"w-full",children:d?a(Ee,{children:[e(ba,{className:"h-4 w-4 mr-2 animate-spin"}),"Processando..."]}):a(Ee,{children:[e(da,{className:"h-4 w-4 mr-2"}),"Processar Arquivo"]})})]})]}),a(K,{children:[a(te,{children:[e(ne,{className:"text-lg",children:"Formatos Suportados e Como Baixar"}),e(Se,{children:"Aprenda a exportar o extrato do seu banco no formato correto"})]}),e(ee,{children:e("div",{className:"space-y-4",children:yr.filter(w=>!w.disabled).map(w=>e("div",{className:w.recommended?G.formatCard.recommended:G.formatCard.default,children:e("div",{className:"flex items-start justify-between",children:a("div",{className:"flex-1",children:[a("h3",{className:"font-semibold mb-1 flex items-center gap-2",children:[e(w.icon,{className:"h-4 w-4"})," ",w.label,w.recommended&&e(ae,{variant:"default",className:"bg-green-600 dark:bg-green-500",children:"Melhor Opção"})]}),e("p",{className:G.formatCard.desc,children:w.description}),w.value==="ofx"&&a("div",{className:"space-y-2 text-sm",children:[e("p",{className:G.formatCard.ofxTitle,children:"Como baixar OFX:"}),a("ul",{className:G.formatCard.ofxList,children:[a("li",{children:["⢠",e("strong",{children:"Nubank:"})," App â Relatórios â Extrato â Baixar OFX"]}),a("li",{children:["⢠",e("strong",{children:"Inter:"})," Internet Banking â Extrato â Exportar â OFX"]}),a("li",{children:["⢠",e("strong",{children:"Itaú:"})," iToken â Conta â Extrato â Baixar â OFX"]}),a("li",{children:["⢠",e("strong",{children:"Bradesco:"})," Internet Banking â Extrato â Exportar â Money (OFX)"]}),a("li",{children:["⢠",e("strong",{children:"Banco do Brasil:"})," App â Extrato â Menu â Exportar OFX"]}),a("li",{children:["⢠",e("strong",{children:"Caixa:"})," Internet Banking â Extrato â Download â OFX"]})]}),a("p",{className:G.formatCard.ofxTip,children:[e("strong",{children:"Dica:"}),' Todos os bancos brasileiros são obrigados por lei a fornecer extrato em OFX. Se não encontrar, procure por "Money", "Quicken" ou "Microsoft Money" â são sinônimos de OFX.']})]}),w.value==="csv"&&e("div",{className:"text-xs text-muted-foreground",children:e("p",{children:"Formato varia entre bancos. Certifique-se que contém: Data, Descrição e Valor"})}),w.value==="xlsx"&&e("div",{className:"text-xs text-muted-foreground",children:e("p",{children:"Planilha Excel exportada do banco. Colunas: Data | Descrição | Valor | Saldo"})})]})})},w.value))})})]}),a(K,{className:G.infoCard,children:[e(te,{children:a(ne,{className:G.infoCardTitle,children:[e(Me,{className:G.infoCardIcon}),"Para que serve o Importador de Extratos?"]})}),a(ee,{className:"space-y-3 text-sm",children:[a("div",{children:[e("h4",{className:G.infoSectionTitle,children:"Controle Financeiro Automático"}),e("p",{className:G.infoSectionBody,children:"Importa automaticamente todas as movimentações bancárias (entradas e saÃdas) para o sistema, eliminando digitação manual e reduzindo erros."})]}),a("div",{children:[e("h4",{className:G.infoSectionTitle,children:"Conciliação Bancária"}),e("p",{className:G.infoSectionBody,children:"Compara os lançamentos importados com suas vendas, contas a pagar e receber, identificando divergências e garantindo que o saldo do sistema bata com o saldo real do banco."})]}),a("div",{children:[e("h4",{className:G.infoSectionTitle,children:"Relatórios Precisos (DRE)"}),e("p",{className:G.infoSectionBody,children:"Os dados importados alimentam o DRE com informações reais de receitas, despesas, custos fixos e variáveis, mostrando o lucro/prejuÃzo real do seu negócio."})]}),a("div",{children:[e("h4",{className:G.infoSectionTitle,children:"Detecção Inteligente"}),e("p",{className:G.infoSectionBody,children:"O sistema identifica automaticamente:"}),a("ul",{className:G.infoList,children:[a("li",{children:[e("strong",{children:"Boletos:"})," ExtraÃdos como despesas (fornecedores, serviços, impostos)"]}),a("li",{children:[e("strong",{children:"Faturas de Cartão:"})," Marcadas separadamente para evitar duplicação"]}),a("li",{children:[e("strong",{children:"PIX/TED/DOC:"})," Classificados como transferências ou pagamentos"]}),a("li",{children:[e("strong",{children:"Transferências Internas:"})," Entre suas próprias contas (ignoradas para não duplicar)"]})]})]}),a(Fe,{className:"bg-card/80 border-border",children:[e(Me,{className:"h-4 w-4"}),a(Ie,{className:"text-muted-foreground",children:[e("strong",{className:"text-foreground",children:"Dica:"})," Transferências entre suas próprias contas bancárias são automaticamente detectadas e mar
761cadas para não duplicar movimentações. Você pode revisar e escolher o que importar antes de confirmar."]})]})]})]})]}),M==="preview"&&a(Ee,{children:[a(Fe,{className:G.alert.purple,children:[e(Me,{className:_e("h-4 w-4",G.alert.purpleIcon)}),a(Ie,{className:_e(G.alert.purpleDesc,G.alert.purpleStrong),children:[e("strong",{children:"Detecção Inteligente Ativada:"})," O método de pagamento (PIX, Boleto, Cartão, etc.) foi detectado automaticamente analisando a descrição de cada transação. Verifique se está correto antes de importar. O badge colorido indica o método detectado."]})]}),a("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[a(K,{children:[e(te,{className:"pb-2",children:e(ne,{className:G.statCard.neutralTitle,children:"Total Transações"})}),e(ee,{children:e("div",{className:G.statCard.neutralValue,children:P.total})})]}),a(K,{className:G.statCard.green,children:[e(te,{className:"pb-2",children:e(ne,{className:G.statCard.titleGreen,children:"Entradas"})}),a(ee,{children:[e("div",{className:G.statCard.valueGreen,children:ve(P.totalCredits)}),a("p",{className:G.statCard.subtext,children:[P.credits," transações"]})]})]}),a(K,{className:G.statCard.red,children:[e(te,{className:"pb-2",children:e(ne,{className:G.statCard.titleRed,children:"SaÃdas"})}),a(ee,{children:[e("div",{className:G.statCard.valueRed,children:ve(P.totalDebits)}),a("p",{className:G.statCard.subtext,children:[P.debits," transações"]})]})]}),a(K,{className:G.statCard.yellow,children:[e(te,{className:"pb-2",children:e(ne,{className:G.statCard.titleYellow,children:"Ignoradas"})}),a(ee,{children:[e("div",{className:G.statCard.valueYellow,children:P.internal}),e("p",{className:G.statCard.subtext,children:"Transf. internas"})]})]})]}),a(K,{children:[e(te,{children:a("div",{className:"flex items-center justify-between",children:[a("div",{children:[e(ne,{children:"Preview das Transações"}),e(Se,{children:"Revise e escolha o que importar. Clique nas transações para incluir/excluir."})]}),a(j,{variant:"outline",size:"sm",onClick:()=>{c(!h),A(1)},children:[h?e(Br,{className:"h-4 w-4 mr-2"}):e(Lr,{className:"h-4 w-4 mr-2"}),h?"Ocultar":"Mostrar"," Transferências Internas"]})]})}),a(ee,{children:[e("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:x.filter(w=>h||!w.isInternalTransfer).slice((C-1)*f,C*f).map(w=>{const O=x.indexOf(w),H=b.has(O),I=!H&&(h||!w.isInternalTransfer);return a("div",{onClick:()=>{const U=new Set(b);H?U.delete(O):U.add(O),N(U)},className:_e("flex items-center justify-between p-3 rounded-lg border cursor-pointer transition-all",H?G.txnRow.excluded:w.isInternalTransfer?G.txnRow.internal:w.type==="credit"?G.txnRow.credit:G.txnRow.debit,I&&"hover:shadow-md"),children:[a("div",{className:"flex items-center gap-3 flex-1",children:[e(st,{checked:I,onCheckedChange:()=>{const U=new Set(b);H?U.delete(O):U.add(O),N(U)},onClick:U=>U.stopPropagation()}),H?e(jt,{className:_e("h-5 w-5",G.txnRow.excludedIcon)}):w.isInternalTransfer?e(Me,{className:_e("h-5 w-5",G.txnRow.iconInternal)}):w.type==="credit"?e(Oe,{className:_e("h-5 w-5",G.txnRow.iconCredit)}):e(Qa,{className:_e("h-5 w-5",G.txnRow.iconDebit)}),a("div",{className:"flex-1",children:[e("p",{className:"font-medium text-sm",children:w.description}),a("div",{className:_e("flex items-center gap-2",G.txnRow.meta),children:[e("span",{children:Ze(w.date)}),w.category&&a(Ee,{children:[e("span",{children:"â¢"}),e(ae,{variant:"outline",className:"text-xs",children:w.category})]}),w.paymentMethod&&a(Ee,{children:[e("span",{children:"â¢"}),e(ae,{variant:"secondary",className:_e("text-xs",w.paymentMethod==="pix"?G.paymentBadge.pix:w.paymentMethod==="boleto"?G.paymentBadge.boleto:w.paymentMethod==="credit_card"?G.paymentBadge.credit_card:w.paymentMethod==="debit_card"?G.paymentBadge.debit_card:w.paymentMethod==="transfer"?G.paymentBadge.transfer:G.paymentBadge.default),children:w.paymentMethod==="pix"?"PIX":w.paymentMethod==="boleto"?"Boleto":w.paymentMethod==="credit_card"?"Crédito":w.paymentMethod==="debit_card"?"Débito":w.paymentMethod==="transfer"?"Transfer.":w.paymentMethod==="cash"?"Dinheiro":"Outros"})]}),w.isInternalTransfer&&a(Ee,{children:[e("span",{children:"â¢"}),e("span",{className:G.txnRow.internalLabel,children:"Transferência Interna"})]}),H&&a(Ee,{children:[e("span",{children:"â¢"}),e("span",{className:G.txnRow.excludedLabel,children:"Não será importada"})]})]})]})]}),a("div",{className:_e("font-semibold",H?G.txnRow.excludedAmount:w.type==="credit"?G.txnRow.creditAmount:G.txnRow.debitAmount),children:[w.type==="credit"?"+":"-"," ",ve(w.amount)]})]},O)})}),(()=>{const w=x.filter(U=>h||!U.isInternalTransfer).length,O=Math.ceil(w/f),H=(C-1)*f+1,I=Math.min(C*f,w);return w<=f?null:a("div",{className:"mt-4 space-y-3",children:[a("p",{className:_e("text-xs text-center",G.statCard.subtext),children:["Mostrando ",H,"-",I," de ",w," transações (Página ",C,"/",O,")"]}),a("div",{className:"flex items-center justify-center gap-2",children:[e(j,{size:"sm",variant:"outline",disabled:C===1,onClick:()=>A(1),children:"Primeira"}),e(j,{size:"sm",variant:"outline",disabled:C===1,onClick:()=>A(U=>U-1),children:"Anterior"}),e("div",{className:"flex gap-1",children:Array.from({length:Math.min(O,5)},(U,se)=>{let le;return O<=5||C<=3?le=se+1:C>=O-2?le=O-4+se:le=C-2+se,e(j,{size:"sm",variant:C===le?"default":"outline",onClick:()=>A(le),children:le},le)})}),e(j,{size:"sm",variant:"outline",disabled:C===O,onClick:()=>A(U=>U+1),children:"Próxima"}),e(j,{size:"sm",variant:"outline",disabled:C===O,onClick:()=>A(O),children:"Ãltima"})]})]})})()]})]}),a("div",{className:"flex gap-3",children:[e(j,{variant:"outline",onClick:()=>{E("upload"),y([]),i(null)},children:"Cancelar"}),e(j,{onClick:Y,disabled:d,className:"flex-1",children:d?a(Ee,{children:[e(ba,{className:"h-4 w-4 mr-2 animate-spin"}),"Importando..."]}):a(Ee,{children:[e($e,{className:"h-4 w-4 mr-2"}),"Confirmar Importação (",P.total-P.internal," transações)"]}
761)})]})]}),M==="complete"&&a(K,{className:G.completeCard,children:[a(te,{className:"text-center",children:[e("div",{className:"flex justify-center mb-4",children:e("div",{className:G.completeIcon,children:e($e,{className:"h-10 w-10 text-white"})})}),e(ne,{className:"text-3xl",children:"Importação ConcluÃda!"}),e(Se,{className:"text-base mt-2",children:"Suas transações foram importadas com sucesso"})]}),a(ee,{className:"text-center space-y-4",children:[a("div",{className:G.completeInner,children:[e("p",{className:"text-sm text-muted-foreground",children:"Transações Importadas"}),e("p",{className:G.completeCount,children:P.total-P.internal})]}),e(j,{onClick:()=>{E("upload"),y([]),i(null),r("")},variant:"outline",className:"w-full",children:"Importar Outro Extrato"})]})]})]})}function Vo(){const{mode:t,setMode:r}=Zr();return e(ls,{children:a("div",{className:"flex items-center gap-1 bg-muted/30 rounded-lg p-1",children:[a(Ht,{children:[e(Xt,{asChild:!0,children:a(j,{variant:t==="beginner"?"default":"ghost",size:"sm",onClick:()=>r("beginner"),className:_e("h-8 px-3 gap-2",t==="beginner"&&"bg-green-600 hover:bg-green-700 text-white"),children:[e(bn,{className:"h-4 w-4"}),e("span",{className:"hidden sm:inline",children:"Simples"})]})}),a(Yt,{children:[e("p",{className:"text-sm",children:"Modo Simples"}),e("p",{className:"text-xs text-muted-foreground",children:"Linguagem fácil, sem termos técnicos"})]})]}),a(Ht,{children:[e(Xt,{asChild:!0,children:a(j,{variant:t==="professional"?"default":"ghost",size:"sm",onClick:()=>r("professional"),className:_e("h-8 px-3 gap-2",t==="professional"&&"bg-blue-600 hover:bg-blue-700 text-white"),children:[e(fn,{className:"h-4 w-4"}),e("span",{className:"hidden sm:inline",children:"Profissional"})]})}),a(Yt,{children:[e("p",{className:"text-sm",children:"Modo Profissional"}),e("p",{className:"text-xs text-muted-foreground",children:"Termos técnicos financeiros (SEBRAE)"})]})]})]})})}function Cc(){return e(ko,{children:e(Lo,{})})}function Lo(){const{license:t}=xn(),r=(t==null?void 0:t.type)!=="free",s=Ut(),[n,o]=_.useState("dashboard"),[m,u]=_.useState(new Date().getMonth()+1),[i,d]=_.useState(new Date().getFullYear()),[g,x]=_.useState(null),[y,M]=_.useState(!1);_.useEffect(()=>{let b=!1;return(async()=>{const{data:{user:N}}=await v.auth.getUser();if(!(!N||b))try{await ut(N.id,{syncPayable:!0})}catch(C){console.warn("[Financial] Alinhamento pró-labore:",C)}})(),()=>{b=!0}},[]);const E={startDate:new Date(i,m-1,1),endDate:new Date(i,m,0,23,59,59)},h=g||E,c=[{value:1,label:"Janeiro"},{value:2,label:"Fevereiro"},{value:3,label:"Março"},{value:4,label:"Abril"},{value:5,label:"Maio"},{value:6,label:"Junho"},{value:7,label:"Julho"},{value:8,label:"Agosto"},{value:9,label:"Setembro"},{value:10,label:"Outubro"},{value:11,label:"Novembro"},{value:12,label:"Dezembro"}];return a("div",{className:"container mx-auto p-4 space-y-6",children:[e(K,{children:e(te,{children:a("div",{className:"flex items-center justify-between",children:[a("div",{children:[e(ne,{className:"text-2xl",children:s.t("Gestão Financeira Profissional","Meu Dinheiro")}),e("p",{className:"text-sm text-muted-foreground mt-1",children:s.t("Análise completa baseada em conceitos SEBRAE","Controle simples do seu negócio")})]}),a("div",{className:"flex gap-2 items-center flex-wrap justify-end",children:[a(j,{type:"button",variant:"outline",size:"sm",onClick:()=>M(!0),className:"gap-1.5",children:[e(Vr,{className:"h-4 w-4"}),e("span",{className:"hidden sm:inline",children:"Ajuda"})]}),e(Vo,{}),e(Hr,{month:m,year:i}),e(Do,{variant:"inline"}),e("select",{value:m,onChange:b=>{u(Number(b.target.value)),x(null)},className:"px-3 py-2 border dark:border-border rounded-md text-sm bg-background dark:bg-card text-foreground",children:c.map(b=>e("option",{value:b.value,children:b.label},b.value))}),a("select",{value:i,onChange:b=>{d(Number(b.target.value)),x(null)},className:"px-3 py-2 border dark:border-border rounded-md text-sm bg-background dark:bg-card text-foreground",children:[e("option",{value:2024,children:"2024"}),e("option",{value:2025,children:"2025"}),e("option",{value:2026,children:"2026"})]}),a("div",{className:"flex items-center gap-2",children:[e(rt,{value:g==null?void 0:g.startDate,onChange:b=>{const N=ra(b);x(C=>{const A=C!=null&&C.endDate?ra(C.endDate):N,f=A<N?N:A;return{startDate:N,endDate:f}})},label:"De",size:"sm"}),e(rt,{value:g==null?void 0:g.endDate,onChange:b=>{const N=ra(b);x(C=>{const A=C!=null&&C.startDate?ra(C.startDate):N,f=N<A?A:N;return{startDate:A,endDate:f}})},label:"Até",size:"sm"}),g?e(j,{variant:"outline",size:"sm",onClick:()=>x(null),children:"Limpar"}):null]})]})]})})}),a(pt,{value:n,onValueChange:o,className:"w-full",children:[a(gt,{className:"grid w-full grid-cols-5 sm:grid-cols-10 lg:w-auto lg:inline-grid",children:[a(qe,{value:"dashboard",className:"flex items-center gap-2",children:[e(Ca,{className:"h-4 w-4"}),e("span",{className:"hidden sm:inline",children:s.get("dashboard")})]}),a(qe,{value:"payable",className:"flex items-center gap-2",children:[e(ta,{className:"h-4 w-4"}),e("span",{className:"hidden sm:inline",children:s.get("accountsPayable")})]}),a(qe,{value:"receivable",className:"flex items-center gap-2",children:[e(Ke,{className:"h-4 w-4"}),e("span",{className:"hidden sm:inline",children:s.get("accountsReceivable")})]}),a(qe,{value:"history",className:"flex items-center gap-2",children:[e($e,{className:"h-4 w-4"}),e("span",{className:"hidden sm:inline",children:s.get("paymentHistory")})]}),a(qe,{value:"indicators",className:"flex items-center gap-2",children:[e(Oe,{className:"h-4 w-4"}),e("span",{className:"hidden sm:inline",children:s.get("indicators")})]}),a(qe,{value:"dre",className:"flex items-center gap-2",children:[e(da,{className:"h-4 w-4"}),e("span",{className:"hidden sm:inline",children:s.get("dre")})]}),a(qe,{value:"breakeven",className:"flex items-center gap-2",children:[e(pa,{
761className:"h-4 w-4"}),e("span",{className:"hidden sm:inline",children:s.get("breakEven")})]}),a(qe,{value:"ai-analysis",className:"flex items-center gap-2",children:[e($a,{className:"h-4 w-4"}),e("span",{className:"hidden sm:inline",children:s.get("aiAnalysis")})]}),a(qe,{value:"banks",className:"flex items-center gap-2",children:[e(ht,{className:"h-4 w-4"}),e("span",{className:"hidden sm:inline",children:s.get("bankAccounts")})]}),a(qe,{value:"import",className:"flex items-center gap-2",children:[e(qt,{className:"h-4 w-4"}),e("span",{className:"hidden sm:inline",children:s.get("bankImport")})]})]}),e(Io,{open:y,onOpenChange:M,activeTab:n}),e(Je,{value:"dashboard",className:"mt-6",children:e(Eo,{})}),e(Je,{value:"payable",className:"mt-6",children:r?e(No,{}):e(Na,{feature:"financial"})}),e(Je,{value:"receivable",className:"mt-6",children:r?e(wo,{}):e(Na,{feature:"financial"})}),e(Je,{value:"history",className:"mt-6",children:e(Co,{})}),e(Je,{value:"indicators",className:"mt-6",children:r?e(jn,{period:h}):e(Na,{feature:"financial"})}),e(Je,{value:"dre",className:"mt-6",children:r?e(Un,{period:h}):e(Na,{feature:"financial"})}),e(Je,{value:"breakeven",className:"mt-6",children:r?e(Wn,{period:h}):e(Na,{feature:"financial"})}),e(Je,{value:"ai-analysis",className:"mt-6",children:r?e(Po,{period:h}):e(Na,{feature:"financial"})}),e(Je,{value:"banks",className:"mt-6",children:r?e(To,{}):e(Na,{feature:"financial"})}),e(Je,{value:"import",className:"mt-6",children:r?e(qo,{}):e(Na,{feature:"financial"})})]})]})}export{Cc 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.