PageSourceSearch

https://app.stoqui.com.br/assets/AttributeEditPage-BDAS09EZ.js

js stoqui.com.br collected 2026-09-24 11:58:32 UTC 24,857 bytes, 23 lines download raw bytes

1var rt=Object.defineProperty;var ot=(r,o,t)=>o in r?rt(r,o,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[o]=t;var ce=(r,o,t)=>(ot(r,typeof o!="symbol"?o+"":o,t),t);import{j as e,X as W,ai as U,Z as B,aN as at,aO as ee,T as j,a7 as f,af as st,ag as ve,ah as ye,ay as de,O as Q,N as q,I as oe,ab as ae,H as ue,Q as we,ap as Ae,aw as it,aq as nt,as as lt,az as ct,ac as R,at as Ce,n as G,ar as $,R as dt,ao as P,z as Ie,q as ut}from"./mui-CRsYZxVY.js";import{r as x,b as ht}from"./vendor-Dwao9eNC.js";import{u as xe,w as E,t as _e,l as De,m as me,bf as te,aI as xt,J as mt,b as pt,dV as bt,dW as Se,dX as ft,T as gt,dY as jt,dZ as vt,d_ as yt,d$ as wt,bG as Ct,bT as St,e1 as Et,e2 as kt,cZ as Ee,e3 as At,e4 as It}from"./index-TALscxEc.js";import{u as Oe,a as V,b as K}from"./query-8ViTdhdk.js";import{P as _t}from"./ProductAvatar-BTM6y7KS.js";import{S as pe}from"./SwatchChip-BfTakq5s.js";import{aB as Dt,a0 as Ot,aC as qt,aD as Tt,M as qe,b as re,e as he,d as Ft,D as ke,G as Lt}from"./icons-D8aatgQ4.js";import{c as Te}from"./colorService-BFHRdnHk.js";import{L as se}from"./lab-DSem1Osk.js";import"./datePickers-BIJXYOKG.js";(function(){try{var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};r.SENTRY_RELEASE={id:"2ad85febf9735404429b0670d4acf56a0af5a0a2"}}catch{}})();try{(function(){var r=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},o=new r.Error().stack;o&&(r._sentryDebugIds=r._sentryDebugIds||{},r._sentryDebugIds[o]="4815cbcf-7887-4c60-bf18-6ad6bae0b84e",r._sentryDebugIdIdentifier="sentry-dbid-4815cbcf-7887-4c60-bf18-6ad6bae0b84e")})()}catch{}const Nt=async(r,o)=>{if(!r)throw new Error("Attribute ID is required");if(!o)throw new Error("User must be logged in to fetch attribute.");const{data:t,error:s}=await E.from("atributos").select("*").eq("id",r).eq("user_id",o).is("deletado_em",null).single();if(s)throw s;const{data:i,error:a}=await E.from("atributo_valor").select("*").eq("atributo_id",r).is("deletado_em",null).order("destaque",{ascending:!1}).order("id",{ascending:!0});if(a)throw a;return{...t,valores:i||[]}},Mt=r=>{const{user:o}=xe(),t=o==null?void 0:o.id;return Oe({queryKey:["attribute",r],queryFn:()=>Nt(r,t),enabled:!!r&&!!t})};let Fe=class extends Error{constructor(t,s){super(t);ce(this,"products");this.name="AttributeInUseError",this.products=s}};const Rt=()=>{const r=V();return K({mutationFn:async({attributeId:o})=>{const{data:t,error:s}=await E.from("produto_atributo").select(`
2          produto_id,
3          produto!inner(
4            id,
5            nome,
6            sku,
7            image_url,
8            deletado_em
9          )
10        `).eq("atributo_id",o).is("produto.deletado_em",null);if(s)throw s;if(t&&t.length>0){const u={};t.forEach(h=>{const d=h.produto;u[d.id]={id:d.id,nome:d.nome,sku:d.sku,image_url:d.image_url}});const m=Object.values(u);throw new Fe("Este atributo está em uso por um ou mais produtos ativos e não pode ser excluído.",m)}const i=new Date().toISOString(),{error:a}=await E.from("atributos").update({deletado_em:i}).eq("id",o);if(a)throw a;const{error:l}=await E.from("atributo_valor").update({deletado_em:i}).eq("atributo_id",o);if(l)throw l},onSuccess:(o,t)=>{_e(De.DELETE.ATTRIBUTE,{attributeId:t.attributeId}),r.invalidateQueries({queryKey:["attributes"]})}})},zt=()=>{const r=V(),{user:o}=xe(),t=o==null?void 0:o.id;return K({mutationFn:async({attributeId:s,value:i,swatch:a})=>{if(!t)throw new Error("User must be logged in to add an attribute value.");const{data:l,error:u}=await E.from("atributo_valor").insert({valor:i.trim(),atributo_id:s,user_id:t,swatch:a===void 0?null:a}).select().single();if(u)throw u;return l},onSuccess:(s,i)=>{r.invalidateQueries({queryKey:["attributes"]}),r.invalidateQueries({queryKey:["attribute",i.attributeId]})}})},Pt=()=>{const r=V(),{triggerRevalidation:o}=me();return K({mutationFn:async({valueId:t,value:s,swatch:i})=>{const{data:a,error:l}=await E.from("atributo_valor").update({valor:s.trim(),swatch:i===void 0?null:i}).eq("id",t).select().single();if(l)throw l;return a},onSuccess:(t,s)=>{r.invalidateQueries({queryKey:["attributes"]}),r.invalidateQueries({queryKey:["attribute",s.attributeId]}),o()}})};
10class Le extends Error{constructor(t,s){super(t);ce(this,"products");this.name="AttributeInUseError",this.products=s}}const Wt=()=>{const r=V();return K({mutationFn:async({valueId:o})=>{const{data:t,error:s}=await E.from("produto_variacao_valor").select(`
11          variacao_id,
12          produto_variacao!inner(
13            produto_id,
14            deletado_em,
15            produto!inner(
16              id,
17              nome,
18              sku,
19              image_url,
20              deletado_em
21            )
22          )
23        `).eq("atributo_valor_id",o).is("produto_variacao.deletado_em",null).is("produto_variacao.produto.deletado_em",null);if(s)throw s;if(t&&t.length>0){const l={};t.forEach(m=>{const h=m.produto_variacao.produto;l[h.id]={id:h.id,nome:h.nome,sku:h.sku,image_url:h.image_url}});const u=Object.values(l);throw new Le("Esta opção está em uso por um ou mais produtos ativos e não pode ser excluída.",u)}const i=new Date().toISOString(),{error:a}=await E.from("atributo_valor").update({deletado_em:i}).eq("id",o);if(a)throw a},onSuccess:(o,t)=>{_e(De.DELETE.ATTRIBUTE_VALUE,{valueId:t.valueId,attributeId:t.attributeId}),r.invalidateQueries({queryKey:["attributes"]}),r.invalidateQueries({queryKey:["attribute",t.attributeId]})}})},Ut=()=>{const r=V(),{triggerRevalidation:o}=me();return K({mutationFn:async({attributeId:t,name:s})=>{const{data:i,error:a}=await E.from("atributos").update({nome:s.trim()}).eq("id",t).select().single();if(a)throw a;return i},onSuccess:(t,s)=>{r.invalidateQueries({queryKey:["attributes"]}),r.invalidateQueries({queryKey:["attribute",s.attributeId]}),o()}})},Bt=({open:r,onClose:o,currentSwatch:t,onSave:s})=>{const[i,a]=x.useState("solid"),[l,u]=x.useState("#FF0000"),[m,h]=x.useState("2"),[d,p]=x.useState(["#FF0000","#0000FF","#00FF00"]),[C,g]=x.use
23State("rainbow");x.useEffect(()=>{if(!t){a("solid");return}switch(t.kind){case"solid":a("solid"),u(t.color);break;case"metallic":a("texture"),g(t.preset);break;case"multicolored":a("combo"),t.colors.length<=2?(h("2"),p([t.colors[0]||"#FF0000",t.colors[1]||"#0000FF","#00FF00"])):(h("3"),p([t.colors[0]||"#FF0000",t.colors[1]||"#0000FF",t.colors[2]||"#00FF00"]));break;case"rainbow":a("texture"),g("rainbow");break;case"camouflage":a("texture"),g("camouflage");break;default:a("none")}},[t,r]);const I=(c,_)=>{_&&a(_)},k=c=>{u(c)},T=c=>{h(c.target.value)},y=(c,_)=>{const N=[...d];N[c]=_,p(N)},b=c=>{g(c)},A=()=>{let c;switch(i){case"solid":c={kind:"solid",color:l};break;case"combo":c={kind:"multicolored",colors:m==="2"?d.slice(0,2):d.slice(0,3)};break;case"texture":C==="rainbow"?c={kind:"rainbow"}:C==="camouflage"?c={kind:"camouflage"}:c={kind:"metallic",preset:C};break;case"none":c=void 0;break}s(c)},H=()=>{switch(i){case"none":return"Nenhuma";case"solid":return"Cor sólida";case"combo":return"Combinação";case"texture":return"Textura";default:return""}},S=[{value:"gold",label:"Ouro",swatch:{kind:"metallic",preset:"gold"}},{value:"silver",label:"Prata",swatch:{kind:"metallic",preset:"silver"}},{value:"stainless",label:"Inox",swatch:{kind:"metallic",preset:"stainless"}},{value:"bronze",label:"Bronze",swatch:{kind:"metallic",preset:"bronze"}},{value:"copper",label:"Cobre",swatch:{kind:"metallic",preset:"copper"}},{value:"rose_gold",label:"Ouro rosé",swatch:{kind:"metallic",preset:"rose_gold"}}],F=[{value:"rainbow",label:"Colorido",swatch:{kind:"rainbow"}},{value:"camouflage",label:"Camuflagem",swatch:{kind:"camouflage"}}],L=c=>e.jsx(de,{item:!0,xs:4,children:e.jsxs(f,{onClick:()=>b(c.value),sx:{display:"flex",flexDirection:"column",alignItems:"center",p:1,cursor:"pointer",border:"1px solid",borderColor:C===c.value?"primary.main":"divider",borderRadius:1,bgcolor:C===c.value?"action.selected":"transparent","&:hover":{bgcolor:"action.hover"}},children:[e.jsx(pe,{swatch:c.swatch,size:28}),e.jsx(j,{variant:"caption",align:"center",sx:{marginTop:.5,width:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.label})]})},c.value);return e.jsxs(W,{open:r,onClose:o,fullWidth:!0,maxWidth:"xs",PaperProps:{sx:{borderRadius:2,m:{xs:1,sm:2}}},children:[e.jsx(U,{children:"Editar prévia da cor"}),e.jsxs(B,{sx:{pb:1},children:[e.jsxs(at,{value:i,exclusive:!0,onChange:I,"aria-label":"tipo de prévia",fullWidth:!0,sx:{mb:2},children:[e.jsx(ee,{value:"none","aria-label":"nenhuma",children:e.jsx(Dt,{})}),e.jsx(ee,{value:"solid","aria-label":"cor sólida",children:e.jsx(Ot,{})}),e.jsx(ee,{value:"combo","aria-label":"combinação",children:e.jsx(qt,{})}),e.jsx(ee,{value:"texture","aria-label":"textura",children:e.jsx(Tt,{})})]}),e.jsx(j,{variant:"subtitle2",gutterBottom:!0,color:"text.secondary",children:H()}),i==="solid"&&e.jsx(f,{sx:{mb:2},children:e.jsx(te,{value:l,onChange:k,format:"hex",isAlphaHidden:!0,fullWidth:!0})}),i==="combo"&&e.jsxs(f,{sx:{mb:2},children:[e.jsxs(st,{row:!0,value:m,onChange:T,sx:{mb:1.5},children:[e.jsx(ve,{value:"2",control:e.jsx(ye,{size:"small"}),label:"2 cores"}),e.jsx(ve,{value:"3",control:e.jsx(ye,{size:"small"}),label:"3 cores"})]}),e.jsxs(f,{sx:{display:"flex",gap:1,mb:1},children:[e.jsx(te,{value:d[0],onChange:c=>y(0,c),format:"hex",isAlphaHidden:!0,fullWidth:!0}),e.jsx(te,{value:d[1],onChange:c=>y(1,c),format:"hex",isAlphaHidden:!0,fullWidth:!0})]}),m==="3"&&e.jsx(te,{value:d[2],onChange:c=>y(2,c),format:"hex",isAlphaHidden:!0,fullWidth:!0})]}),i==="texture"&&e.jsxs(f,{sx:{mb:2},children:[e.jsx(j,{variant:"body2",fontWeight:"medium",sx:{mb:1,mt:2},children:"Metálicos"}),e.jsx(de,{container:!0,spacing:1,sx:{mb:2},children:S.map(c=>L(c))}),e.jsx(j,{variant:"body2",fontWeight:"medium",sx:{mb:1,mt:2},children:"Outros"}),e.jsx(de,{container:!0,spacing:1,children:F.map(c=>L(c))})]})]}),e.jsxs(Q,{sx:{px:3,pb:2},children:[e.jsx(q,{onClick:o,color:"inherit",sx:{color:"text.secondary"},children:"CANCELAR"}),e.jsx(q,{onClick:A,variant:"contained",children:"SALVAR"})]})]})},Qt=4;
23function Vt(r,o=!0){const[t,s]=x.useState(r),i=xt(a=>{s(a)},800);return x.useEffect(()=>{i(r)},[r,i]),Oe({queryKey:["swatchClassify",t],queryFn:()=>Te.classifyColor(t),enabled:o&&!!t&&t.trim()!==""&&t.trim().length>=Qt,staleTime:1e3*60*5})}const Kt=()=>{const r=V(),{user:o}=xe(),t=o==null?void 0:o.id,{triggerRevalidation:s}=me();return K({mutationFn:async({values:i})=>{if(!t)throw new Error("User must be logged in to update attribute value orders.");const{data:a,error:l}=await E.from("atributo_valor").select("*").in("id",i.map(h=>h.id));if(l)throw l;const u=new Map((a==null?void 0:a.map(h=>[h.id,h]))||[]),{error:m}=await E.from("atributo_valor").upsert(i.map(({id:h,destaque:d})=>{const p=u.get(h);if(!p)throw new Error(`Attribute value with id ${h} not found`);return{id:h,destaque:d,valor:p.valor,atributo_id:p.atributo_id,user_id:p.user_id,swatch:p.swatch}}),{onConflict:"id",ignoreDuplicates:!1});if(m)throw m},onMutate:async({attributeId:i,values:a,originalAttribute:l})=>{await r.cancelQueries({queryKey:["attribute",i]});const u=r.getQueryData(["attribute",i]);if(l){const m=JSON.parse(JSON.stringify(l)),h=new Map(a.map(({id:d,destaque:p})=>[d,p]));m.valores.forEach(d=>{const p=h.get(d.id);p!==void 0&&(d.destaque=p)}),m.valores.sort((d,p)=>{const C=d.destaque??0,g=p.destaque??0;return g!==C?g-C:d.id-p.id}),r.setQueryData(["attribute",i],m)}return{previousAttribute:u}},onError:(i,{attributeId:a},l)=>{l!=null&&l.previousAttribute&&r.setQueryData(["attribute",a],l.previousAttribute)},onSettled:(i,a,{attributeId:l})=>{r.invalidateQueries({queryKey:["attribute",l]}),s()}})},Ht=({value:r,handleOpenOptionMenu:o})=>{const{attributes:t,listeners:s,setNodeRef:i,transform:a,transition:l,isDragging:u}=Et({id:r.id.toString()}),m={transform:kt.Transform.toString(a),transition:l,opacity:u?.8:1,position:"relative",zIndex:u?999:"auto",boxShadow:u?"0 5px 15px rgba(0,0,0,0.2)":"none"};return e.jsxs(dt,{ref:i,style:m,sx:{py:1.5,px:1,borderColor:"divider",bgcolor:"white"},children:[e.jsx(f,{...t,...s,sx:{color:"text.disabled",cursor:u?"grabbing":"grab",touchAction:"none",display:"flex",alignItems:"center",px:.5,mr:.5,alignSelf:"stretch"},"aria-label":"Arrastar para reordenar",children:e.jsx(Lt,{})}),e.jsxs(f,{sx:{display:"flex",alignItems:"center",gap:1.5},children:[r.swatch&&e.jsx(pe,{swatch:r.swatch,size:28}),e.jsx(R,{primary:e.jsx(j,{fontWeight:500,children:r.valor})})]}),e.jsx(f,{sx:{ml:"auto"},children:e.jsx(oe,{edge:"end",onClick:h=>{h.stopPropagation(),o(h,r.id,r.valor,r.swatch)},sx:{color:"text.secondary"},children:e.jsx(qe,{})})})]})},Gt=()=>e.jsxs(ae,{spacing:3,children:[e.jsxs(f,{children:[e.jsx(P,{width:140,height:24,sx:{mb:.5}}),e.jsx(P,{width:200,height:20,sx:{mb:1}}),e.jsx(P,{height:56})]}),e.jsxs(f,{children:[e.jsx(P,{width:80,height:24,sx:{mb:.5}}),e.jsx(P,{width:160,height:20,sx:{mb:1}}),e.jsx(ae,{spacing:1,children:[1,2,3].map(r=>e.jsx(P,{height:48},r))})]})]}),$t=({open:r,onClose:o,currentName:t,onSave:s,isLoading:i})=>{const[a,l]=x.useState(t);ht.useEffect(()=>{l(t)},[t,r]);const u=m=>{m.preventDefault(),a.trim()&&s(a)};return e.jsxs(W,{open:r,onClose:o,fullWidth:!0,maxWidth:"xs",children:[e.jsx(U,{sx:{pb:1},children:"Editar nome do atributo"}),e.jsxs("form",{onSubmit:u,children:[e.jsx(B,{sx:{pt:0},children:e.jsx(Ie,{fullWidth:!0,value:a,onChange:m=>l(m.target.value),label:"Nome do atributo",variant:"outlined",autoFocus:!0,margin:"normal",placeholder:"Ex: Cor, Tamanho, Material",InputLabelProps:{shrink:!0}})}),e.jsxs(Q,{sx:{px:3,pb:2},children:[e.jsx(q,{onClick:o,sx:{color:"text.secondary"},children:"Cancelar"}),e.jsx(se,{type:"submit",loading:i,disabled:!a.trim()||a===t,variant:"contained",children:"Salvar"})]})]})]})},Jt=({open:r,onClose:o,value:t,isEdit:s,onSave:i,isLoading:a,onAISwatchSuggestion:l,currentSwatch:u,isColorAttribute:m})=>
23{const h=x.useRef(t),[d,p]=x.useState(t),[C,g]=x.useState(!1),[I,k]=x.useState(u),[T,y]=x.useState(!!u),[b,A]=x.useState(!1),H=m||!!u;x.useEffect(()=>{r&&(h.current=t,p(t),k(u),y(!!u))},[r]);const{data:S,isLoading:F}=Vt(d,r&&!s&&m&&!T&&d.length>=4);x.useEffect(()=>{s||!r||!S||!l||T||(l(S),k(S))},[S,l,T,s,r]);const L=w=>{const M=w.target.value;h.current=M,p(M)},c=()=>{o()},_=w=>{w.preventDefault(),d.trim()&&i(d,I)},N=w=>{k(w),y(!0),g(!1)},ie=async()=>{if(d.trim())try{A(!0);const w=await Te.classifyColor(d.trim());w&&(k(w),y(!0),l&&l(w))}catch(w){console.error("Error manually classifying color:",w)}finally{A(!1)}},D=()=>{g(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs(W,{open:r,onClose:c,fullWidth:!0,maxWidth:"xs",keepMounted:!1,children:[e.jsx(U,{sx:{pb:1},children:s?"Editar opção":"Adicionar opção"}),e.jsxs("form",{onSubmit:_,children:[e.jsxs(B,{sx:{pt:0},children:[e.jsx(Ie,{fullWidth:!0,value:d,onChange:L,label:"Opção",variant:"outlined",placeholder:m?"Ex.: Azul, Vermelho":"Ex: Vermelho, P, Algodão",autoFocus:!0,margin:"normal",InputLabelProps:{shrink:!0},InputProps:{endAdornment:m&&e.jsx(ut,{position:"end",children:e.jsx(Ae,{title:"Detectar cor automaticamente",children:e.jsx(oe,{edge:"end",onClick:ie,size:"small",disabled:b||F,children:e.jsx(Ee,{})})})})}}),H&&e.jsxs(e.Fragment,{children:[m&&e.jsx(f,{sx:{display:"flex",alignItems:"center",mt:.5,mb:1.5,fontSize:12,color:"text.secondary",fontWeight:500},children:e.jsxs(j,{component:"span",fontSize:"inherit",fontWeight:500,ml:.5,mr:.5,sx:{lineHeight:"inherit"},children:[" ","Clique em ",e.jsx(Ee,{style:{fontSize:"inherit",verticalAlign:"middle"}})," para gerar uma prévia da cor"]})}),e.jsx(j,{variant:"body2",color:"text.secondary",gutterBottom:!0,children:"Prévia da cor"}),e.jsxs(f,{sx:{display:"flex",alignItems:"center",gap:2,p:1.5,bgcolor:"action.hover",borderRadius:1,cursor:"pointer",position:"relative"},onClick:D,children:[F||b?e.jsx(f,{sx:{width:36,height:36,display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsx(f,{sx:{width:20,height:20,borderRadius:"50%",border:"2px solid",borderColor:"grey.300",borderLeftColor:"primary.main",animation:"spin 1s linear infinite","@keyframes spin":{"0%":{transform:"rotate(0deg)"},"100%":{transform:"rotate(360deg)"}}}})}):e.jsx(pe,{swatch:I,size:36}),e.jsx(j,{variant:"body2",flex:1,children:F||b?"Detectando cor...":I?"Clique para editar a prévia da cor":"Clique para adicionar uma prévia da cor"}),e.jsx(re,{fontSize:"small",color:"action"})]})]}),!s&&e.jsx(j,{variant:"caption",color:"text.secondary",sx:{display:"block",mt:2},children:"Após adicionar, você poderá incluir mais opções."})]}),e.jsxs(Q,{sx:{px:3,pb:2},children:[e.jsx(q,{onClick:c,sx:{color:"text.secondary"},children:"Cancelar"}),e.jsx(se,{type:"submit",loading:a,disabled:!d.trim()||s&&d===t&&JSON.stringify(I??{})===JSON.stringify(u??{}),variant:"contained",color:"primary",children:s?"Atualizar":"Adicionar"})]})]})]}),e.jsx(Bt,{open:C,onClose:()=>g(!1),currentSwatch:I,onSave:N})]})},cr=()=>{const{attributeId:r}=mt(),o=pt(),{data:t,isLoading:s}=Mt(Number(r)),i=Rt(),a=zt(),l=Pt(),u=Wt(),m=Ut(),h=Kt(),[d,p]=x.useState(!1),[C,g]=x.use
23State(!1),[I,k]=x.useState(!1),[T,y]=x.useState(!1),[b,A]=x.useState(null),[H,S]=x.useState(void 0),F=bt(Se(It,{activationConstraint:{distance:5}}),Se(At,{activationConstraint:{delay:100,tolerance:5}})),[L,c]=x.useState(null),[_,N]=x.useState(null),[ie,D]=x.useState(!1),[w,M]=x.useState(""),[Ne,J]=x.useState(""),[Me,Y]=x.useState([]),Re=async n=>{if(r)try{await m.mutateAsync({attributeId:Number(r),name:n}),p(!1)}catch(v){console.error("Error updating attribute name:",v)}},ze=async()=>{if(r)try{await i.mutateAsync({attributeId:Number(r)}),o(-1)}catch(n){k(!1),n instanceof Fe?(M("Não é possível excluir este atributo"),J(`O atributo <strong>${t==null?void 0:t.nome}</strong> está sendo usado pelos seguintes produtos:`),Y(n.products),D(!0)):(M("Erro ao excluir o atributo"),J(n instanceof Error?n.message:"Ocorreu um erro ao tentar excluir este atributo."),Y([]),D(!0))}},Pe=async(n,v)=>{if(r)try{await a.mutateAsync({attributeId:Number(r),value:n,swatch:v}),g(!1),S(void 0)}catch(O){console.error("Error adding attribute option:",O)}},We=async(n,v)=>{if(!(!r||!b))try{await l.mutateAsync({valueId:b.id,attributeId:Number(r),value:n,swatch:v}),g(!1),A(null)}catch(O){console.error("Error updating attribute option:",O)}},Ue=async()=>{if(!(!r||!b))try{await u.mutateAsync({valueId:b.id,attributeId:Number(r)}),y(!1),A(null)}catch(n){y(!1),n instanceof Le?(M("Não é possível excluir esta opção"),J(`A opção <strong>${b.value}</strong> está sendo usada pelos seguintes produtos:`),Y(n.products),D(!0)):(M("Erro ao excluir a opção"),J(n instanceof Error?n.message:"Ocorreu um erro ao tentar excluir esta opção."),Y([]),D(!0))}},Be=n=>{S(n)},Qe=x.useCallback(async n=>{const{active:v,over:O}=n;if(!O||!v||v.id===O.id||!t)return;const X=t.valores.findIndex(z=>z.id.toString()===v.id),je=t.valores.findIndex(z=>z.id.toString()===O.id);if(X!==-1&&je!==-1){const z=ft(t.valores,X,je),Xe=z.length,et=z.map((le,tt)=>({id:le.id,destaque:Xe-tt}));try{await h.mutateAsync({attributeId:t.id,values:et,originalAttribute:t})}catch(le){console.error("Failed to update attribute value order:",le)}}},[t,h]),Ve=n=>{c(n.currentTarget)},Z=()=>{c(null)},Ke=(n,v,O,X)=>{n.stopPropagation(),N(n.currentTarget),A({id:v,value:O,swatch:X})},ne=()=>{N(null)},be=()=>{Z(),p(!0)},He=()=>{ne(),g(!0)},Ge=()=>{Z(),k(!0)},$e=()=>{Z(),S(void 0),g(!0)},Je=()=>{ne(),y(!0)},fe=()=>{A(null),S(void 0),g(!0)},ge=()=>t?["cor","color","colour"].some(v=>t.nome.toLowerCase().includes(v.toLowerCase())):!1,Ye=n=>ge()||n!==null&&!!(n!=null&&n.swatch),Ze=!!(!s&&t&&t.valores.length>0&&t.valores.length<=2);return e.jsxs(f,{sx:{display:"flex",flexDirection:"column"},children:[e.jsx(gt,{title:"Editar atributo",navigateBack:!0,children:e.jsx(oe,{color:"inherit",onClick:Ve,children:e.jsx(qe,{})})}),e.jsxs(f,{sx:{flex:1,p:2,display:"flex",flexDirection:"column",overflowY:"auto"},children:[s?e.jsx(Gt,{}):t?e.jsxs(ae,{spacing:3,children:[e.jsx(ue,{sx:{p:3,borderRadius:2,bgcolor:"white"},elevation:0,children:e.jsxs(ae,{direction:"row",justifyContent:"space-between",alignItems:"center",children:[e.jsxs(f,{children:[e.jsx(j,{variant:"caption",color:"text.secondary",sx:{letterSpacing:.5,fontWeight:500},children:"Nome do atributo"}),e.jsx(j,{variant:"h6",sx:{mt:.5,fontWeight:600},children:t.nome})]}),e.jsx(oe,{onClick:be,size:"small",sx:{bgcolor:"action.hover","&:hover":{bgcolor:"action.selected"}},children:e.jsx(re,{fontSize:"small"})})]})}),e.jsxs(f,{children:[e.jsxs(j,{variant:"subtitle1",fontWeight:600,sx:{mb:1.5,pl:.5},children:["Opções (",t.valores.length,")"]}),t.valores.length>0?e.jsx(ue,{sx:{overflow:"visible"},elevation:0,children:e.jsx(jt,{sensors:F,collisionDetection:vt,onDragEnd:Qe,children:e.jsx(yt,{items:t.valores.map(n=>n.id.toString()),strategy:wt,children:e.jsx(we,{disablePadding:!0,children:t.valores.map(n=>e.jsx(Ht,{value:n,handleOpenOptionMenu:Ke},n.id))})})})}):e.jsxs(ue,{sx:{p:3,borderRadius:2,textAlign:"center",borderStyle:"dashed",borderWidth:1,borderColor:"divider",bgcolor:"white"},children:[e.jsx(j,{color:"text.secondary",children:"Nenhuma opção adicionada ainda"}),e.jsx(q,{startIcon:e.jsx(he,{}),onClick:fe,variant:"outlined",sx:{mt:1.5},children:"Adicionar opção"})]})]})]}):null,e.jsx(f,{sx:{display:"flex",justifyContent:"center",alignItems:"center",height:"64px",width:"64px",backgroundColor:"transparent"}})]}),t&&t.valores.length>0&&e.jsx(Ae,{title:"Adicionar opção",children:e.jsx(it,{color:"primary","aria-label":"adicionar",onClick:fe,sx:{position:"fixed",bottom:"calc(16px + var(--safe-area-inset-bottom))",right:16},children:e.jsx(he,{})})}),e.jsx(Ct,{text:"Adicionar opção",visible:Ze,fabBottom:"calc(16px + var(--safe-area-inset-bottom))",fabRight:16}),e.jsx($t,{open:d,onClose:()=>p(!1),currentName:(t==null?void 0:t.nome)||"",onSave:Re,isLoading:m.isPending}),e.jsx(Jt,{open:C,onClose:()=>{g(!1),A(null),S(void 0)},value:(b==null?void 0:b.value)||"",isEdit:!!b,onSave:b?We:Pe,isLoading:a.isPending||l.isPending,onAISwatchSuggestion:ge()?Be:void 0,currentSwatch:b?b.swatch:H,isColorAttribute:Ye(b)}),e.jsxs(W,{open:I,onClose:()=>k(!1),children:[e.jsx(U,{children:"Excluir atributo"}),e.jsx(B,{children:e.jsxs(j,{children:['Tem certeza que deseja excluir o atributo "',t==null?void 0:t.nome,'"?']})}),e.jsxs(Q,{children:[e.jsx(q,{onClick:()=>k(!1),sx:{color:"text.secondary"},children:"Cancelar"}),e.jsx(se,{onClick:ze,color:"error",loading:i.isPending,variant:"contained",children:"Excluir"})]})]}),e.jsxs(W,{open:T,onClose:()=>y(!1),children:[e.jsx(U,{children:"Excluir opção"}),e.jsx(B,{children:e.jsxs(j,{children:['Tem certeza que deseja excluir a opção "',b==null?void 0:b.value,'"?']})}),e.jsxs(Q,{children:[e.jsx(q,{onClick:()=>y(!1),sx:{color:"text.secondary"},children:"Cancelar"}),e.jsx(se,{onClick:Ue,color:"error",loading:u.isPending,variant:"contained",children:"Excluir"})]})]}),e.jsxs(W,{open:ie,onClose:()=>D(!1),maxWidth:"sm",fullWidth:!0,children:[e.jsx(U,{children:w}),e.jsxs(B,{children:[e.jsx(nt,{sx:{mb:2},dangerouslySetInnerHTML:{__html:Ne}}),e.jsx(f,{sx:{maxHeight:300,overflow:"auto"},children:e.jsx(we,{sx:{borderRadius:1},children:Me.map(n=>{var v;return e.jsxs(lt,{onClick:()=>{D(!1),o(`/products/${n.id}/edit`)},sx:{py:1.25,bgcolor:"white",transition:"all 0.1s","&:hover":{backgroundColor:"action.hover"},mb:1,borderRadius:1}
23,children:[e.jsx(ct,{sx:{minWidth:48},children:e.jsx(_t,{imageUrl:(v=n.image_url)==null?void 0:v[0],size:36})}),e.jsx(R,{primary:e.jsx(j,{variant:"body2",component:"div",sx:{fontWeight:600,...St(3)},children:n.nome}),secondary:n.sku&&e.jsxs(j,{variant:"caption",color:"text.secondary",component:"span",children:["#",n.sku]})}),e.jsx(Ft,{color:"action",fontSize:"small"})]},n.id)})})}),e.jsx(f,{sx:{mt:2,p:2,bgcolor:"rgba(0, 0, 0, 0.02)",borderRadius:1},children:e.jsx(j,{variant:"body2",color:"text.secondary",children:"Para excluir este item, primeiro remova-o de todos os produtos listados acima."})})]}),e.jsx(Q,{children:e.jsx(q,{onClick:()=>D(!1),variant:"contained",children:"Entendi"})})]}),e.jsxs(Ce,{anchorEl:L,open:!!L,onClose:Z,children:[e.jsxs(G,{onClick:be,children:[e.jsx($,{children:e.jsx(re,{fontSize:"small"})}),e.jsx(R,{children:"Editar nome"})]}),e.jsxs(G,{onClick:Ge,children:[e.jsx($,{children:e.jsx(ke,{fontSize:"small"})}),e.jsx(R,{children:"Excluir atributo"})]}),e.jsxs(G,{onClick:$e,children:[e.jsx($,{children:e.jsx(he,{fontSize:"small"})}),e.jsx(R,{children:"Adicionar opção"})]})]}),e.jsxs(Ce,{anchorEl:_,open:!!_,onClose:ne,children:[e.jsxs(G,{onClick:He,children:[e.jsx($,{children:e.jsx(re,{fontSize:"small"})}),e.jsx(R,{children:"Editar"})]}),e.jsxs(G,{onClick:Je,children:[e.jsx($,{children:e.jsx(ke,{fontSize:"small"})}),e.jsx(R,{children:"Excluir"})]})]})]})};export{cr 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.