PageSourceSearch

https://ecommercetools.lovable.app/assets/PricingTool-DYYjFIhz.js

js ecommercetools.lovable.app collected 2026-10-03 03:30:18 UTC 69,382 bytes, 6 lines download raw bytes

1import{c as na,j as e,L as C,ak as A,S as U,m as G,n as H,o as Q,p as v,B as g,an as h,v as ue,al as ca,ah as la,ao as da,s as Ue,q as ma,as,u as ua,a as pa}from"./index-Cvkbcx7o.js";import{r as i}from"./react-DshDVN6X.js";import{u as me,w as ms,r as xa}from"./sheets-uoQkVabA.js";import{C as F}from"./card-DfmUXIpv.js";import{B as ts}from"./badge-Cid6NAYR.js";import{T as ha,a as ga,b as es,c as ss}from"./tabs-lv2sGyZY.js";import{D as Pe,a as Me,b as Fe,c as Te,P as ja,d as us,S as As,u as va,T as fa}from"./Dashboard-C1iuHx5B.js";import{P as Na}from"./ProgramSelector-Bful6vRp.js";import{H as ba}from"./HowToUseButton-1XYODJT_.js";import{c as Es,h as Is,d as ps,i as xs,s as $s}from"./pdfExport-I9sTGtJ5.js";import{I as Ca}from"./InfoHint-0F2wyT2h.js";import{C as hs,p as ya,f as M,a as wa,c as ke,m as Sa,b as _e,d as ka,e as _a,g as be,D as Ss,n as Pa,h as ls,i as Ma}from"./calc-BA3F_yYX.js";import{S as Ds}from"./switch-B_DvtZwb.js";import{S as Bs}from"./save-CNCU-MZK.js";import{P as rs}from"./plus-ClByMxcJ.js";import{P as gs}from"./pencil-Bwmtr_fL.js";import{T as Ke}from"./trash-2-BWkehG29.js";import{F as js}from"./file-spreadsheet-BlrQnm_J.js";import{F as Rs}from"./file-down-DupYA9rB.js";import{f as Vs,c as qs}from"./abcSync-Bkk3W9FA.js";import{R as Ls}from"./refresh-cw-Cv73Kbix.js";import{T as ks}from"./target-ETns8Tus.js";import{C as Fa}from"./chevron-left-peGWMssr.js";import{C as Ta}from"./lock-BIimy1Cz.js";import{D as Aa}from"./download-CyfJulW1.js";import{U as Ea}from"./upload-BgYH2KiE.js";import"./pdf-5yfr9NG8.js";import"./charts-BdJeKDok.js";import"./supabase-FJNi00o9.js";import"./index-BlBnr0iU.js";import"./clipboard-list-DvU85Tqj.js";import"./command-D5mzLA4b.js";import"./circle-play-B5fhaY53.js";import"./abcClassification-DwYdostj.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 Ia=na("Truck",[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]]);function zs({costs:r,onChange:E,onFreteModeChange:k,disabled:I,compact:_}){const B=hs.filter(j=>j.type==="pct"),R=hs.filter(j=>j.type==="brl"&&j.key!=="custoFrete"),m=r.custoFreteMode==="pct"?"pct":"brl",Z=(j,$,P,f)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs font-medium",children:$}),e.jsxs("div",{className:"relative",children:[e.jsx(A,{type:"number",step:"0.01",inputMode:"decimal",disabled:I,value:Number.isFinite(r[j])?r[j]:0,onChange:D=>E(j,D.target.value===""?0:parseFloat(D.target.value)||0),className:"pr-10"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground",children:P})]}),f&&!_&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:f})]},j);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-2",children:"Deduções sobre a venda (%)"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:B.map(j=>Z(j.key,j.label,"%",j.hint))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-2",children:"Custos por pedido"}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[R.map(j=>Z(j.key,j.label,"R$",j.hint)),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs font-medium",children:"Frete subsidiado"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(A,{type:"number",step:"0.01",inputMode:"decimal",disabled:I,value:Number.isFinite(r.custoFrete)?r.custoFrete:0,onChange:j=>E("custoFrete",j.target.value===""?0:parseFloat(j.target.value)||0),className:"pr-10"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground",children:m==="pct"?"%":"R$"})]}),e.jsxs(U,{value:m,disabled:I,onValueChange:j=>k==null?void 0:k(j),children:[e.jsx(G,{className:"w-[76px]",children:e.jsx(H,{})}),e.jsxs(Q,{children:[e.jsx(v,{value:"brl",children:"R$"}),e.jsx(v,{value:"pct",children:"%"})]})]})]}),!_&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:m==="pct"?"Percentual sobre o preço de venda":"Valor fixo por pedido"})]})]})]}),!_&&e.jsxs(F,{className:"p-3 bg-muted/40 border-border text-sm space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-8 gap-y-1",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:["Composição dos custos variáveis",e.jsx(Ca,{title:"Composição dos custos variáveis",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{children:[e.jsx("span",{className:"font-medium text-foreground",children:"Custo percentual (%): "}),"parte dos custos cobrada sobre o preço de venda — impostos, taxa de pagamento, comissões e marketing. Ele acompanha o preço: se o preço sobe, o valor em reais também sobe, por isso é informado em porcentagem."]}),e.jsxs("p",{children:[e.jsx("span",{className:"font-medium text-foreground",children:"Custo por pedido (R$): "}),"valores fixos pagos a cada venda, independente do preço — embalagem, outros insumos e o frete subsidiado quando cadastrado em reais."]}),e.jsxs("p",{children:[e.jsx("span",{className:"font-medium text-foreground",children:"Por que aparece separado: "}),"um percentual e um valor em reais não podem ser somados diretamente — o % só vira reais quando aplicad
6o ao preço de cada produto. Por isso exibimos os dois totais em linhas separadas; a soma correta dos dois já acontece dentro do cálculo da margem de contribuição de cada item."]}),e.jsxs("p",{children:[e.jsx("span",{className:"font-medium text-foreground",children:"Atenção: "}),"o frete subsidiado entra na linha correspondente ao modo escolhido no campo dele (R$ por pedido ou % do preço)."]})]})})]}),e.jsxs("span",{children:["Custo percentual: ",e.jsxs("b",{children:[(ya(r)*100).toFixed(2),"%"]})," do preço"]}),e.jsxs("span",{children:["Custo por pedido: ",e.jsx("b",{children:M(wa(r))})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"O percentual incide sobre o preço de venda; o valor por pedido é fixo em reais. A soma dos dois é feita automaticamente no cálculo da margem de cada produto."})]})]})}function $a({product:r,globalCosts:E,globalTarget:k,categories:I,readOnly:_,onClose:B,onSave:R}){const[m,Z]=i.useState(r),[j,$]=i.useState(!1);if(i.useEffect(()=>{Z(r),$(!!r&&Object.keys(r.costOverrides||{}).length>0)},[r]),!m)return null;const P=c=>Z(z=>z&&{...z,...c}),f=ke(m,E,k),D=Sa(E,m.costOverrides);return e.jsx(Pe,{open:!!r,onOpenChange:c=>{c||B()},children:e.jsxs(Me,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Fe,{children:e.jsx(Te,{className:"text-xl",children:m.name?"Editar produto":"Novo produto"})}),e.jsxs("div",{className:"space-y-5 mt-2",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{className:"space-y-1.5 sm:col-span-2",children:[e.jsx(C,{className:"text-xs",children:"Nome do produto"}),e.jsx(A,{value:m.name,disabled:_,onChange:c=>P({name:c.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"SKU"}),e.jsx(A,{value:m.sku,disabled:_,onChange:c=>P({sku:c.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Categoria"}),e.jsx(A,{list:"pricing-categories",value:m.category,disabled:_,onChange:c=>P({category:c.target.value})}),e.jsx("datalist",{id:"pricing-categories",children:I.map(c=>e.jsx("option",{value:c},c))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Custo do produto (R$)"}),e.jsx(A,{type:"number",step:"0.01",disabled:_,value:m.productCost,onChange:c=>P({productCost:parseFloat(c.target.value)||0})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Curva ABC"}),e.jsxs(U,{value:m.curve,disabled:_,onValueChange:c=>P({curve:c}),children:[e.jsx(G,{children:e.jsx(H,{})}),e.jsxs(Q,{children:[e.jsx(v,{value:"A",children:"Curva A"}),e.jsx(v,{value:"B",children:"Curva B"}),e.jsx(v,{value:"C",children:"Curva C"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Forma de precificação"}),e.jsxs(U,{value:m.method,disabled:_,onValueChange:c=>P({method:c}),children:[e.jsx(G,{children:e.jsx(H,{})}),e.jsxs(Q,{children:[e.jsx(v,{value:"markup",children:"Markup"}),e.jsx(v,{value:"price",children:"Preço direto"}),e.jsx(v,{value:"margin",children:"Margem de contribuição alvo"})]})]})]}),m.method==="markup"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Markup (x)"}),e.jsx(A,{type:"number",step:"0.01",disabled:_,value:m.markup,onChange:c=>P({markup:parseFloat(c.target.value)||0})})]}),m.method==="price"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Preço de venda (R$)"}),e.jsx(A,{type:"number",step:"0.01",disabled:_,value:m.price,onChange:c=>P({price:parseFloat(c.target.value)||0})})]}),m.method==="margin"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Margem alvo (%)"}),e.jsx(A,{type:"number",step:"0.1",disabled:_,placeholder:`Global: ${k}`,value:m.targetMarginPct??"",onChange:c=>P({targetMarginPct:c.target.value===""?null:parseFloat(c.target.value)||0})})]})]}),e.jsxs(F,{className:"p-4 border-border space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Custos variáveis específicos deste produto"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Desligado, o produto usa os custos variáveis globais."})]}),e.jsx(Ds,{checked:j,disabled:_,onCheckedChange:c=>{$(c),P({costOverrides:c?{...D}:{}})}})]}),j&&e.jsx(zs,{compact:!0,disabled:_,costs:D,onChange:(c,z)=>P({costOverrides:{...m.costOverrides,[c]:z}}),onFreteModeChange:c=>P({costOverrides:{...m.costOverrides,custoFreteMode:c}})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsxs(F,{className:"p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Preç
6o"}),e.jsx("p",{className:"text-lg font-semibold",children:M(f.price)})]}),e.jsxs(F,{className:"p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Deduções"}),e.jsx("p",{className:"text-lg font-semibold",children:M(f.deductions.total)})]}),e.jsxs(F,{className:"p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Markup"}),e.jsxs("p",{className:"text-lg font-semibold",children:[f.markup.toFixed(2),"x"]})]}),e.jsxs(F,{className:"p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Margem de contribuição"}),e.jsxs("p",{className:`text-lg font-semibold ${f.contribution>=0?"text-green-600":"text-destructive"}`,children:[M(f.contribution)," · ",_e(f.contributionPct)]})]})]}),!f.feasible&&e.jsx("p",{className:"text-xs text-destructive",children:"Margem alvo inviável com os percentuais informados. Reduza deduções ou a meta."}),!_&&e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(g,{variant:"outline",onClick:B,children:"Cancelar"}),e.jsxs(g,{className:"gap-2",onClick:()=>R({...m,price:f.price}),children:[e.jsx(Bs,{className:"h-4 w-4"})," Salvar"]})]})]})]})})}const te=Ue,_s=r=>({id:r.id,name:r.name??"",description:r.description??"",status:r.status??"draft",startDate:r.start_date??null,endD
6ate:r.end_date??null}),Ps=r=>({id:r.id,campaignId:r.campaign_id,name:r.name??"",discountType:r.discount_type??"pct",discountValue:Number(r.discount_value??0),freeShipping:!!r.free_shipping,freightCost:r.freight_cost===null||r.freight_cost===void 0?null:Number(r.freight_cost),freightCostMode:r.freight_cost_mode??"brl",position:Number(r.position??0)}),Ms=r=>({id:r.id,campaignId:r.campaign_id,groupId:r.group_id,productId:r.product_id,discountOverride:r.discount_override===null||r.discount_override===void 0?null:Number(r.discount_override)}),Da={draft:"bg-muted text-muted-foreground border-border",active:"bg-green-500/15 text-green-600 border-green-500/30",archived:"bg-yellow-500/15 text-yellow-700 border-yellow-500/30"};function Ba({products:r,costs:E,target:k,programId:I,userId:_,readOnly:B,categories:R}){const[m,Z]=i.useState(!0),[j,$]=i.useState([]),[P,f]=i.useState([]),[D,c]=i.useState([]),[z,re]=i.useState(null),[O,N]=i.useState(!1),[Y,ie]=i.useState(!1),[V,ne]=i.useState(null),[pe,ce]=i.useState(!1),[x,q]=i.useState(null),[Ce,ae]=i.useState(!1),[ve,y]=i.useState(null),[ee,X]=i.useState(""),[le,Ge]=i.useState("all"),[ye,Ae]=i.useState("all"),[we,fe]=i.useState(new Set),De=i.useMemo(()=>new Map(r.map(a=>[a.id,a])),[r]),K=j.find(a=>a.id===z)??null,Be=i.useCallback(async()=>{if(_){Z(!0);try{let a=te.from("pricing_campaigns").select("*");a=I?a.eq("program_id",I):a.eq("user_id",_).is("program_id",null);const{data:d,error:n}=await a.order("created_at",{ascending:!1});if(n)throw n;const p=(d??[]).map(_s);$(p);const u=p.map(L=>L.id);if(u.length){const[{data:L},{data:J}]=await Promise.all([te.from("pricing_campaign_groups").select("*").in("campaign_id",u).order("position"),te.from("pricing_campaign_items").select("*").in("campaign_id",u)]);f((L??[]).map(Ps)),c((J??[]).map(Ms))}else f([]),c([])}catch(a){h.error("Erro ao carregar campanhas",{description:a.message})}finally{Z(!1)}}},[_,I]);i.useEffect(()=>{Be()},[Be]),i.useEffect(()=>{re(null)},[I]);const Re=async()=>{if(!(!V||!_)){if(!V.name.trim()){h.error("Informe o nome da campanha");return}N(!0);try{const a={user_id:_,program_id:I,name:V.name.trim(),description:V.description.trim()||null,status:V.status,start_date:V.startDate||null,end_date:V.endDate||null};if(j.some(n=>n.id===V.id)){const{error:n}=await te.from("pricing_campaigns").update(a).eq("id",V.id);if(n)throw n;$(p=>p.map(u=>u.id===V.id?V:u))}else{const{data:n,error:p}=await te.from("pricing_campaigns").insert(a).select("*").single();if(p)throw p;const u=_s(n);$(L=>[u,...L]),re(u.id)}ie(!1),h.success("Campanha salva")}catch(a){h.error("Erro ao salvar campanha",{description:a.message})}finally{N(!1)}}},He=async a=>{if(!window.confirm("Excluir esta campanha e todos os seus blocos?"))return;const{error:d}=await te.from("pricing_campaigns").delete().eq("id",a);if(d){h.error("Erro ao excluir campanha",{description:d.message});return}$(n=>n.filter(p=>p.id!==a)),f(n=>n.filter(p=>p.campaignId!==a)),c(n=>n.filter(p=>p.campaignId!==a)),z===a&&re(null),h.success("Campanha excluída")},de=async()=>{if(!(!x||!K)){if(!x.name.trim()){h.error("Informe o nome do bloco");return}N(!0);try{const a={campaign_id:K.id,name:x.name.trim(),discount_type:x.discountType,discount_value:x.discountValue,free_shipping:x.freeShipping,freight_cost:x.freightCost,freight_cost_mode:x.freightCostMode,position:x.position};if(P.some(n=>n.id===x.id)){const{error:n}=await te.from("pricing_campaign_groups").update(a).eq("id",x.id);if(n)throw n;f(p=>p.map(u=>u.id===x.id?x:u))}else{const{data:n,error:p}=await te.from("pricing_campaign_groups").insert(a).select("*").single();if(p)throw p;f(u=>[...u,Ps(n)])}ce(!1),h.success("Bloco salvo")}catch(a){h.error("Erro ao salvar bloco",{description:a.message})}finally{N(!1)}}},os=async a=>{if(!window.confirm("Excluir este bloco e os produtos vinculados a ele?"))return;const{error:d}=await te.from("pricing_campaign_groups").delete().eq("id",a);if(d){h.error("Erro ao excluir bloco",{description:d.message});return}f(n=>n.filter(p=>p.id!==a)),c(n=>n.filter(p=>p.groupId!==a)),h.success("Bloco excluído")},Qe=a=>{y(a),fe(new Set(D.filter(d=>d.groupId===a).map(d=>d.productId))),X(""),Ge("all"),Ae("all"),ae(!0)},Se=i.useMemo(()=>{const a=ee.trim().toLowerCase();return r.filter(d=>(le==="all"||d.category===le)&&(ye==="all"||d.curve===ye)&&(!a||d.name.toLowerCase().includes(a)||(d.sku||"").toLowerCase().includes(a)))},[r,ee,le,ye]),Ve=async()=>
6{if(!(!ve||!K)){N(!0);try{const a=D.filter(u=>u.groupId===ve),d=[...we].filter(u=>!a.some(L=>L.productId===u)),n=a.filter(u=>!we.has(u.productId));if(n.length){const{error:u}=await te.from("pricing_campaign_items").delete().in("id",n.map(L=>L.id));if(u)throw u}let p=[];if(d.length){const{data:u,error:L}=await te.from("pricing_campaign_items").insert(d.map(J=>({campaign_id:K.id,group_id:ve,product_id:J}))).select("*");if(L)throw L;p=(u??[]).map(Ms)}c(u=>[...u.filter(L=>!n.some(J=>J.id===L.id)),...p]),ae(!1),h.success("Produtos do bloco atualizados")}catch(a){h.error("Erro ao atualizar produtos do bloco",{description:a.message})}finally{N(!1)}}},Xe=async a=>{const{error:d}=await te.from("pricing_campaign_items").delete().eq("id",a.id);if(d){h.error("Erro ao remover produto",{description:d.message});return}c(n=>n.filter(p=>p.id!==a.id))},xe=P.filter(a=>a.campaignId===z),Ee=i.useCallback(a=>D.filter(d=>d.groupId===a.id).map(d=>{const n=De.get(d.productId);return n?{item:d,p:n,r:ka(n,E,k,a,d.discountOverride)}:null}).filter(Boolean),[D,De,E,k]),W=i.useMemo(()=>{let a=0,d=0,n=0,p=0,u=0;return xe.forEach(L=>Ee(L).forEach(({r:J})=>{a++,J.negative&&d++,J.belowTarget&&n++,p+=J.base.contribution,u+=J.promoContribution})),{count:a,negative:d,below:n,baseMc:p,promoMc:u,delta:u-p}},[xe,Ee]),qe=()=>xe.flatMap(a=>Ee(a).map(({p:d,r:n})=>({Bloco:a.name,Produto:d.name,SKU:d.sku,"Frete gratis":a.freeShipping?"Sim":"Nao","Preco normal":Number(n.base.price.toFixed(2)),"Preco campanha":Number(n.promoPrice.toFixed(2)),"Desconto R$":Number(n.discountValue.toFixed(2)),"MC normal R$":Number(n.base.contribution.toFixed(2)),"MC campanha R$":Number(n.promoContribution.toFixed(2)),"MC normal %":Number(n.base.contributionPct.toFixed(2)),"MC campanha %":Number(n.promoContributionPct.toFixed(2))}))),We=()=>{const a=me.json_to_sheet(qe()),d=me.book_new();me.book_append_sheet(d,a,"Campanha"),ms(d,`campanha-${((K==null?void 0:K.name)||"precificacao").toLowerCase().replace(/\s+/g,"-")}.xlsx`)},is=()=>{if(!K)return;const a=Es(`Campanha de precificação — ${K.name}`);let d=45;d=Is(a,[{label:"Produtos",value:String(W.count)},{label:"MC normal",value:M(W.baseMc)},{label:"MC campanha",value:M(W.promoMc)},{label:"Margem negativa",value:String(W.negative)}],d),xe.forEach(n=>{d=ps(a,`${n.name} — ${n.discountType==="pct"?`${n.discountValue}% de desconto`:`${M(n.discountValue)} de desconto`}${n.freeShipping?" · frete grátis":""}`,d),d=xs(a,[{header:"Produto",dataKey:"n"},{header:"Preço normal",dataKey:"a",halign:"right"},{header:"Preço campanha",dataKey:"b",halign:"right"},{header:"MC normal",dataKey:"c",halign:"right"},{header:"MC campanha",dataKey:"d",halign:"right"},{header:"MC %",dataKey:"e",halign:"right"}],Ee(n).map(({p,r:u})=>({n:p.name,a:M(u.base.price),b:M(u.promoPrice),c:M(u.base.contribution),d:M(u.promoContribution),e:_e(u.promoContributionPct)})),d)}),$s(a,"campanha-precificacao")};return m?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(ue,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):K?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(g,{variant:"ghost",size:"icon",onClick:()=>re(null),children:e.jsx(ca,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h3",{className:"font-semibold truncate flex items-center gap-2",children:[e.jsx(la,{className:"h-4 w-4"})," ",K.name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:K.description||"Sem descrição"})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",className:"gap-2",onClick:We,disabled:W.count===0,children:[e.jsx(js,{className:"h-4 w-4"})," Excel"]}),e.jsxs(g,{variant:"outline",size:"sm",className:"gap-2",onClick:is,disabled:W.count===0,children:[e.jsx(Rs,{className:"h-4 w-4"})," PDF"]}),!B&&e.jsxs(g,{size:"sm",className:"gap-2",onClick:()=>{q({id:crypto.randomUUID(),campaignId:K.id,name:"",discountType:"pct",discountValue:10,freeShipping:!1,freightCost:null,freightCostMode:"brl",position:xe.length}),ce(!0)},children:[e.jsx(rs,{className:"h-4 w-4"})," Novo bloco"]})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsxs(F,{className:"p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Produtos na campanha"}),e.jsx("p",{className:"text-lg font-semibold",children:W.count})]}),e.jsxs(F,{className:"p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"MC total normal"}),e.jsx("p",{className:"text-lg font-semibold",children:M(W.baseMc)})]}),e.jsxs(F,{className:"p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"MC total na campanha"}),e.jsx("p",{className:`text-lg font-semibold ${W.promoMc<0?"text-destructive":""}`,children:M(W.promoMc)})]}),e.jsxs(F,{className:"p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Margem negativa"}),e.jsx("p",{className:"text-lg font-semibold text-destructive",children:W.negative})]})]}),W.negative>0&&e.jsxs(F,{className:"p-3 border-destructive/40 bg-destructive/5 text-sm",children:[W.negative," produto(s) ficam com margem de contribuição negativa nesta campanha. Reduza o desconto ou reveja o frete grátis."]}),xe.length===0?e.jsx(F,{className:"p-8 text-center text-sm text-muted-foreground",children:"Nenhum bloco nesta campanha. Crie um bloco (ex.: “Curva C — 25% + frete grátis”) e escolha os produtos."}):xe.map(a=>{const d=Ee(a);return e.jsxs(F,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 p-4 border-b border-border",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium flex flex-wrap items-center gap-2",children:[a.name,e.jsx(ts,{variant:"outline",className:"text-[10px]",children:a.discountType==="pct"?`${a.discountValue}% OFF`:`${M(a.discountValue)} OFF`}),a.freeShipping&&e.jsxs(ts,{className:"bg-cyan-500/15 text-cyan-700 border-cyan-500/30 border text-[10px] gap-1",children:[e.jsx(Ia,{className:"h-3 w-3"})," Frete grátis"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[d.length," produto(s)",a.freeShipping&&` · custo de frete absorvido: ${a.freightCost===null?"usa o custo cadastrado":a.freightCostMode==="pct"?`${a.freightCost}% do preço`:M(a.freightCost)}`]})]}),!B&&e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(g,{size:"sm",variant:"outline",className:"gap-1",onClick:()=>Qe(a.id),children:[e.jsx(ja,{className:"h-3.5 w-3.5"})," Produtos"]}),e.jsx(g,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>{q(a),ce(!0)},children:e.jsx(gs,{className:"h-4 w-4"})}),e.jsx(g,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive",onClick:()=>os(a.id),children:e.jsx(Ke,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-xs text-muted-foreground border-b",children:[e.jsx("th",{className:"text-left p-3",children:"Produto"}
6),e.jsx("th",{className:"text-right",children:"Preço normal"}),e.jsx("th",{className:"text-right",children:"Preço campanha"}),e.jsx("th",{className:"text-right",children:"Desconto"}),e.jsx("th",{className:"text-right",children:"MC normal"}),e.jsx("th",{className:"text-right",children:"MC campanha"}),e.jsx("th",{className:"text-right",children:"MC %"}),!B&&e.jsx("th",{className:"text-right pr-3",children:"Ações"})]})}),e.jsxs("tbody",{children:[d.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"p-6 text-center text-muted-foreground",children:"Nenhum produto neste bloco."})}),d.map(({item:n,p,r:u})=>e.jsxs("tr",{className:"border-b border-border/50",children:[e.jsxs("td",{className:"p-3",children:[e.jsx("p",{className:"font-medium truncate max-w-[220px]",children:p.name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate max-w-[220px]",children:[p.sku,p.category].filter(Boolean).join(" · ")||"—"})]}),e.jsx("td",{className:"text-right text-muted-foreground",children:M(u.base.price)}),e.jsx("td",{className:"text-right font-medium",children:M(u.promoPrice)}),e.jsx("td",{className:"text-right text-muted-foreground",children:M(u.discountValue)}),e.jsx("td",{className:"text-right text-muted-foreground",children:M(u.base.contribution)}),e.jsx("td",{className:`text-right font-medium ${u.negative?"text-destructive":""}`,children:M(u.promoContribution)}),e.jsx("td",{className:`text-right font-semibold ${u.negative?"text-destructive":u.belowTarget?"text-yellow-600":"text-green-600"}`,children:_e(u.promoContributionPct)}),!B&&e.jsx("td",{className:"text-right pr-3",children:e.jsx(g,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive",onClick:()=>Xe(n),children:e.jsx(Ke,{className:"h-4 w-4"})})})]},n.id))]})]})})]},a.id)}),e.jsx(Fs,{open:Y,onOpenChange:ie,form:V,setForm:ne,onSave:Re,saving:O}),e.jsx(Pe,{open:pe,onOpenChange:ce,children:e.jsxs(Me,{className:"max-w-lg",children:[e.jsx(Fe,{children:e.jsx(Te,{children:"Bloco da campanha"})}),x&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Nome do bloco"}),e.jsx(A,{value:x.name,onChange:a=>q({...x,name:a.target.value}),placeholder:"Ex.: Curva C — queima de estoque"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Tipo de desconto"}),e.jsxs(U,{value:x.discountType,onValueChange:a=>q({...x,discountType:a}),children:[e.jsx(G,{children:e.jsx(H,{})}),e.jsxs(Q,{children:[e.jsx(v,{value:"pct",children:"Percentual (%)"}),e.jsx(v,{value:"fixed",children:"Valor fixo (R$)"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:x.discountType==="pct"?"Desconto (%)":"Desconto (R$)"}),e.jsx(A,{type:"number",step:"0.01",value:x.discountValue,onChange:a=>q({...x,discountValue:be(a.target.value)})})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border border-border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Frete grátis neste bloco"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Quando ligado, o custo do frete entra como custo variável absorvido pela loja."})]}),e.jsx(Ds,{checked:x.freeShipping,onCheckedChange:a=>q({...x,freeShipping:a})})]}),x.freeShipping&&e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Custo do frete da campanha"}),e.jsx(A,{type:"number",step:"0.01",placeholder:"Usar o custo cadastrado",value:x.freightCost??"",onChange:a=>q({...x,freightCost:a.target.value===""?null:be(a.target.value)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Forma do custo"}),e.jsxs(U,{value:x.freightCostMode,onValueChange:a=>q({...x,freightCostMode:a}),children:[e.jsx(G,{children:e.jsx(H,{})}),e.jsxs(Q,{children:[e.jsx(v,{value:"brl",children:"R$ por pedido"}),e.jsx(v,{value:"pct",children:"% sobre o preço"})]})]})]})]}),e.jsxs(us,{children:[e.jsx(g,{variant:"outline",onClick:()=>ce(!1),children:"Cancelar"}),e.jsxs(g,{onClick:de,disabled:O,className:"gap-2",children:[O&&e.jsx(ue,{className:"h-4 w-4 animate-spin"})," Salvar bloco"]})]})]})]})}),e.jsx(Pe,{open:Ce,onOpenChange:ae,children:e.jsxs(Me,{className:"max-w-2xl",children:[e.jsx(Fe,{children:e.jsx(Te,{children:"Escolher produtos do bloco"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(As,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(A,{className:"pl-8",placeholder:"Buscar por nome ou código da loja (SKU)",value:ee,onChange:a=>X(a.target.value)})]}),e.jsxs(U,{value:le,onValueChange:Ge,children:[e.jsx(G,{className:"w-44",children:e.jsx(H,{})}),e.jsxs(Q,{children:[e.jsx(v,{value:"all",children:"Todas as categorias"}),R.map(a=>e.jsx(v,{value:a,children:a},a))]})]}),e.jsxs(U,{value:ye,onValueChange:Ae,children:[e.jsx(G,{className:"w-36",children:e.jsx(H,{})}),e.jsxs(Q,{children:[e.jsx(v,{value:"all",children:"Todas as curvas"}),e.jsx(v,{value:"A",children:"Curva A"}),e.jsx(v,{value:"B",children:"Curva B"}),e.jsx(v,{value:"C",children:"Curva C"})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[Se.length," produto(s) na busca · ",we.size," selecionado(s)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(g,{size:"sm",variant:"outline",onClick:()=>fe(a=>new Set([...a,...Se.map(d=>d.id)])),children:"Selecionar todos da busca"}),e.jsx(g,{size:"sm",variant:"ghost",onClick:()=>fe(new Set),children:"Limpar seleção"})]})]}),e.jsx("div",{className:"max-h-80 overflow-y-auto divide-y divide-border rounded-md border border-border",children:Se.length===0?e.jsx("p",{className:"p-6 text-center text-sm text-muted-foreground",children:"Nenhum produto encontrado."}):Se.map(a=>e.jsxs("label",{className:"flex items-center gap-3 p-2.5 cursor-pointer hover:bg-muted/40",children:[e.jsx(da,{checked:we.has(a.id),onCheckedChange:d=>fe(n=>{const p=new Set(n);return d?p.add(a.id):p.delete(a.id),p})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm truncate",children:a.name}),e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate",children:[[a.sku,a.category].filter(
6Boolean).join(" · ")||"—"," · Curva ",a.curve]})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:M(a.price)})]},a.id))}),e.jsxs(us,{children:[e.jsx(g,{variant:"outline",onClick:()=>ae(!1),children:"Cancelar"}),e.jsxs(g,{onClick:Ve,disabled:O,className:"gap-2",children:[O&&e.jsx(ue,{className:"h-4 w-4 animate-spin"})," Salvar produtos"]})]})]})]})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Campanhas de precificação"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Reúna produtos em blocos, aplique desconto por bloco e veja o impacto do frete grátis na margem."})]}),!B&&e.jsxs(g,{className:"gap-2",onClick:()=>{ne({id:crypto.randomUUID(),name:"",description:"",status:"draft",startDate:null,endDate:null}),ie(!0)},children:[e.jsx(rs,{className:"h-4 w-4"})," Nova campanha"]})]}),j.length===0?e.jsx(F,{className:"p-8 text-center text-sm text-muted-foreground",children:"Nenhuma campanha criada neste projeto. Crie a primeira para planejar descontos por grupos de produtos."}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:j.map(a=>{const d=P.filter(p=>p.campaignId===a.id),n=D.filter(p=>p.campaignId===a.id).length;return e.jsxs(F,{className:"p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:a.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:a.description||"Sem descrição"})]}),e.jsx(ts,{className:`${Da[a.status]} border text-[10px]`,children:_a[a.status]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[d.length," bloco(s) · ",n," produto(s)",a.startDate?` · de ${a.startDate.split("-").reverse().join("/")}`:"",a.endDate?` até ${a.endDate.split("-").reverse().join("/")}`:""]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsx(g,{size:"sm",variant:"outline",onClick:()=>re(a.id),children:"Abrir"}),!B&&e.jsxs(e.Fragment,{children:[e.jsxs(g,{size:"sm",variant:"ghost",className:"gap-1",onClick:()=>{ne(a),ie(!0)},children:[e.jsx(gs,{className:"h-3.5 w-3.5"})," Editar"]}),e.jsxs(g,{size:"sm",variant:"ghost",className:"gap-1 text-destructive",onClick:()=>He(a.id),children:[e.jsx(Ke,{className:"h-3.5 w-3.5"})," Excluir"]})]})]})]},a.id)})}),e.jsx(Fs,{open:Y,onOpenChange:ie,form:V,setForm:ne,onSave:Re,saving:O})]})}function Fs({open:r,onOpenChange:E,form:k,setForm:I,onSave:_,saving:B}){return e.jsx(Pe,{open:r,onOpenChange:E,children:e.jsxs(Me,{className:"max-w-lg",children:[e.jsx(Fe,{children:e.jsx(Te,{children:"Campanha de precificação"})}),k&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Nome"}),e.jsx(A,{value:k.name,onChange:R=>I({...k,name:R.target.value}),placeholder:"Ex.: Black Friday"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Descrição"}),e.jsx(ma,{rows:2,value:k.description,onChange:R=>I({...k,description:R.target.value}),placeholder:"Objetivo da campanha, público, canais..."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Situação"}),e.jsxs(U,{value:k.status,onValueChange:R=>I({...k,status:R}),children:[e.jsx(G,{children:e.jsx(H,{})}),e.jsxs(Q,{children:[e.jsx(v,{value:"draft",children:"Rascunho"}),e.jsx(v,{value:"active",children:"Ativa"}),e.jsx(v,{value:"archived",children:"Arquivada"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Início"}),e.jsx(A,{type:"date",value:k.startDate??"",onChange:R=>I({...k,startDate:R.target.value||null})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Fim"}),e.jsx(A,{type:"date",value:k.endDate??"",onChange:R=>I({...k,endDate:R.target.value||null})})]})]}),e.jsxs(us,{children:[e.jsx(g,{variant:"outline",onClick:()=>E(!1),children:"Cancelar"}),e.jsxs(g,{onClick:_,disabled:B,className:"gap-2",children:[B&&e.jsx(ue,{className:"h-4 w-4 animate-spin"})," Salvar campanha"]})]})]})]})})}const Ra=[{value:"30",label:"Últimos 30 dias"},{value:"60",label:"Últimos 60 dias"},{value:"90",label:"Últimos 90 dias"},{value:"all",label:"Todo o período com vendas"},{value:"custom",label:"Período personalizado"}],Va={revenue:"Faturamento (R$)",quantity:"Quantidade vendida",margin:"Margem de contribuição (R$)"};function qa({open:r,onOpenChange:E,products:k,costs:I,onApply:_}){const[B,R]=i.useState([]),[m,Z]=i.useState(""),[j,$]=i.useState("90"),[P,f]=i.useState(""),[D,c]=i.useState(""),z=j==="custom",re=!z||!!P&&!!D&&P<=D,[O,N]=i.useState("revenue"),[Y,ie]=i.useState(!1),[V,ne]=i.useState(!1),[pe,ce]=i.useState(!1),[x,q]=i.useState(null);i.useEffect(()=>{r&&(q(null),ie(!0),(async()=>{try{const{data:y,error:ee}=await Ue.functions.invoke("nuvemshop-list-connections");
6if(ee)throw ee;const X=(y==null?void 0:y.connections)??[];R(X),X[0]&&Z(le=>le||X[0].id)}catch(y){h.error("Não foi possível listar as lojas conectadas",{description:y.message})}finally{ie(!1)}})())},[r]),i.useEffect(()=>{q(null)},[m,j,O,P,D]);const Ce=async()=>{if(!(!m||!re)){ne(!0);try{const y=await Vs(m,j==="all"||z?null:Number(j),z?{from:P,to:D}:null),ee=qs(k,y,O,I);q(ee),ee.counts.A===0&&ee.counts.B===0&&h.warning("Nenhuma venda encontrada para os produtos da lista no período escolhido.")}catch(y){h.error("Não foi possível calcular as curvas",{description:y.message})}finally{ne(!1)}}},ae=async()=>{if(x){ce(!0);try{await _(x.next),E(!1)}finally{ce(!1)}}},ve=k.some(y=>!(y.sku||"").trim());return e.jsx(Pe,{open:r,onOpenChange:E,children:e.jsxs(Me,{className:"max-w-2xl",children:[e.jsx(Fe,{children:e.jsx(Te,{children:"Sincronizar Curva ABC com as vendas da loja"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"A curva é recalculada a partir dos pedidos reais já importados da loja. Somente a letra A, B ou C é alterada: custos, preços, markups e campanhas permanecem exatamente como estão."}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(C,{className:"text-xs flex items-center gap-1",children:[e.jsx(as,{className:"h-3 w-3"})," Loja"]}),e.jsxs(U,{value:m,onValueChange:Z,disabled:Y,children:[e.jsx(G,{children:e.jsx(H,{placeholder:Y?"Carregando...":"Selecione a loja"})}),e.jsx(Q,{children:B.map(y=>e.jsx(v,{value:y.id,children:y.store_name||y.name||"Loja conectada"},y.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Período"}),e.jsxs(U,{value:j,onValueChange:$,children:[e.jsx(G,{children:e.jsx(H,{})}),e.jsx(Q,{children:Ra.map(y=>e.jsx(v,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Critério"}),e.jsxs(U,{value:O,onValueChange:y=>N(y),children:[e.jsx(G,{children:e.jsx(H,{})}),e.jsxs(Q,{children:[e.jsx(v,{value:"revenue",children:"Por faturamento (recomendado)"}),e.jsx(v,{value:"quantity",children:"Por quantidade vendida"}),e.jsx(v,{value:"margin",children:"Por margem de contribuição"})]})]})]})]}),z&&e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"De"}),e.jsx("input",{type:"date",value:P,max:D||void 0,onChange:y=>f(y.target.value),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Até"}),e.jsx("input",{type:"date",value:D,min:P||void 0,onChange:y=>c(y.target.value),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"})]}),e.jsx("p",{className:"text-xs text-muted-foreground sm:col-span-2",children:"Use para comparar sazonalidades (ex.: Black Friday, Natal, Dia das Mães). As datas seguem o horário de Brasília."})]}),O==="margin"&&e.jsx(F,{className:"p-3 border-yellow-500/40 bg-yellow-500/5 text-xs text-muted-foreground",children:"A margem usa o faturamento do período menos o custo de compra do item e os custos variáveis. Produtos sem custo de compra informado ficam como Curva C até o custo ser preenchido."}),ve&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Produtos sem código da loja (SKU) são comparados pelo nome. Se o nome não bater com o da loja, o item fica como C."}),x&&e.jsxs(F,{className:"p-4 space-y-3",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Prévia do impacto — ",Va[O]]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"rounded-md border border-green-500/30 bg-green-500/10 p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Curva A"}),e.jsx("p",{className:"text-lg font-semibold text-green-600",children:x.counts.A})]}),e.jsxs("div",{className:"rounded-md border border-yellow-500/30 bg-yellow-500/10 p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Curva B"}),e.jsx("p",{className:"text-lg font-semibold text-yellow-700",children:x.counts.B})]}),e.jsxs("div",{className:"rounded-md border border-red-500/30 bg-red-500/10 p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Curva C"}),e.jsx("p",{className:"text-lg font-semibold text-red-600",children:x.counts.C})]})]}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("li",{children:[x.changed," produto(s) mudam de curva."]}),e.jsxs("li",{children:[x.withoutSales," produto(s) sem vendas no período — ficam como C."]}),O==="margin"&&e.jsxs("li",{children:[x.withoutCost," produto(s) sem custo informado — considerados C por au
6sência de margem."]}),O!=="quantity"&&e.jsxs("li",{children:["Base total considerada: ",M(x.totalValue),"."]})]})]}),e.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[e.jsx(g,{variant:"outline",onClick:()=>E(!1),disabled:pe,children:"Cancelar"}),e.jsxs(g,{variant:"outline",className:"gap-2",onClick:Ce,disabled:!m||!re||V||pe,children:[V?e.jsx(ue,{className:"h-4 w-4 animate-spin"}):e.jsx(Ls,{className:"h-4 w-4"}),x?"Recalcular prévia":"Calcular prévia"]}),e.jsxs(g,{className:"gap-2",onClick:ae,disabled:!x||pe||V,children:[pe&&e.jsx(ue,{className:"h-4 w-4 animate-spin"}),"Aplicar curvas"]})]})]})]})})}const je=Ue,La={A:"bg-green-500/15 text-green-600 border-green-500/30",B:"bg-yellow-500/15 text-yellow-700 border-yellow-500/30",C:"bg-red-500/15 text-red-600 border-red-500/30"},Ts=["Nome","SKU","Categoria","Curva","Custo do Produto","Forma (markup|preco|margem)","Markup","Preco de Venda","Margem Alvo (%)"],za=r=>{const E=(r||"").toString().trim().toLowerCase();return E.startsWith("pre")?"price":E.startsWith("mar")&&E!=="markup"?"margin":"markup"},ds={markup:"Markup",price:"Preço direto",margin:"Margem alvo"},Oa=r=>({id:r.id,name:r.name??"",sku:r.sku??"",category:r.category??"",curve:r.curve??"C",productCost:Number(r.product_cost??0),method:r.method??"markup",markup:Number(r.markup??0),price:Number(r.price??0),targetMarginPct:r.target_margin_pct===null||r.target_margin_pct===void 0?null:Number(r.target_margin_pct),costOverrides:r.cost_overrides??{},source:r.source??"manual",position:Number(r.position??0)}),Ka=(r,E,k,I)=>({id:r.id,user_id:I??E,program_id:k,name:r.name,sku:r.sku||null,category:r.category||null,curve:r.curve,product_cost:r.productCost,method:r.method,markup:r.markup,price:r.price,target_margin_pct:r.targetMarginPct,cost_overrides:r.costOverrides,source:r.source,position:r.position});function St(){const{user:r}=ua(),{view_only:E}=va("pricing"),{isAdmin:k,isConsultingAdmin:I,isConsultingClient:_,consultingClientId:B}=pa(),R=_&&!k&&!I,m=!!E,Z=i.useRef(new Map),j=i.useRef(null),[$,P]=i.useState(null);i.useEffect(()=>{if(!R||!B||$)return;let s=!1;return Ue.from("consulting_client_programs").select("program_id").eq("client_id",B).limit(1).then(({data:t})=>{var o;!s&&t&&((o=t[0])!=null&&o.program_id)&&P(t[0].program_id)}),()=>{s=!0}},[R,B,$]);const[f,D]=i.useState(Ss),[c,z]=i.useState(20),[re,O]=i.useState(null),[N,Y]=i.useState([]),[ie,V]=i.useState(!0),[ne,pe]=i.useState(!1),[ce,x]=i.useState(null),[q,Ce]=i.useState("all"),[ae,ve]=i.useState("all"),[y,ee]=i.useState(""),[X,le]=i.useState([]),[Ge,ye]=i.useState(!1),[Ae,we]=i.useState(""),[fe,De]=i.useState(!1),[K,Be]=i.useState(""),[Re,He]=i.useState(""),[de,os]=i.useState("markup"),[Qe,Se]=i.useState(""),[Ve,Xe]=i.useState(""),[xe,Ee]=i.useState("C"),[W,qe]=i.useState(!1),[We,is]=i.useState([]),[a,d]=i.useState(""),[n,p]=i.useState(!1),[u,L]=i.useState(!1),J=i.useCallback(async()=>{if(r){V(!0);try{let s=je.from("pricing_settings").select("*");s=$?s.eq("program_id",$):s.eq("user_id",r.id).is("program_id",null);const{data:t}=await s,o=t??[],l=o.find(T=>T.user_id===r.id)??o[0]??null;l?(O(l.id),j.current=l.user_id,D(Pa(l.variable_costs)),z(Number(l.target_margin_pct??20)),le(Array.isArray(l.categories)?l.categories:[])):(O(null),j.current=null,D(Ss),z(20),le([]));let b=je.from("pricing_products").select("*");b=$?b.eq("program_id",$):b.eq("user_id",r.id).is("program_id",null);const{data:S}=await b.order("position",{ascending:!0}).order("created_at",{ascending:!0});Z.current=new Map((S??[]).map(T=>[T.id,T.user_id])),Y((S??[]).map(Oa))}catch(s){h.error("Erro ao carregar precificação",{description:s.message})}finally{V(!1)}}},[r,$]);i.useEffect(()=>{J()},[J]);const vs=async s=>{if(!r)throw new Error("Sessão expirada");const t={user_id:j.current??r.id,program_id:$,variable_costs:f,target_margin_pct:c,categories:(s==null?void 0:s.categories)??X};if(re){const{error:o}=await je.from("pricing_settings").update(t).eq("id",re);if(o)throw o}else{const{data:o,error:l}=await je.from("pricing_settings").insert(t).select("id").single();if(l)throw l;O(o.id)}},Os=async()=>
6{if(!(!r||m)){pe(!0);try{await vs(),h.success("Custos variáveis salvos")}catch(s){h.error("Erro ao salvar custos",{description:s.message})}finally{pe(!1)}}},fs=async s=>{De(!0);try{await vs({categories:s}),le(s)}catch(t){h.error("Erro ao salvar categorias",{description:t.message})}finally{De(!1)}},Ns=async()=>{const s=Ae.trim();if(s){if(X.some(t=>t.toLowerCase()===s.toLowerCase())){h.error("Categoria já existe neste projeto");return}await fs([...X,s].sort((t,o)=>t.localeCompare(o,"pt-BR"))),we(""),h.success("Categoria criada")}},Ks=async s=>{await fs(X.filter(t=>t!==s)),q===s&&Ce("all"),Ve===s&&Xe(""),h.success("Categoria removida")},Ze=async s=>{if(!r)return;const t=s.map(l=>Ka(l,r.id,$,Z.current.get(l.id))),{error:o}=await je.from("pricing_products").upsert(t);o&&h.error("Erro ao salvar produtos",{description:o.message})},Le=s=>{Y(t=>t.some(l=>l.id===s.id)?t.map(l=>l.id===s.id?s:l):[...t,s]),Ze([s])},Us=async s=>{Y(o=>o.filter(l=>l.id!==s));const{error:t}=await je.from("pricing_products").delete().eq("id",s);t?h.error("Erro ao excluir",{description:t.message}):h.success("Produto removido")},Gs=()=>{if(!K.trim()){h.error("Informe o nome do produto");return}const s=be(Re),t=be(Qe),o={...ls(N.length),name:K.trim(),category:Ve.trim(),curve:xe,productCost:s,method:de,markup:de==="markup"?t||2.5:0,price:de==="price"?t:0,targetMarginPct:de==="margin"?t||c:null},l=ke(o,f,c);Le({...o,price:l.price}),Be(""),He(""),Se(""),h.success("Produto incluído na lista")},Hs=(s,t)=>{const o={...s,method:"price",price:t,targetMarginPct:null};Le(o)},Qs=(s,t)=>{const o={...s,method:"margin",targetMarginPct:t};o.price=Ma(o.productCost,ke(o,f,c).costs,t),Le(o)},Xs=(s,t)=>
6{const o={...s,productCost:t};o.price=ke(o,f,c).price,Le(o)},Ws=()=>{const s=N.map(t=>{const o={...t,method:"margin",targetMarginPct:null};return o.price=ke(o,f,c).price,o});Y(s),Ze(s),h.success("Preços sugeridos pela margem alvo aplicados")},Zs=()=>{const s=me.aoa_to_sheet([Ts,["Camiseta Basica","CAM-001","Vestuario","A",35,"markup",2.5,"",""],["Tenis Runner","TEN-010","Calcados","B",180,"preco","",399.9,""],["Boné Trucker","BON-003","Acessorios","C",22,"margem","","",25]]);s["!cols"]=Ts.map(()=>({wch:22}));const t=me.book_new();me.book_append_sheet(t,s,"Produtos"),ms(t,"modelo-precificacao.xlsx")},Js=async s=>{try{const t=await s.arrayBuffer(),o=xa(t,{type:"array"}),l=me.sheet_to_json(o.Sheets[o.SheetNames[0]],{defval:""}),b=[];if(l.forEach((S,T)=>{const w=String(S.Nome??S.nome??"").trim();if(!w)return;const Oe=za(String(S["Forma (markup|preco|margem)"]??S.Forma??"markup")),oe={...ls(N.length+T),name:w,sku:String(S.SKU??"").trim(),category:String(S.Categoria??"").trim(),curve:["A","B","C"].includes(String(S.Curva).toUpperCase())?String(S.Curva).toUpperCase():"C",productCost:be(S["Custo do Produto"]),method:Oe,markup:be(S.Markup)||2.5,price:be(S["Preco de Venda"]??S["Preço de Venda"]),targetMarginPct:S["Margem Alvo (%)"]===""?null:be(S["Margem Alvo (%)"]),source:"sheet"};oe.price=ke(oe,f,c).price,b.push(oe)}),b.length===0){h.error("Nenhum produto válido encontrado na planilha");return}Y(S=>[...S,...b]),await Ze(b),h.success(`${b.length} produto(s) importado(s) da planilha`)}catch(t){h.error("Falha ao ler a planilha",{description:t.message})}},Ys=async()=>{qe(!0);try{const{data:s,error:t}=await Ue.functions.invoke("nuvemshop-list-connections");if(t)throw t;const o=(s==null?void 0:s.connections)??[];is(o),o[0]&&d(o[0].id)}catch(s){h.error("Não foi possível listar as lojas conectadas",{description:s.message})}},ea=async()=>{if(a){p(!0);try{const[{data:s},{data:t}]=await Promise.all([je.from("ns_product_variants").select("ns_variant_id, ns_product_id, sku, price_cents, promo_price_cents, cost_cents").eq("connection_id",a).limit(5e3),je.from("ns_products").select("ns_product_id, name").eq("connection_id",a).limit(5e3)]),o=new Map((t??[]).map(w=>[w.ns_product_id,w.name])),l=new Set(N.map(w=>(w.sku||w.name).toLowerCase())),b=[];if((s??[]).forEach((w,Oe)=>{const oe=w.sku||`SKU#${w.ns_variant_id}`,oa=o.get(w.ns_product_id)||oe;if(l.has(oe.toLowerCase()))return;const ia=Number(w.promo_price_cents??0)>0?Number(w.promo_price_cents)/100:Number(w.price_cents??0)/100;b.push({...ls(N.length+Oe),name:oa,sku:oe,category:"",productCost:Number(w.cost_cents??0)/100,method:"price",markup:0,price:ia,source:"ecommerce"})}),b.length===0){h.error("Nenhum produto novo encontrado na loja selecionada");return}let S=b;try{const w=await Vs(a,90),{next:Oe}=qs(b,w,"revenue",f);S=b.map(oe=>({...oe,curve:Oe.get(oe.id)??oe.curve}))}catch{}Y(w=>[...w,...S]),await Ze(S),qe(!1);const T=S.filter(w=>w.productCost<=0).length;h.success(`${S.length} produto(s) importado(s) da loja`,{description:T>0?`${T} item(ns) sem custo cadastrado — informe o custo para calcular a margem.`:void 0})}catch(s){h.error("Erro ao importar da loja",{description:s.message})}finally{p(!1)}}},sa=async s=>{const t=N.filter(l=>(s.get(l.id)??l.curve)!==l.curve);if(t.length===0){h.info("As curvas já estão atualizadas");return}const o=N.map(l=>({...l,curve:s.get(l.id)??l.curve}));Y(o),ns(1);try{const l={A:[],B:[],C:[]};t.forEach(b=>l[s.get(b.id)].push(b.id));for(const b of Object.keys(l)){const S=l[b];for(let T=0;T<S.length;T+=200){const{error:w}=await je.from("pricing_products").update({curve:b}).in("id",S.slice(T,T+200));if(w)throw w}}h.success(`Curva ABC atualizada em ${t.length} produto(s)`)}catch(l){h.error("Erro ao salvar as curvas",{description:l.message}),J()}},he=i.useMemo(()=>N.map(s=>({p:s,r:ke(s,f,c)})),[N,f,c]),Je=i.useMemo(()=>Array.from(new Set([...X,...N.map(s=>s.category).filter(Boolean)])).sort((s,t)=>s.localeCompare(t,"pt-BR")),[N,X]),Ye=y.trim().toLowerCase(),bs={A:0,B:1,C:2},[se,ze]=i.useState("all"),Ie=he.filter(({p:s,r:t})=>{const o=s.targetMarginPct??c;return(se==="all"||se==="onTarget"&&t.contributionPct>=o||se==="below"&&t.contributionPct<o&&t.contribution>=0||se==="negative"&&t.contribution<0)&&(q==="all"||s.category===q)&&(ae==="all"||s.curve===ae)&&(!Ye||s.name.toLowerCase().includes(Ye)||(s.sku||"").toLowerCase().includes(Ye))}).sort((s,t)=>(bs[s.p.curve]??3)-(bs[t.p.curve]??3)||s.p.name.localeCompare(t.p.name,"pt-BR")),$e=50,[aa,ns]=i.useState(1),Cs=i.useRef(null);i.useEffect(()=>{ns(1)},[y,q,ae,se,N.length]);const cs=Math.max(1,Math.ceil(Ie.length/$e)),ge=Math.min(aa,cs),ys=Ie.slice((ge-1)*$e,ge*$e),ws=s=>{var t;ns(s),(t=Cs.current)==null||t.scrollIntoView({behavior:"auto",block:"start"})},Ne=i.useMemo(()=>{const s=he.filter(({r:T})=>T.price>0),t=s.length?s.reduce((T,w)=>T+w.r.contributionPct,0)/s.length:0,o=he.filter(({p:T,r:w})=>
6w.contributionPct<(T.targetMarginPct??c)&&w.contribution>=0).length,l=he.filter(({r:T})=>T.contribution<0).length,b=he.filter(({p:T,r:w})=>w.contributionPct>=(T.targetMarginPct??c)).length,S=he.filter(({r:T})=>T.pendingCost).length;return{avgMargin:t,below:o,negative:l,onTarget:b,pending:S}},[he,c]),ta=()=>{const s=Es("Precificação por Margem de Contribuição");let t=45;t=Is(s,[{label:"Produtos",value:String(N.length)},{label:"Margem média",value:_e(Ne.avgMargin)},{label:"Margem alvo",value:`${c}%`},{label:"Abaixo da meta",value:String(Ne.below)}],t),t=ps(s,"Custos variáveis considerados",t),t=xs(s,[{header:"Custo",dataKey:"c"},{header:"Valor",dataKey:"v",halign:"right"}],hs.map(o=>({c:o.label,v:(o.key==="custoFrete"?f.custoFreteMode==="pct":o.type==="pct")?`${f[o.key]}%`:M(f[o.key])})),t),t=ps(s,"Produtos precificados",t),xs(s,[{header:"Produto",dataKey:"n"},{header:"Forma",dataKey:"m"},{header:"Custo",dataKey:"c",halign:"right"},{header:"Preço",dataKey:"p",halign:"right"},{header:"MC R$",dataKey:"mc",halign:"right"},{header:"MC %",dataKey:"pct",halign:"right"}],he.map(({p:o,r:l})=>({n:o.name,m:ds[o.method],c:M(o.productCost),p:M(l.price),mc:M(l.contribution),pct:_e(l.contributionPct)})),t),$s(s,"precificacao")},ra=()=>{const s=me.json_to_sheet(he.map(({p:o,r:l})=>({Nome:o.name,SKU:o.sku,Categoria:o.category,Curva:o.curve,"Custo do Produto":o.productCost,"Forma (markup|preco|margem)":ds[o.method],Markup:Number(l.markup.toFixed(2)),"Preco de Venda":Number(l.price.toFixed(2)),Deducoes:Number(l.deductions.total.toFixed(2)),"Margem Contribuicao R$":Number(l.contribution.toFixed(2)),"Margem Contribuicao %":Number(l.contributionPct.toFixed(2))}))),t=me.book_new();me.book_append_sheet(t,s,"Precificacao"),ms(t,"precificacao.xlsx")};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-display font-semibold",children:"Precificação"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Defina os custos variáveis uma única vez e precifique por markup, preço direto ou margem de contribuição alvo."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Na,{value:$,onChange:P}),e.jsx(ba,{toolId:"pricing"}),e.jsxs(g,{variant:"outline",size:"sm",className:"gap-2",onClick:ra,disabled:N.length===0,children:[e.jsx(js,{className:"h-4 w-4"})," Excel"]}),e.jsxs(g,{variant:"outline",size:"sm",className:"gap-2",onClick:ta,disabled:N.length===0,children:[e.jsx(Rs,{className:"h-4 w-4"})," PDF"]})]})]}),e.jsx(fa,{toolId:"pricing"}),ie?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(ue,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(ha,{defaultValue:"products",children:[e.jsxs(ga,{children:[e.jsxs(es,{value:"products",children:["Produtos (",N.length,")"]}),e.jsx(es,{value:"campaigns",children:"Campanhas"}),e.jsx(es,{value:"import",children:"Importar"}),e.jsx(es,{value:"costs",children:"Custos variáveis"})]}),e.jsx(ss,{value:"campaigns",className:"mt-4",children:e.jsx(Ba,{products:N,costs:f,target:c,programId:$,userId:r==null?void 0:r.id,readOnly:m,categories:Je})}),e.jsx(ss,{value:"costs",className:"mt-4 space-y-4",children:e.jsxs(F,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Custos variáveis da operação"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tudo que incide sobre a venda, exceto o custo de compra/produção do produto. Serve de base para todos os itens da lista."})]}),e.jsx(zs,{costs:f,disabled:m,onChange:(s,t)=>D(o=>({...o,[s]:t})),onFreteModeChange:s=>D(t=>({...t,custoFreteMode:s}))}),e.jsxs("div",{className:"flex flex-wrap items-end gap-4 border-t border-border pt-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(C,{className:"text-xs flex items-center gap-1",children:[e.jsx(ks,{className:"h-3 w-3"})," Margem de contribuição alvo (%)"]}),e.jsx(A,{type:"number",step:"0.1",className:"w-40",disabled:m,value:c,onChange:s=>
6z(parseFloat(s.target.value)||0)})]}),e.jsxs(g,{onClick:Os,disabled:m||ne,className:"gap-2",children:[ne?e.jsx(ue,{className:"h-4 w-4 animate-spin"}):e.jsx(Bs,{className:"h-4 w-4"}),"Salvar custos"]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs(g,{variant:"outline",onClick:Ws,disabled:m||N.length===0,className:"gap-2",children:[e.jsx(ks,{className:"h-4 w-4"})," Sugerir preços por margem alvo"]}),e.jsx("p",{className:"text-xs text-muted-foreground max-w-md",children:m?"Indisponível no modo somente leitura.":N.length===0?"Disponível após cadastrar pelo menos um produto na aba Produtos.":"Recalcula o preço de todos os produtos para atingir a margem alvo acima, considerando o custo de cada item e os custos variáveis. Margens individuais são substituídas pela margem alvo."})]})]})]})}),e.jsxs(ss,{value:"products",className:"mt-4 space-y-4",children:[!m&&e.jsxs(F,{className:"p-4 space-y-3",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Incluir produto"}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-7 items-end",children:[e.jsxs("div",{className:"space-y-1.5 lg:col-span-2",children:[e.jsx(C,{className:"text-xs",children:"Nome"}),e.jsx(A,{value:K,onChange:s=>Be(s.target.value),placeholder:"Nome do produto"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Custo (R$)"}),e.jsx(A,{type:"number",step:"0.01",value:Re,onChange:s=>He(s.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Forma"}),e.jsxs(U,{value:de,onValueChange:s=>os(s),children:[e.jsx(G,{children:e.jsx(H,{})}),e.jsxs(Q,{children:[e.jsx(v,{value:"markup",children:"Markup"}),e.jsx(v,{value:"price",children:"Preço direto"}),e.jsx(v,{value:"margin",children:"Margem alvo"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:de==="markup"?"Markup (x)":de==="price"?"Preço (R$)":"Margem (%)"}),e.jsx(A,{type:"number",step:"0.01",value:Qe,onChange:s=>Se(s.target.value),placeholder:de==="margin"?String(c):""})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 gap-2",children:[e.jsx(C,{className:"text-xs",children:"Categoria"}),e.jsx("button",{type:"button",className:"text-[11px] text-primary hover:underline",onClick:()=>ye(!0),children:"Gerenciar"})]}),e.jsxs(U,{value:Ve||"none",onValueChange:s=>Xe(s==="none"?"":s),children:[e.jsx(G,{children:e.jsx(H,{placeholder:"Sem categoria"})}),e.jsxs(Q,{children:[e.jsx(v,{value:"none",children:"Sem categoria"}),Je.map(s=>e.jsx(v,{value:s,children:s},s))]})]})]}),e.jsxs(g,{onClick:Gs,className:"gap-2",children:[e.jsx(rs,{className:"h-4 w-4"})," Incluir"]})]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-5",children:[e.jsxs(F,{className:`p-3 cursor-pointer transition-colors hover:border-primary/50 ${se==="all"?"border-primary ring-1 ring-primary/30":""}`,onClick:()=>ze("all"),title:"Mostrar todos os produtos, sem filtro de margem",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Produtos"}),e.jsx("p",{className:"text-lg font-semibold",children:N.length})]}),e.jsxs(F,{className:"p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Margem média"}),e.jsx("p",{className:"text-lg font-semibold",children:_e(Ne.avgMargin)})]}),e.jsxs(F,{className:`p-3 cursor-pointer transition-colors hover:border-primary/50 ${se==="onTarget"?"border-primary ring-1 ring-primary/30":""}`,onClick:()=>ze(se==="onTarget"?"all":"onTarget"),title:"Produtos cuja margem de contribuição atinge ou supera a meta",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Na meta ou +"}),e.jsx("p",{className:"text-lg font-semibold text-emerald-600",children:Ne.onTarget})]}),e.jsxs(F,{className:`p-3 cursor-pointer transition-colors hover:border-primary/50 ${se==="below"?"border-primary ring-1 ring-primary/30":""}`,onClick:()=>ze(se==="below"?"all":"below"),title:"Produtos com margem positiva, mas abaixo da meta",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Abaixo da meta"}),e.jsx("p",{className:"text-lg font-semibold text-yellow-600",children:Ne.below})]}),e.jsxs(F,{className:`p-3 cursor-pointer transition-colors hover:border-primary/50 ${se==="negative"?"border-primary ring-1 ring-primary/30":""}`,onClick:()=>ze(se==="negative"?"all":"negative"),title:"Produtos cuja margem de contribuição é negativa (prejuízo por venda)",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Margem negativa"}),e.jsx("p",{className:"text-lg font-semibold text-destructive",children:Ne.negative})]})]}),Ne.pending>0&&e.jsxs(F,{className:"p-3 border-yellow-500/40 bg-yellow-500/5 text-sm",children:[Ne.pending," produto(s) ainda sem custo de compra informado — a margem só aparece após preencher o custo."]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px] max-w-md",children:[e.jsx(As,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(A,{className:"pl-8",placeholder:"Buscar por nome ou código da loja (SKU)",value:y,onChange:s=>ee(s.target.value)})]}),e.jsxs(U,{value:q,onValueChange:Ce,children:[e.jsx(G,{className:"w-52",children:e.jsx(H,{placeholder:"Categoria"})}),e.jsxs(Q,{children:[e.jsx(v,{value:"all",children:"Todas as categorias"}),Je.map(s=>e.jsx(v,{value:s,children:s},s))]})]}),e.jsxs(U,{value:ae,onValueChange:ve,children:[e.jsx(G,{className:"w-40",children:e.jsx(H,{placeholder:"Curva"})}),e.jsxs(Q,{children:[e.jsx(v,{value:"all",children:"Todas as curvas"}),e.jsx(v,{value:"A",children:"Curva A"}),e.jsx(v,{value:"B",children:"Curva B"}),e.jsx(v,{value:"C",children:"Curva C"})]})]}),(Ye||q!=="all"||ae!=="all"||se!=="all")&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[Ie.length," de ",N.length," produto(s)"]}),e.jsx("button",{type:"button",className:"text-primary hover:underline",onClick:()=>{ee(""),Ce("all"),ve("all"),ze("all")},children:"Limpar filtros"})]}),!m&&e.jsxs(g,{variant:"outline",className:"gap-2",onClick:()=>L(!0),disabled:N.length===0,children:[e.jsx(Ls,{className:"h-4 w-4"})," Sincronizar Curva ABC"]})]}),e.jsx("div",{ref:Cs}),e.jsx(F,{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-xs text-muted-foreground border-b",children:[e.jsx("th",{className:"text-left p-3",children:"Produto"}),e.jsx("th",{className:"text-left",children:"Forma"}),e.jsx("th",{className:"text-right",children:"Custo (R$)"}
6),e.jsx("th",{className:"text-right",children:"Preço (R$)"}),e.jsx("th",{className:"text-right",children:"Deduções"}),e.jsx("th",{className:"text-right",children:"MC R$"}),e.jsx("th",{className:"text-right",children:"MC %"}),e.jsx("th",{className:"text-right pr-3",children:"Ações"})]})}),e.jsxs("tbody",{children:[ys.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:8,className:"p-6 text-center text-muted-foreground",children:"Nenhum produto na lista."})}),ys.map(({p:s,r:t})=>{const o=s.targetMarginPct??c;return e.jsxs("tr",{className:"border-b border-border/50",children:[e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{className:`${La[s.curve]} border text-[10px]`,children:s.curve}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate max-w-[220px]",children:s.name}),e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate max-w-[220px]",children:[[s.sku,s.category].filter(Boolean).join(" · ")||"—",s.source==="ecommerce"&&" · loja"]})]})]})}),e.jsx("td",{className:"text-xs text-muted-foreground",children:ds[s.method]}),e.jsx("td",{className:"text-right",children:e.jsx(A,{type:"number",step:"0.01",disabled:m,className:`h-8 w-24 text-right ml-auto ${t.pendingCost?"border-yellow-500":""}`,defaultValue:s.productCost,onBlur:l=>{const b=parseFloat(l.target.value)||0;b!==s.productCost&&Xs(s,b)}})}),e.jsx("td",{className:"text-right",children:e.jsx(A,{type:"number",step:"0.01",disabled:m,className:"h-8 w-28 text-right ml-auto",defaultValue:Number(t.price.toFixed(2)),onBlur:l=>{const b=parseFloat(l.target.value)||0;Math.abs(b-t.price)>.001&&Hs(s,b)}},`price-${s.id}-${t.price.toFixed(2)}`)}),e.jsx("td",{className:"text-right text-muted-foreground",children:M(t.deductions.total)}),e.jsx("td",{className:`text-right font-medium ${t.contribution>=0?"":"text-destructive"}`,children:M(t.contribution)}),e.jsx("td",{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx("span",{className:`font-semibold ${t.contribution<0?"text-destructive":t.contributionPct<o?"text-yellow-600":"text-green-600"}`,children:_e(t.contributionPct)}),e.jsx(A,{type:"number",step:"0.1",disabled:m,title:"Margem alvo deste produto",className:"h-8 w-20 text-right",defaultValue:s.targetMarginPct??"",placeholder:String(c),onBlur:l=>{if(l.target.value==="")return;const b=parseFloat(l.target.value)||0;b!==s.targetMarginPct&&Qs(s,b)}},`t-${s.id}-${s.targetMarginPct??"g"}`)]})}),e.jsxs("td",{className:"text-right pr-3",children:[e.jsx(g,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>x(s),children:e.jsx(gs,{className:"h-4 w-4"})}),!m&&e.jsx(g,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>Us(s.id),children:e.jsx(Ke,{className:"h-4 w-4"})})]})]},s.id)})]})]})}),Ie.length>$e&&e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Exibindo ",(ge-1)*$e+1,"–",Math.min(ge*$e,Ie.length)," de ",Ie.length," produto(s)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(g,{variant:"outline",size:"sm",className:"h-8 gap-1",disabled:ge<=1,onClick:()=>ws(ge-1),children:[e.jsx(Fa,{className:"h-4 w-4"})," Anterior"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Página ",ge," de ",cs]}),e.jsxs(g,{variant:"outline",size:"sm",className:"h-8 gap-1",disabled:ge>=cs,onClick:()=>ws(ge+1),children:["Próxima ",e.jsx(Ta,{className:"h-4 w-4"})]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ao editar o preço, a margem de contribuição é recalculada automaticamente. Ao informar uma margem alvo na linha, o preço é sugerido para atingi-la."})]}),e.jsxs(ss,{value:"import",className:"mt-4 grid gap-4 md:grid-cols-2",children:[e.jsxs(F,{className:"p-5 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(js,{className:"h-4 w-4"})," Planilha de produtos"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Baixe o modelo, preencha com seus produtos e envie para precificar tudo de uma vez. Os custos variáveis globais são aplicad
6os automaticamente."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(g,{variant:"outline",className:"gap-2",onClick:Zs,children:[e.jsx(Aa,{className:"h-4 w-4"})," Baixar planilha modelo"]}),e.jsx(g,{asChild:!0,className:"gap-2",disabled:m,children:e.jsxs("label",{children:[e.jsx(Ea,{className:"h-4 w-4"})," Enviar planilha",e.jsx("input",{type:"file",accept:".xlsx,.xls,.csv",className:"hidden",disabled:m,onChange:s=>{var o;const t=(o=s.target.files)==null?void 0:o[0];t&&Js(t),s.currentTarget.value=""}})]})})]})]}),e.jsxs(F,{className:"p-5 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(as,{className:"h-4 w-4"})," Exportar da sua loja"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Traga os produtos e os preços praticados na loja conectada e veja a margem de contribuição alcançada com os custos variáveis informados. Itens sem custo cadastrado entram sinalizados para você preencher."}),e.jsxs(g,{variant:"outline",className:"gap-2",onClick:Ys,disabled:m,children:[e.jsx(as,{className:"h-4 w-4"})," Importar produtos do e-commerce"]})]})]})]}),e.jsx($a,{product:ce,globalCosts:f,globalTarget:c,categories:Je,readOnly:m,onClose:()=>x(null),onSave:s=>{Le(s),x(null),h.success("Produto atualizado")}}),e.jsx(Pe,{open:W,onOpenChange:qe,children:e.jsxs(Me,{className:"max-w-md",children:[e.jsx(Fe,{children:e.jsx(Te,{children:"Importar do e-commerce"})}),We.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhuma loja conectada. Conecte uma loja na ferramenta de E-commerce antes de importar."}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(C,{className:"text-xs",children:"Loja"}),e.jsxs(U,{value:a,onValueChange:d,children:[e.jsx(G,{children:e.jsx(H,{placeholder:"Selecione a loja"})}),e.jsx(Q,{children:We.map(s=>e.jsx(v,{value:s.id,children:s.store_name||s.store_url||`Loja ${s.ns_store_id}`},s.id))})]})]}),e.jsxs(g,{className:"w-full gap-2",onClick:ea,disabled:n||!a,children:[n?e.jsx(ue,{className:"h-4 w-4 animate-spin"}):e.jsx(as,{className:"h-4 w-4"})," Importar produtos"]})]})]})}),e.jsx(Pe,{open:Ge,onOpenChange:ye,children:e.jsxs(Me,{className:"max-w-md",children:[e.jsx(Fe,{children:e.jsx(Te,{children:"Categorias do projeto"})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"As categorias criadas aqui valem apenas para este projeto e não afetam os demais."}),!m&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(A,{value:Ae,onChange:s=>we(s.target.value),onKeyDown:s=>{s.key==="Enter"&&(s.preventDefault(),Ns())},placeholder:"Nova categoria"}),e.jsxs(g,{onClick:Ns,disabled:fe||!Ae.trim(),className:"gap-2",children:[fe?e.jsx(ue,{className:"h-4 w-4 animate-spin"}):e.jsx(rs,{className:"h-4 w-4"})," Criar"]})]}),e.jsx("div",{className:"max-h-64 overflow-y-auto divide-y divide-border",children:X.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-3",children:"Nenhuma categoria cadastrada neste projeto."}):X.map(s=>{const t=N.filter(o=>o.category===s).length;return e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 gap-3 py-2",children:[e.jsxs("span",{className:"text-sm",children:[s," ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",t,")"]})]}),!m&&e.jsx(g,{variant:"ghost",size:"icon",disabled:fe,onClick:()=>Ks(s),children:e.jsx(Ke,{className:"h-4 w-4 text-destructive"})})]},s)})})]})}),e.jsx(qa,{open:u,onOpenChange:L,products:N,costs:f,onApply:sa})]})}export{St 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.