1 2!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="87e8c020-2c80-51fa-9e9d-4c11a518ed87")}catch(e){}}(); 3import{R as t,Q as O,aJ as Le,V as gt,W as M,bJ as Oe,b5 as Me,b6 as Be,bG as ht,ao as ge,b7 as N,aN as S,bO as bt,bC as vt,b9 as We,ba as A,bW as xe,cB as ft,a6 as he,bF as Q,X as Et,av as qe,aj as je,Y as L,k as I,ah as Z,bD as yt,cC as xt,cD as $e,bf as Y,cE as ee,D as wt,q as Ct,I as kt,s as ze,t as At,b0 as Nt,bk as He,cF as Ge,M as Ve,cG as we,c8 as Ye,aS as St,bS as _t,aH as Pt,bi as H,bg as Rt,E as It,bN as Dt,m as Ut,n as Je,ad as Ke,bI as de,aU as Tt,bj as Ft,c9 as Lt,cH as Ot,cI as Mt,bY as Bt,l as Ce,aG as Wt}from"./index-Cs-In7Vx.js";import{C as qt}from"./Drawer-z0Voclkl.js";import{S as jt}from"./SearchInput-6k8qtIIx.js";import{i as $t,c as zt,M as ke,a as Ht}from"./utils-BV20SPqd.js";import{M as Gt,b as Vt,f as te,a as be,A as Yt}from"./appPermissions-IOfUOL5d.js";import{D as $,r as Jt}from"./Draft-yvgGJQ1j.js";/* empty css */import{D as Kt}from"./DescriptionRounded-fU0kur7i.js";import{A as Xt}from"./index-Dpr9l0yn.js";import{A as Qt}from"./AppsRounded-B77gkWds.js";import{V as Zt}from"./VpnKeyRounded-DcOTWpCN.js";import"./Lock-C5j5Mq5n.js";import"./CloudUploadRounded-DqYHvwyH.js";import"./SearchTextInput-Gprlx1Wp.js";function ea({value:e=[],onChange:a,maxFiles:r=5,mapValueToItem:n,mapFileToValue:o,validateFile:s,onRemoveValue:u}){const d=t.useMemo(()=>e.map((m,i)=>n(m,i)),[n,e]),f=t.useCallback(m=>{const i=Array.from(m.target.files||[]);if(!i.length||e.length>=r){m.target.value="";return}const E=r-e.length,k=i.filter(C=>!s||s(C)).slice(0,E).map(C=>o(C));k.length>0&&a([...e,...k]),m.target.value=""},[o,r,a,s,e]),g=t.useCallback(m=>{const i=e[m];i&&(u?.(i,m),a(e.filter((E,x)=>x!==m)))},[a,u,e]),l=t.useCallback((m,i)=>{const E=[...e],[x]=E.splice(m,1);E.splice(i,0,x),a(E)},[a,e]),v=t.useCallback(()=>{},[]);return{items:d,handleSelectFile:f,handleRemoveItem:g,handleReorderItems:l,handleReorderComplete:v}}async function ta(e){const{data:a}=await O.post("/api/v2/integrations/integrators",{integrator:e});return a}async function Xe(e,a){const{data:r}=await O.put(`/api/v2/integrations/integrators/${e}`,{integrator:a});return r}async function aa(e){await O.delete(`/api/v2/integrations/integrators/${e}`)}async function ra(e){const{data:a}=await O.get(`/api/v2/integrations/integrators/${e}/token`);return a}const ve="/api/v2/integrations/marketplace_apps";function na({integratorId:e,page:a=1,per_page:r=100,status:n,q:o}={}){const s=new URLSearchParams;return s.set("page",String(a)),s.set("per_page",String(r)),e&&s.set("integrator_id",String(e)),n&&s.set("status",n),o&&s.set("q",o),`${ve}?${s.toString()}`}async function oa({payload:e,formData:a}){const{data:r}=await O.post(ve,a||{marketplace_app:e});return r}async function z(e,{payload:a,formData:r}){const{data:n}=await O.patch(`${ve}/${e}`,r||{marketplace_app:a});return n?.marketplace_app||n}const sa=e=>O.get(e).then(a=>a.data),ie="/api/v2/integrations/integrators";let Ae;function fe(e=Ae){if(Ae=e,!e)return ie;const a=gt.queryParamsObjectToString(e);return a?`${ie}?${a}`:ie}function Qe(e){const{data:a,error:r,isLoading:n,mutate:o}=Le(fe(e),sa,{dedupingInterval:1e4,keepPreviousData:!0});return{data:a?.integrators,totalRecords:a?.meta?.total??0,isLoading:n,isError:r,mutate:o}}const ia=We().shape({name:A().trim().required("Informe o nome").max(255,"O nome deve ter no máximo 255 caracteres"),email:A().trim().lowercase().required("Informe o e-mail").email("Informe um e-mail válido"),document:A().trim().required("Informe o CPF ou CNPJ").test("is-cpf-or-cnpj","Deve ser um CPF (11 dÃgitos) ou CNPJ (14 dÃgitos)",e=>{const a=e?.replace(/\D/g,"");return a?.length===11||a?.length===14}),site:A().trim().lowercase().required("Informe o site").matches(/^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}([/][a-z0-9._~:/?#[\]@!$&'()*+,;=%-]*)?$/,"Deve ser um domÃnio válido (ex: exemplo.com ou exemplo.com/path)"),description:A().trim().required("Informe a descrição").max(1e3,"A descrição deve ter no máximo 1000 caracteres"),telephone:A().trim().required("Informe o telefone").test("has-11-digits","Deve ter exatamente 11 dÃgitos",e=>e?.replace(/\D/g,"")?.length===11)}),le={name:"",email:"",document:"",site:"",description:"",telephone:""};function la({open:e,defaultValues:a,onClose:r}){const n=M(),[o,s]=t.useState(!1),{mutate:u}=Oe(),{handleSubmit:d,reset:f,formState:g,control:l}=Me({mode:"onSubmit",defaultValues:le,resolver:Be(ia)});t.useEffect(()=>
3{e&&f(a?{...le,...a,telephone:a?.telephone?ht(a.telephone):""}:le)},[a,e,f]);const v=t.useCallback(async i=>{s(!0);const E={name:i.name.trim(),email:i.email.trim().toLowerCase(),document:i.document.replace(/\D/g,""),site:i.site.trim().toLowerCase(),description:i.description.trim(),telephone:i.telephone.replace(/\D/g,"")};try{a?.id?(await Xe(a.id,E),n.success("Integradora atualizada com sucesso")):(await ta(E),n.success("Integradora criada com sucesso")),await u(fe()),r()}catch(x){const p=x.response?.data?.message;n.error(p||"Não foi possÃvel salvar a integradora")}finally{s(!1)}},[n,a,u,r]),{errors:m}=g;return t.createElement(ge,{open:e,title:a?.id?"Editar integradora":"Cadastrar integradora",loading:o,onClose:r,onSubmit:d(v),maxWidth:"sm"},t.createElement("div",{className:"space-y-24"},t.createElement(N,{name:"name",control:l,render:({field:i})=>t.createElement(S,{...i,id:"name",label:"Nome",error:!!m.name,helperText:m?.name?.message,variant:"outlined",autoFocus:!0,fullWidth:!0,required:!0})}),t.createElement(N,{name:"email",control:l,render:({field:i})=>t.createElement(S,{...i,id:"email",label:"E-mail",type:"email",error:!!m.email,helperText:m?.email?.message,variant:"outlined",fullWidth:!0,required:!0})}),t.createElement(N,{name:"document",control:l,render:({field:i})=>t.createElement(S,{...i,id:"document",label:"CPF ou CNPJ",error:!!m.document,helperText:m?.document?.message,InputProps:{inputComponent:bt},variant:"outlined",fullWidth:!0,required:!0})}),t.createElement(N,{name:"site",control:l,render:({field:i})=>t.createElement(S,{...i,id:"site",label:"Site",error:!!m.site,helperText:m?.site?.message||"Exemplo: exemplo.com ou exemplo.com/path",variant:"outlined",fullWidth:!0,required:!0})}),t.createElement(N,{name:"telephone",control:l,render:({field:i})=>t.createElement(S,{...i,id:"telephone",label:"Telefone",error:!!m.telephone,helperText:m?.telephone?.message,InputProps:{inputComponent:vt},variant:"outlined",fullWidth:!0,required:!0})}),t.createElement(N,{name:"description",control:l,render:({field:i})=>t.createElement(S,{...i,id:"description",label:"Descrição",error:!!m.description,helperText:m?.description?.message,variant:"outlined",fullWidth:!0,multiline:!0,rows:4,required:!0})})))}const ae=40,re=300,ue=3e3;function ca(e){return e?.iconFile?!0:e?.removeLogo?!1:!!(e?.iconPreview||e?.initialLogoUrl)}function ma(e){if(!e)return $.EditorState.createEmpty();try{return $.EditorState.createWithContent($.convertFromRaw(JSON.parse(e)))}catch{return $.EditorState.createWithContent($.ContentState.createFromText(e))}}function Ne(e){const a=e.getCurrentContent();return a.hasText()?JSON.stringify($.convertToRaw(a)):""}function da(e){if(!e)return"";try{return $.convertFromRaw(JSON.parse(e)).getPlainText()}catch{return e}}function Ze(e){return da(e).trim().length}const pe={name:"",category:"",shortDescription:"",visibility:"public",installUrl:"",redirectUri:"",authenticationUrl:"",webhookUrl:"",description:"",iconFile:null,iconPreview:null,initialLogoUrl:null,initialBannerUrls:[],removeLogo:!1,banners:[],permissions:[]};function ne(e){return!!(e&&typeof e=="string"&&!e.startsWith("blob:"))}function et(e=[]){return pa(e).filter(ne)}function ua(e){if(e?.banners?.length)return e.banners;const a=e?.bannerPreviews||e?.banner_images_urls||[],r=e?.bannerFiles||[];if(!r.length)return a.map(o=>({preview:o}));const n=a.length-r.length;return a.map((o,s)=>({preview:o,file:s>=n?r[s-n]:void 0}))}function pa(e=[]){return e.map(a=>a.preview)}function Ee(e=[]){return e.filter(a=>a.file).map(a=>a.file)}function ga(e){e?.startsWith?.("blob:")&&URL.revokeObjectURL(e)}function ha(e){if(!e)return{...pe};const a=te(e.lockedPermissions),r=te(e.permissions);return{...pe,name:e.name||"",category:e.category||"",shortDescription:e.shortDescription||"",visibility:e.visibility||"public",installUrl:e.installUrl||e.installation_link||"",redirectUri:e.redirectUri||e.redirect_uri||"",authenticationUrl:e.authenticationUrl||e.loginUrl||e.login_url||e.authentication_url||e.auth_url||e.auth_link||"",webhookUrl:e.webhookUrl||e.webhook_url||"",description:e.description||e.long_description||"",iconFile:e.iconFile||null,iconPreview:e.iconPreview||e.logo_url||null,initialLogoUrl:e.iconPreview||e.logo_url||null,initialBannerUrls:[...e.banner_images_urls||e.bannerPreviews||[]],removeLogo:!1,banners:ua(e),permissions:[...new Set([...r,...a])]}}function ba(e){return!!e?.id}function tt(e,a=[]){return[...new Set([...a,...e])]}function va(e,a=[]){return tt(e,a)}function Se(e,a=[]){return a.includes(e)}function fa(e){return e==="public"}function Ea(e=[]){return We().shape({name:A().trim().required("Informe o nome do aplicativo").max(ae,`O nome deve ter no máximo ${ae} caracteres`),category:A().oneOf(Vt,"Selecione uma categoria válida").required("Selecione a categoria"),shortDescription:A().trim().required("Informe a descrição curta").max(re,`A descrição curta deve ter no máximo ${re} caracteres`),visibility:A().oneOf(["public","hidden"],"Selecione a visibilidade").required("Selecione a visibilidade"),installUrl:A().trim().required("Informe a URL de instalação").url("Informe uma url válida").matches(/^https:\/\/.+/,'A URL deve começar com "https://"'),redirectUri:A().trim().required("Informe a redirect URI").url("Informe uma url válida").matches(/^https:\/\/.+/,'A redirect URI deve começar com "https://"'),authenticationUrl:A().trim().required("Informe a URL de autenticação").url("Informe uma url válida").matches(/^https:\/\/.+/,'A URL de autenticação deve começar com "https://"'),webhookUrl:A().trim().nullable().test("webhook-url",'A URL de webhook deve começar com "https://"',a=>!a||/^https:\/\/.+/.test(a)).test("webhook-url-valid","Informe uma url válida",a=>{if(!a)return!0;try{return new URL(a),!0}catch{return!1}}),iconPreview:ft().nullable().test("has-icon","Selecione o Ãcone do aplicativo",function(){return ca(this.parent)}),description:A().when("visibility",{is:"public",then:a=>a.test("max-description",`A descrição deve ter no máximo ${ue} caracteres`,r=>!r||Ze(r)<=ue),otherwise:a=>a.notRequired()}),banners:xe(),permissions:xe().of(A().oneOf(Gt,"Permissão inválida")).test("has-permissions","Selecione ao menos uma permissão",a=>tt(a||[],e).length>0)})}
3const ya={options:["inline"],inline:{inDropdown:!1,options:["bold","italic","strikethrough"]}},xa=({value:e,onChange:a,error:r,errorMessage:n,maxLength:o=3e3})=>{const[s,u]=t.useState(()=>ma(e)),d=Ze(Ne(s)||e),f=g=>{g.getCurrentContent().getPlainText().length>o||(u(g),a(Ne(g)))};return t.createElement("div",{className:"space-y-8"},t.createElement("span",{className:"text-14 font-semibold text-gray-600"},"Descrição na página do aplicativo ",t.createElement("span",{className:"text-red"},"*")),t.createElement("div",{className:he("overflow-hidden rounded-8",r&&"border border-solid border-red p-1")},t.createElement(Jt.Editor,{editorState:s,toolbarClassName:"border-grey-border",toolbarStyle:{padding:"0.8rem"},wrapperClassName:"border-1 border-solid border-grey-border-dark rounded-8 bg-white",editorClassName:"min-h-160 px-12 py-12",toolbar:ya,placeholder:"Clique para inserir",onEditorStateChange:f,localization:{locale:"pt"}})),r&&n?t.createElement(Q,{error:!0,className:"mx-0"},n):t.createElement(t.Fragment,null,t.createElement("p",{className:"m-0 text-13 leading-normal text-gray-500"},"Estilize a descrição com negrito, itálico ou riscado usando a barra de ferramentas acima."),t.createElement("p",{className:"m-0 text-right text-13 text-gray-400"},d,"/",o)))},_e=({checked:e,disabled:a})=>t.createElement("span",{className:he("flex h-20 w-20 flex-shrink-0 items-center justify-center rounded-2 border border-solid",a&&e&&"border-gray-400 bg-gray-400 text-white",a&&!e&&"border-gray-300 bg-gray-100",!a&&e&&"border-purple bg-purple text-white",!a&&!e&&"border-gray-300 bg-white")},e&&t.createElement(qe,{style:{fontSize:16}})),wa=({checked:e,disabled:a,onChange:r,inputProps:n})=>{const o={disabled:a};return t.createElement(Et,{color:"default",checked:e,disabled:a,onChange:r,disableRipple:!0,className:"p-0 hover:bg-transparent",style:{padding:0,width:20,height:20},icon:t.createElement(_e,{...o}),checkedIcon:t.createElement(_e,{checked:!0,...o}),inputProps:n})},Ca=({permission:e,checked:a,locked:r,onToggle:n})=>t.createElement("div",{className:"flex items-center gap-12"},t.createElement("div",{className:"flex-shrink-0"},t.createElement(wa,{checked:a,disabled:r,onChange:n,inputProps:{"aria-label":`${e.label}. ${e.description}`}})),t.createElement("div",{className:"min-w-0 flex-1"},t.createElement("p",{className:"m-0 text-16 leading-snug text-gray-600"},t.createElement("span",{className:"font-semibold"},e.label,":")," ",e.description))),Pe=3;function ka(e,a){return{id:e.id||e.preview||`banner-${a}`,previewUrl:e.preview,name:e.file?.name||(ne(e.preview)?e.preview.split("/").pop()?.split("?")[0]:"Imagem"),type:"image",file:e.file}}function Aa(e){return{preview:zt(e).previewUrl,file:e}}function Na(e){return $t(e,!1)?e.size>Pe*1024*1024?`Arquivo muito grande. O limite é ${Pe} MB.`:!0:"Formato não suportado. Use imagens JPG, PNG, WEBP ou HEIC."}const K=5,Re={FormHelperTextProps:{className:"mx-0 mt-4 flex justify-end"}},Sa=Object.fromEntries(be.map(e=>[e.key,e.label])),_a=e=>e?Sa[e]||e:t.createElement("span",{className:"text-gray-400"},"Clique para selecionar"),ce=({children:e})=>t.createElement("h3",{className:"m-0 text-18 font-bold text-gray-600"},e),Ie=({current:e,max:a})=>t.createElement("span",{className:"text-13 text-gray-400"},`${e}/${a}`),Pa=({open:e,defaultValues:a,onClose:r,onSave:n,loading:o})=>{const s=M(),u=je(),d=t.useMemo(()=>a?.lockedPermissions||[],[a?.lockedPermissions]),f=t.useMemo(()=>Ea(d),[d]),{control:g,handleSubmit:l,reset:v,watch:m,setValue:i,clearErrors:E,formState:x}=Me({mode:"onSubmit",defaultValues:pe,resolver:Be(f)}),{errors:p,isDirty:k}=x,C=m("visibility"),_=fa(C);t.useEffect(()=>{e&&v(ha(a))},[a,e,v]),t.useEffect(()=>{_||E("description")},[E,_]);const R=c=>{const w=c.target.files?.[0];if(!w)return;const T=m("iconPreview");T?.startsWith?.("blob:")&&URL.revokeObjectURL(T),i("iconFile",w,{shouldDirty:!0}),i("iconPreview",URL.createObjectURL(w),{shouldDirty:!0}),i("removeLogo",!1,{shouldDirty:!0}),E("iconPreview"),c.target.value=""},D=()=>{const c=m("iconPreview"),w=m("initialLogoUrl"),T=ne(c)||ne(w);c?.startsWith?.("blob:")&&URL.revokeObjectURL(c),i("iconFile",null,{shouldDirty:!0}),i("iconPreview",null,{shouldDirty:!0}),i("removeLogo",T,{shouldDirty:!0})},P=c=>
3{if(Se(c,d)){s.warning("Esta permissão já foi salva e não pode ser desmarcada");return}const w=m("permissions")||[],T=w.includes(c)?w.filter(V=>V!==c):[...w,c];i("permissions",T,{shouldDirty:!0}),E("permissions")},y=async()=>{if(k)try{await u({title:"Descartar alterações?",description:"As informações não salvas serão perdidas.",cancellationText:"Continuar editando",confirmationText:"Descartar"})}catch{return}r()},B=c=>{n({...c,banners:m("banners")||[],iconFile:m("iconFile"),iconPreview:m("iconPreview"),initialBannerUrls:m("initialBannerUrls")||[],initialLogoUrl:m("initialLogoUrl"),removeLogo:m("removeLogo")||!1,permissions:[...new Set([...d,...c.permissions])]})},b=c=>{const w=Object.keys(c);w.length>0&&setTimeout(()=>{const T=w[0],V=document.getElementsByName(T)[0]||document.querySelector(`[name="${T}"]`)||document.querySelector(".Mui-error");V&&(V.scrollIntoView({behavior:"smooth",block:"center"}),V.focus?.())},100)},F=m("iconPreview"),W=m("banners")||[],U=m("permissions")||[],q=t.useCallback(c=>{i("banners",c,{shouldDirty:!0})},[i]),j=t.useCallback(c=>{const w=Na(c);return w!==!0?(s.error(w),!1):!0},[s]),{items:G,handleSelectFile:J,handleRemoveItem:se}=ea({value:W,onChange:q,maxFiles:K,mapValueToItem:ka,mapFileToValue:Aa,validateFile:j,onRemoveValue:c=>ga(c?.preview)}),pt=F?[{id:"icon",previewUrl:F}]:[];return t.createElement(ge,{open:e,title:"Informações do aplicativo",onClose:y,loading:o,disableSubmitOnEnter:!0,maxWidth:"md",fullWidth:!0,contentPadding:"px-24 py-28",Actions:t.createElement(t.Fragment,null,t.createElement(L,{onClick:y,color:"primary",variant:"outlined",disableElevation:!0,className:"font-bold"},"RETORNAR"),t.createElement(L,{type:"button",color:"primary",variant:"contained",className:"min-w-88 font-bold",disableElevation:!0,disabled:o,onClick:l(B,b)},"SALVAR"))},t.createElement("div",{className:"flex flex-col"},t.createElement("section",{className:"space-y-24 pb-16"},t.createElement(ce,null,"Informações básicas para publicação"),t.createElement("div",{className:"flex flex-col gap-20 sm:flex-row sm:items-stretch"},t.createElement("div",{className:"flex min-h-0 w-full flex-shrink-0 flex-col sm:w-160"},t.createElement(ke,{layout:"compact",compactVariant:Ht.profile,maxFiles:1,items:pt,disabled:o,onSelectFile:R,onRemove:()=>D()}),p.iconPreview?.message&&t.createElement(Q,{error:!0,className:"mx-0 mt-8"},p.iconPreview.message)),t.createElement("div",{className:"flex min-w-0 flex-1 flex-col gap-16"},t.createElement("div",{className:"grid grid-cols-1 gap-16 sm:grid-cols-2"},t.createElement(N,{name:"name",control:g,render:({field:c})=>t.createElement(S,{...c,label:"Nome do aplicativo",value:c.value,onChange:w=>c.onChange(w.target.value.slice(0,ae)),error:!!p.name,helperText:p.name?.message||t.createElement(Ie,{current:(c.value||"").length,max:ae}),FormHelperTextProps:p.name?void 0:Re.FormHelperTextProps,variant:"outlined",fullWidth:!0,required:!0,placeholder:"Clique para inserir"})}),t.createElement(N,{name:"category",control:g,render:({field:c})=>t.createElement(S,{...c,select:!0,label:"Categoria",error:!!p.category,helperText:p.category?.message,variant:"outlined",fullWidth:!0,required:!0,InputLabelProps:{shrink:!0},SelectProps:{displayEmpty:!0,renderValue:_a}},be.map(w=>t.createElement(I,{key:w.key,value:w.key},w.label)))})),t.createElement(N,{name:"shortDescription",control:g,render:({field:c})=>t.createElement(S,{...c,label:"Descrição visÃvel na loja de aplicativos (curta)",value:c.value,onChange:w=>c.onChange(w.target.value.slice(0,re)),error:!!p.shortDescription,helperText:p.shortDescription?.message||t.createElement(Ie,{current:(c.value||"").length,max:re}),FormHelperTextProps:p.shortDescription?void 0:Re.FormHelperTextProps,variant:"outlined",fullWidth:!0,required:!0,placeholder:"Clique para inserir"})}))),t.createElement("div",{className:"space-y-16"},t.createElement("div",{className:"space-y-8"},t.createElement("p",{className:"m-0 text-14 leading-normal text-gray-500"},"Informe a URL do link de instalação ou cadastro do seu aplicativo, para onde o usuário será direcionado ao clicar em âInstalarâ."),t.createElement(N,{name:"installUrl",control:g,render:({field:c})=>t.createElement(S,{...c,label:"URL",error:!!p.installUrl,helperText:p.installUrl?.message,variant:"outlined",fullWidth:!0,required:!0,placeholder:"Clique para inserir",autoComplete:"off"})})),t.createElement("div",{className:"space-y-8"},t.createElement("p",{className:"m-0 text-14 leading-normal text-gray-500"},"Informe a URL para onde a Cardápio Web redirecionará o usuário após ele aceitar a autorização da instalação."),t.createElement(N,{name:"redirectUri",control:g,render:({field:c})=>t.createElement(S,{...c,label:"Redirect URI",error:!!p.redirectUri,helperText:p.redirectUri?.message,variant:"outlined",fullWidth:!0,required:!0,placeholder:"https://seuapp.com/oauth/callback",autoComplete:"off"})})),t.createElement("div",{className:"space-y-8"},t.createElement("p",{className:"m-0 text-14 leading-normal text-gray-500"},"Informe a URL usada no botão âAcessarâ na tela do aplicativo, onde os usuários farão login no seu aplicativo."),t.createElement(N,{name:"authenticationUrl",control:g,render:({field:c})=>t.createElement(S,{...c,label:"URL",error:!!p.authenticationUrl,helperText:p.authenticationUrl?.message,variant:"outlined",fullWidth:!0,required:!0,placeholder:"Clique para inserir",autoComplete:"off"})})))),t.createElement(Z,null),t.createElement("section",{className:"space-y-20 pb-16 pt-16"},t.createElement(ce,null,"Permissões do aplicativo"),t.createElement("p",{className:"m-0 text-14 text-gray-500"},"Após aprovação só será possÃvel adicionar novas permissões"),t.createElement("div",{className:"flex flex-col gap-20",role:"group","aria-label":"Permissões"},Yt.map(c=>t.createElement(Ca,{key:c.id,permission:c,checked:U.includes(c.id),locked:Se(c.id,d),onToggle:()=>P(c.id)}))),p.permissions?.message&&t.createElement(Q,{error:!0,className:"mx-0"},p.permissions.message)),t.createElement(Z,null),t.createElement("section",{className:"space-y-24 pt-16"},t.createElement(ce,null,"Dados da página do aplicativo"),t.createElement(yt,{component:"fieldset",className:"w-full",error:!!p.visibility},t.createElement(xt,{component:"legend",className:"mb-12 text-16 font-semibold text-gray-600"},"Visibilidade na loja de aplicativos"),t.createElement(N,{name:"visibility",control:g,render:({field:c})=>t.createElement($e,{...c,row:!0,className:"gap-24",value:c.value,onChange:w=>c.onChange(w.target.value)},t.createElement(Y,{className:"m-0",value:"public",control:t.createElement(ee,{color:"primary",size:"small"}),label:t.createElement("span",{className:"text-16 text-gray-600"},"Público na loja de aplicativo")}),t.createElement(Y,{className:"m-0",value:"hidden",control:t.createElement(ee,{color:"primary",size:"small"}),label:t.createElement("span",{className:"text-16 text-gray-600"},"Não visÃvel")}))}),p.visibility?.message&&t.createElement(Q,{error:!0,className:"mx-0"},p.visibility.message)),t.createElement("section",{className:"space-y-8"},t.createElement("p",{className:"m-0 text-14 leading-normal text-gray-500"},"Informe a URL que receberá os eventos enviados pela Cardápio Web (opcional)."),t.createElement(N,{name:"webhookUrl",control:g,render:({field:c})=>t.createElement(S,{...c,label:"URL",error:!!p.webhookUrl,helperText:p.webhookUrl?.message,variant:"outlined",fullWidth:!0,placeholder:"Clique para inserir",autoComplete:"off"})})),_&&t.createElement(t.Fragment,null,t.createElement("section",{className:"space-y-24"},t.createElement(N,{name:"description",control:g,render:({field:c})=>t.createElement(xa,{key:`description-${a?.id??"new"}-${e}`,value:c.value,onChange:c.onChange,error:!!p.description,errorMessage:p.description?.message,maxLength:ue})})),t.createElement("section",{className:"space-y-16"},t.createElement(ke,{label:"Banners ilustrativos",maxFiles:K,multiple:!0,items:G,onSelectFile:J,onRemove:se,counter:`${G.length}/${K}`,maxReachedLabel:`Limite de ${K} banners atingido`}))))))},h={pending:"pending",approved:"approved",rejected:"rejected",disabled:"disabled"},at={[h.pending]:"Aguardando aprovação",[h.approved]:"Aprovado",[h.rejected]:"Reprovado",[h.disabled]:"Desativado"},ye={[h.pending]:"orange",[h.approved]:"green",[h.rejected]:"red",[h.disabled]:"grey"},De=[h.approved,h.pending,h.rejected,h.disabled];function rt({title:e,open:a,loading:r,onClose:n,onConfirm:o}){return t.createElement(wt,{open:a,onClose:r?void 0:n,maxWidth:"xs",fullWidth:!0,PaperProps:{className:"shadow-md rounded-12"}},t.createElement(Ct,{className:"p-0"},t.createElement("div",{className:"flex items-center justify-between px-20 py-16"},t.createElement("span",{className:"text-18 font-bold text-gray-700"},e),t.createElement(kt,{"aria-label":"Fechar",onClick:n,disabled:r,style:{padding:9}},t.createElement(ze,null)))),t.createElement(Z,null),t.createElement(At,{className:"px-20 py-16"},t.createElement("p",{className:"m-0 text-16 text-gray-600"},"Ao confirmar, não será possÃvel desfazer a ação.")),t.createElement(Z,null),t.createElement(Nt,{className:"space-x-12 px-20 py-16"},t.createElement(L,{variant:"outlined",color:"primary",onClick:n,disabled:r,disableElevation:!0},"CANCELAR"),t.createElement(L,{variant:"contained",color:"primary",onClick:o,disabled:r,disableElevation:!0,className:"min-w-88"},"CONFIRMAR")))}
3const Ra=({app:e,onReviewData:a,onOpenHomologation:r,onMutate:n})=>{const o=M(),s=je(),[u,d]=t.useState(null),[f,g]=t.useState(!1),[l,v]=t.useState(!1),m=e.status===h.pending,i=e.status===h.approved,E=e.status===h.disabled,x=e.status===h.rejected,p=m||x||i||E,k=ba(e),C=()=>d(null),_=t.useCallback(async()=>{C();try{await s({title:"Desativar aplicativo?",description:"O aplicativo não permitirá novas instalações, mas as instalações existentes serão mantidas.",cancellationText:"Cancelar",confirmationText:"Desativar"}),await z(e.id,{payload:{status:h.disabled,observation:"Desativado pelo administrador"}}),await n?.(),o.success("Aplicativo desativado")}catch(y){if(y===void 0)return;o.error(y.response?.data?.message||"Não foi possÃvel desativar o aplicativo")}},[o,e.id,s,n]),R=t.useCallback(async()=>{C();try{await s({title:"Reativar aplicativo?",description:"O aplicativo voltará ao estado aprovado e permitirá novas instalações.",cancellationText:"Cancelar",confirmationText:"Reativar"}),await z(e.id,{payload:{status:h.approved,observation:"Reativado pelo administrador"}}),await n?.(),o.success("Aplicativo reativado")}catch(y){if(y===void 0)return;o.error(y.response?.data?.message||"Não foi possÃvel reativar o aplicativo")}},[o,e.id,s,n]),D=t.useCallback(()=>{g(!1)},[]),P=t.useCallback(async()=>{v(!0);try{await z(e.id,{payload:{status:h.disabled,observation:"ExcluÃdo pelo administrador"}}),await n?.(),o.success("Aplicativo excluÃdo"),g(!1)}catch(y){o.error(y.response?.data?.message||"Não foi possÃvel excluir o aplicativo")}finally{v(!1)}},[o,e.id,n]);return t.createElement(t.Fragment,null,t.createElement(He,{tooltip:"Ações do aplicativo",onClick:y=>d(y.currentTarget)},t.createElement(Ge,{color:"inherit"})),t.createElement(Ve,{anchorEl:u,open:!!u,onClose:C,getContentAnchorEl:null,elevation:0,anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},classes:{paper:"border-1 border-solid border-gray-200 rounded-8 shadow-md"},keepMounted:!1},k&&t.createElement(I,{className:"py-12 text-16",onClick:()=>{C(),a(e)}},t.createElement(Kt,{className:"mr-12 text-gray-500",fontSize:"small"}),"Revisar dados"),p&&t.createElement(I,{className:"py-12 text-16",onClick:()=>{C(),r(e)}},t.createElement(we,{className:"mr-12 text-gray-500",fontSize:"small"}),"Homologação"),i&&t.createElement(I,{className:"py-12 text-16",onClick:_},t.createElement(Ye,{className:"mr-12 text-gray-500",fontSize:"small"}),"Desativar aplicativo"),E&&t.createElement(I,{className:"py-12 text-16",onClick:R},t.createElement(we,{className:"text-green-700 mr-12",fontSize:"small"}),"Reativar aplicativo")),t.createElement(rt,{title:"Confirmação de exclusão de aplicativo",open:f,loading:l,onClose:D,onConfirm:P}))},nt=({app:e,className:a="h-48 w-48"})=>{if(e?.iconPreview)return t.createElement("img",{src:e.iconPreview,alt:"",className:`${a} flex-shrink-0 rounded-8 object-cover`});const r=e?.name?.charAt(0)?.toUpperCase()||"A";return t.createElement("div",{className:`${a} flex flex-shrink-0 items-center justify-center rounded-8 bg-yellow-lighter bg-opacity-50 text-20 font-bold text-yellow-dark`},r)},Ue=6,Te=6,me=8;function Ia(e){if(!e)return"";if(e.length<=Ue+Te){const a=Math.max(1,Math.floor(e.length/3)),r=Math.max(1,e.length-a);return a+r>=e.length?"*".repeat(Math.min(me,e.length)):`${e.slice(0,a)}${"*".repeat(me)}${e.slice(-r)}`}return`${e.slice(0,Ue)}${"*".repeat(me)}${e.slice(-Te)}`}const Da=({value:e,disabled:a})=>{const r=M();return t.createElement(St,{position:"end"},t.createElement(_t.CopyToClipboard,{text:e||"",onCopy:()=>{e&&r.success("Copiado!")}},t.createElement(L,{type:"button",size:"small",variant:"outlined",disabled:!e||a,className:"min-w-0 whitespace-nowrap border-gray-200 text-14 font-semibold text-gray-600",startIcon:t.createElement(Pt,{fontSize:"small"}),onMouseDown:n=>n.preventDefault()},"Copiar")))},X=({label:e,value:a,disabled:r,placeholder:n,onChange:o,readOnly:s=!0,obfuscate:u=!1})=>{const d=u?Ia(a):a||"";return t.createElement(S,{label:e,value:d,placeholder:n,onChange:o,variant:"outlined",fullWidth:!0,disabled:r,InputProps:{readOnly:u||s&&!o,endAdornment:t.createElement(Da,{value:a})}})};function ot(e){return!!(e.removeLogo&&e.initialLogoUrl)}function st(e){const a=e.initialBannerUrls||[];if(!a.length)return!1;const r=et(e.banners);return r.length<a.length||a.some(n=>!r.includes(n))}
3function it(e,a){return ot(a)&&(e.logo=null),e}function Ua(e){return dt(e)||ot(e)||st(e)}function lt(e){const a=e.status;return{id:e.id,integratorId:e.integrator_id,name:e.name,category:e.category,shortDescription:e.short_description,description:e.long_description,visibility:e.is_public?"public":"hidden",installUrl:e.installation_url,redirectUri:e.redirect_url||"",authenticationUrl:e.login_url||e.authentication_url||e.auth_url||e.auth_link||"",loginUrl:e.login_url||e.authentication_url||e.auth_url||e.auth_link||"",site:e.site_url||"",permissions:te(e.permissions),lockedPermissions:te(e.permissions),webhookActive:!!e.webhook_active,usesWebhook:!!e.webhook_active,webhookUrl:e.webhook_url||"",webhookSecret:e.webhook_token||e.webhook_secret||"",iconPreview:e.logo_url||null,bannerPreviews:e.banner_images_urls||[],banners:(e.banner_images_urls||[]).map(r=>({preview:r})),iconFile:null,status:a,active:a===h.approved,observation:e.observation||"",clientSecret:e.client_secret||"",clientId:e.client_id||"",savedAt:e.updated_at||e.created_at,createdAt:e.created_at}}function ct(e,a,r){const n=a.visibility==="public",o=n?a.description?.trim():a.shortDescription?.trim(),s={integrator_id:e.id,name:a.name.trim(),installation_url:a.installUrl.trim(),redirect_url:a.redirectUri.trim(),login_url:a.authenticationUrl.trim(),authentication_url:a.authenticationUrl.trim(),short_description:a.shortDescription.trim(),long_description:o,is_public:n,category:a.category,permissions:r};return(a.webhookActive||a.usesWebhook||a.webhookUrl?.trim())&&(s.webhook_active=!0,a.webhookUrl?.trim()&&(s.webhook_url=a.webhookUrl.trim())),it(s,a)}function mt(e,a){const{permissions:r,...n}=a;Object.entries(n).forEach(([o,s])=>{if(s===null){e.append(`marketplace_app[${o}]`,"");return}if(s!==void 0&&s!==""){const u=typeof s=="boolean"?s?"true":"false":String(s);e.append(`marketplace_app[${o}]`,u)}}),(r||[]).forEach(o=>{e.append("marketplace_app[permissions][]",o)})}function Ta(e,a,r){const n=new FormData,o=ct(e,a,r);return mt(n,o),a.iconFile&&n.append("marketplace_app[logo]",a.iconFile,a.iconFile.name),Ee(a.banners).forEach(s=>{n.append("marketplace_app[banner_images][]",s,s.name)}),n}function dt(e){return!!(e.iconFile||Ee(e.banners).length)}function ut(e,a){const r=e.visibility==="public",n=r?e.description?.trim():e.shortDescription?.trim(),o={name:e.name.trim(),installation_url:e.installUrl.trim(),redirect_url:e.redirectUri.trim(),login_url:e.authenticationUrl.trim(),authentication_url:e.authenticationUrl.trim(),short_description:e.shortDescription.trim(),long_description:n,is_public:r,category:e.category,permissions:a};return e.webhookActive!==void 0&&(o.webhook_active=!!e.webhookActive),e.webhookUrl!==void 0&&(o.webhook_url=e.webhookUrl?.trim()||null),it(o,e)}function Fa(e,a,r=[]){const n=new FormData,o=ut(e,a);mt(n,o),e.iconFile&&n.append("marketplace_app[logo]",e.iconFile,e.iconFile.name);const s=Ee(e.banners);return r.length+s.length>0?(r.forEach(d=>{n.append("marketplace_app[banner_images][]",d,d.name)}),s.forEach(d=>{n.append("marketplace_app[banner_images][]",d,d.name)})):st(e)&&n.append("marketplace_app[banner_images][]",""),n}const La=e=>be.find(a=>a.key===e)?.label||e,Fe=(e,a)=>{a.setWebhookActive(!!e.webhookActive),a.setWebhookUrl(e.webhookUrl||""),a.setWebhookSecret(e.webhookSecret||"")},Oa=({app:e,onReviewData:a,onOpenHomologation:r,onMutate:n})=>{const o=M(),s=e.status===h.approved,u=e.status===h.rejected,d=e.status===h.disabled,f=(s||e.status===h.pending)&&!u&&!d,g=u||d,[l,v]=t.useState(()=>!!e.webhookActive),[m,i]=t.useState(e.webhookUrl||""),[E,x]=t.useState(e.webhookSecret||""),[p,k]=t.useState(!1),C=t.useRef(l);C.current=l,t.useEffect(()=>{Fe(e,{setWebhookActive:v,setWebhookUrl:i,setWebhookSecret:x})},[e]);const _=t.useCallback(P=>{if(!P)return;const y=lt(P);Fe(y,{setWebhookActive:v,setWebhookUrl:i,setWebhookSecret:x})},[]),R=t.useCallback(async P=>{try{const y=await z(e.id,{payload:P});return _(y),await n?.(),y}catch(y){throw o.error(y.response?.data?.message||"Não foi possÃvel atualizar o aplicativo"),y}},[o,e.id,_,n]),D=t.useCallback(async(P,y)=>{const B=l;v(y),k(!0);try{await R({webhook_active:y})}
3catch{v(B)}finally{k(!1)}},[R,l]);return t.createElement("div",{className:"space-y-20 rounded-12 border border-solid border-gray-200 p-20"},t.createElement("div",{className:"flex items-start justify-between space-x-16"},t.createElement("div",{className:"flex min-w-0 flex-1 items-center space-x-16"},t.createElement(nt,{app:e}),t.createElement("div",{className:"min-w-0 space-y-8"},t.createElement("div",{className:"truncate text-18 font-bold text-gray-600"},e.name),t.createElement("div",{className:"flex flex-wrap items-center gap-8"},t.createElement(H,{color:ye[e.status]||"grey"},at[e.status]||e.status),e.category&&t.createElement(H,{color:"grey"},La(e.category))))),t.createElement(Ra,{app:e,onReviewData:a,onOpenHomologation:r,onMutate:n})),e.observation&&t.createElement("div",{className:he("rounded-8 p-12 text-15 leading-relaxed",u||d?"bg-red-lightest text-red-darker":e.status===h.pending?"bg-orange-lightest text-orange-dark":"bg-gray-50 text-gray-600")},u||d?e.observation:t.createElement(t.Fragment,null,t.createElement("span",{className:"font-semibold"},"Observação: "),e.observation)),t.createElement("div",{className:"space-y-16"},s?t.createElement("div",{className:"flex flex-col gap-16"},t.createElement(X,{label:"Client Id",value:e.clientId}),t.createElement(X,{label:"Client Secret",value:e.clientSecret,obfuscate:!0})):!d&&t.createElement("p",{className:"text-14 text-gray-500"},"à necessário aprovar o aplicativo para visualizar Client Secret e Client Id."),f&&t.createElement("div",{className:"space-y-16"},t.createElement(Y,{className:"m-0",control:t.createElement(Rt,{color:"primary",checked:l,onChange:D,disabled:g||p}),label:t.createElement("span",{className:"text-16 font-semibold text-gray-600"},"Ativar envio de Webhook")}),l&&t.createElement("div",{className:"flex flex-col gap-16"},t.createElement(X,{label:"URL do Webhook",value:m,readOnly:!1,placeholder:"https://api.exemplo.com/webhook",disabled:!0}),t.createElement(X,{label:"Token",value:E,obfuscate:!0,disabled:!0})))))},Ma=({open:e,app:a,onClose:r,onMutate:n})=>{const o=M(),[s,u]=t.useState("approve"),[d,f]=t.useState(""),[g,l]=t.useState(!1),v=a?.status===h.rejected;t.useEffect(()=>{e&&a&&(u(a.status===h.rejected||a.status===h.disabled?"disapprove":"approve"),f(a.observation||""))},[a,e]);const m=async()=>{if(s==="disapprove"&&!d.trim()){o.warning("Ao desaprovar/rejeitar é obrigatório adicionar uma observação");return}l(!0);try{const i={status:s==="approve"?h.approved:h.rejected,observation:d.trim()};await z(a.id,{payload:i}),await n?.(),s==="approve"?o.success(v?"Aplicativo reaprovado com sucesso":"Aplicativo aprovado com sucesso"):o.success("Aplicativo rejeitado"),r()}catch(i){o.error(i.response?.data?.message||"Não foi possÃvel atualizar o aplicativo")}finally{l(!1)}};return a?t.createElement(ge,{open:e,title:"Homologação do aplicativo (Aprovar/Desaprovar)",loading:g,onClose:r,onSubmit:i=>{i.preventDefault(),m()},cancelText:"RETORNAR",confirmText:"SALVAR",maxWidth:"sm",contentPadding:"p-24"},t.createElement("div",{className:"space-y-24"},t.createElement("div",{className:"flex items-center space-x-16 rounded-8 border border-solid border-gray-200 p-16"},t.createElement(nt,{app:a}),t.createElement("div",{className:"space-y-8"},t.createElement("div",{className:"text-18 font-bold text-gray-600"},a.name),t.createElement(H,{color:ye[a.status]||"grey"},at[a.status]||a.status))),t.createElement($e,{value:s,onChange:i=>u(i.target.value)},t.createElement(Y,{value:"approve",control:t.createElement(ee,{color:"primary"}),label:"Aprovar aplicativo"}),t.createElement(Y,{value:"disapprove",control:t.createElement(ee,{color:"primary"}),label:"Desaprovar aplicativo"})),s==="approve"&&v&&t.createElement("p",{className:"rounded-8 bg-green-lightest p-12 text-14 text-green-darker"},"O aplicativo será reaprovado e voltará ao estado ",t.createElement("strong",null,"Aprovado"),", permitindo novas instalações."),s==="disapprove"&&(a.status===h.approved||a.status===h.disabled)&&t.createElement("p",{className:"rounded-8 bg-red-lightest p-12 text-14 text-red-darker"}
3,"Ao rejeitar, o aplicativo ",t.createElement("strong",null,"não permitirá novas instalações")," e as"," ",t.createElement("strong",null,"instalações ativas serão revogadas"),". Informe o motivo abaixo."),t.createElement(S,{label:s==="disapprove"?"Motivo da rejeição (obrigatório)":"Observação (opcional)",value:d,onChange:i=>f(i.target.value),variant:"outlined",fullWidth:!0,multiline:!0,rows:4,error:s==="disapprove"&&!d.trim(),helperText:s==="disapprove"&&!d.trim()?"Ao desaprovar/rejeitar é obrigatório adicionar uma observação":""}))):null},Ba=e=>O.get(e).then(a=>a.data);function Wa(e,a={}){const{page:r=1,per_page:n=100,status:o,q:s}=a,u=e?na({integratorId:e,page:r,per_page:n,status:o,q:s}):null,{data:d,error:f,isLoading:g,mutate:l}=Le(u,Ba,{dedupingInterval:5e3,revalidateOnFocus:!1});return{apps:t.useMemo(()=>(d?.marketplace_apps||[]).map(lt),[d?.marketplace_apps]),meta:d?.meta,isLoading:g,isError:!!f,mutate:l}}const qa=(e,a)=>{const r=e?.response?.data;if(typeof r?.message=="string")return r.message;if(r?.errors&&typeof r.errors=="object"){const n=Object.values(r.errors).flat()[0];if(typeof n=="string")return n}return a};async function ja(e){return(await Promise.all(e.map(async r=>{try{const o=await(await fetch(r)).blob(),s=r.split("/").pop().split("?")[0]||"banner";return new File([o],s,{type:o.type})}catch{return null}}))).filter(Boolean)}const $a=({integrator:e,onAddAppActionChange:a})=>{const r=M(),{apps:n,isLoading:o,isError:s,mutate:u}=Wa(e?.id),[d,f]=t.useState(""),[g,l]=t.useState(!1),[v,m]=t.useState(!1),[i,E]=t.useState(null),[x,p]=t.useState(null),[k,C]=t.useState(!1),_=t.useMemo(()=>{const b=d.trim().toLowerCase();return b?n.filter(F=>F.name.toLowerCase().includes(b)):n},[n,d]),R=t.useCallback(async b=>{if(!e?.site?.trim()){r.warning("Cadastre o site da integradora antes de criar um aplicativo");return}const F=va(b.permissions,x?.lockedPermissions||[]),W=[...new Set([...F,...b.permissions])],U={...b,permissions:W};C(!0);try{if(x?.id){const q=ut(U,W),j=Ua(U);let G;if(j){const J=et(U.banners||[]),se=J.length?await ja(J):[];G=Fa(U,W,se)}await z(x.id,{payload:j?void 0:q,formData:G}),r.success("Aplicativo atualizado com sucesso")}else{const q=ct(e,U,W),j=dt(U);await oa({payload:j?void 0:q,formData:j?Ta(e,U,W):void 0}),r.success("Aplicativo salvo e enviado para homologação")}await u(),l(!1),p(null)}catch(q){r.error(qa(q,x?.id?"Não foi possÃvel atualizar o aplicativo":"Não foi possÃvel criar o aplicativo"))}finally{C(!1)}},[r,e,u,x]),D=t.useCallback(b=>{p(b),l(!0)},[]),P=t.useCallback(b=>{E(b),m(!0)},[]),y=t.useCallback(()=>{p(null),l(!0)},[]),B=t.useCallback(()=>{l(!1),p(null)},[]);return t.useEffect(()=>(a?.(()=>y),()=>{a?.(null)}),[y,a]),t.createElement("div",{className:"flex h-full min-h-0 flex-col gap-20 p-24"},t.createElement("div",null,t.createElement(jt,{placeholder:"Pesquisar pelo nome",value:d,onChange:b=>f(b.target.value),wrapperClassName:"w-full",className:"w-full",cleanable:!0})),t.createElement("div",{className:"min-h-0 flex-1 overflow-auto"},o?t.createElement("p",{className:"text-14 text-gray-500"},"Carregando aplicativos..."):s?t.createElement("p",{className:"text-14 text-red"},"Não foi possÃvel carregar os aplicativos."):_.length===0?t.createElement(It,{className:"h-full py-40 text-gray-500",title:"Nenhum aplicativo adicionado",colorIcon:"text-purple-main",ActionButton:t.createElement(L,{variant:"outlined",color:"primary",disableElevation:!0,className:"sm:max-w-520 mt-20 w-full py-12 text-16 font-bold",onClick:y},"ADICIONAR APP")},t.createElement("p",{className:"max-w-520 m-0 text-center text-16 text-gray-500"},"Crie e faça a análise de aplicativo clicando no botão a seguir")):t.createElement("div",{className:"space-y-20 pb-8"},_.map(b=>t.createElement(Oa,{key:b.id,app:b,onReviewData:D,onOpenHomologation:P,onMutate:u})))),t.createElement(Pa,{open:g,loading:k,defaultValues:x,onClose:B,onSave:R}),t.createElement(Ma,{open:v,app:i,onClose:()=>{m(!1),E(null)},onMutate:u}))},oe=Dt(e=>({filters:{page:1,per_page:10,q:{}},updateFilter:(a,r)=>e(n=>({...n,filters:a==="page"?{...n.filters,[a]:r}:{...n.filters,[a]:r,page:1}}))})),za=()=>{const e=Ut(),a=Je(),r=oe(E=>E.filters),{data:n}=Qe(r),[o,s]=t.useState(!1),[u,d]=t.useState(null),[f,g]=t.useState(null);t.useEffect(()=>{e.has("integradora")?(d(e.get("integradora")),s(!0)):(s(!1),d(null))},[e]);const l=t.useMemo(()=>
3n?.find(E=>String(E.id)===String(u)),[n,u]),v=t.useCallback(()=>a.goBack(),[a]),m=!!(l&&f),i=t.useCallback(()=>t.createElement("div",{className:"flex w-full items-center justify-end gap-16 px-8"},t.createElement(L,{color:"primary",variant:"outlined",disableElevation:!0,className:"min-w-140 font-bold",onClick:v},"CANCELAR"),t.createElement(L,{color:"primary",variant:"contained",disableElevation:!0,className:"min-w-200 font-bold",onClick:()=>f(),disabled:!m},"ADICIONAR APP")),[m,v,f]);return t.createElement(qt,{title:"Gerenciar aplicativos",open:o,onClose:v,width:"min(100vw, 520px)",Footer:i},l?t.createElement($a,{integrator:l,onAddAppActionChange:g}):t.createElement("div",{className:"p-24 text-16 text-gray-500"},"Integradora não encontrada."))},Ha=[{field:"document",label:"CPF/CNPJ",type:"string"},{field:"site",label:"Site",type:"string"},{field:"telephone",label:"Telefone",type:"string"},{field:"active",label:"Ativo",type:"list_eq_required",valueOptions:[{key:"true",label:"Sim"},{key:"false",label:"Não"}],valueOptionKey:"key",valueOptionLabel:"label"},{field:"created_at",label:"Data de criação",value:"today",type:"date"},{field:"token_last_used_at",label:"Ãltimo uso do token",value:"today",type:"date"}],Ga=[{field:"name_or_email",label:"Pesquisar integradora",operation:"i_cont",type:"string",valueInputProps:{placeholder:"Pesquisar por nome ou e-mail",className:"my-6 mr-12 sm:min-w-320 sm:flex-1 sm:max-w-480"}}];function Va({openIntegratorDialog:e}){const a=oe(o=>o.updateFilter),{hasUserRolePermissions:r}=Ke(),n=t.useCallback(o=>a("q",o),[a]);return t.createElement(Xt,{fields:Ha,fixedFields:Ga,onFilterChange:n,wrapperClassName:"rounded-8 border border-solid border-grey-border bg-white py-6 pl-12 pr-12",actions:r(de.INTEGRATORS_MANAGE)?t.createElement("div",{className:"my-6 ml-auto flex flex-shrink-0 items-center"},t.createElement("button",{type:"button",className:"inline-flex cursor-pointer items-center space-x-8 whitespace-nowrap rounded-6 border border-solid border-gray-200 bg-gray-50 py-8 pl-12 pr-16 text-16 font-bold text-gray-600 hover:bg-gray-100",onClick:e},t.createElement(Tt,{fontSize:"small"}),t.createElement("span",null,"Cadastrar integradora"))):null})}function Ya({integrator:e,openIntegratorDialog:a,onMutate:r}){const n=M(),o=Je(),{mutate:s}=Oe(),{hasUserRolePermissions:u}=Ke(),[d,f]=t.useState(null),[g,l]=t.useState(!1),[v,m]=t.useState(!1),i=u(de.INTEGRATORS_MANAGE),E=u(de.INTEGRATORS_VIEW_TOKEN),x=()=>{f(null)},p=b=>{b.stopPropagation(),f(b.currentTarget)},k=t.useCallback(async()=>{await r?.(),await s(fe())},[s,r]),C=t.useCallback(async()=>{x();try{const b=await ra(e.id);await navigator.clipboard.writeText(b.token),n.success("Token copiado")}catch(b){n.error(b.response?.data?.message||"Erro ao copiar token")}},[n,e.id]),_=t.useCallback(async()=>{x();const b=!e.active;try{await Xe(e.id,{active:b}),await k(),n.success(b?"Integrador ativado":"Integrador desativado")}catch(F){n.error(F.response?.data?.message||"Erro ao desativar integrador")}},[n,e.active,e.id,k]),R=t.useCallback(()=>{x(),l(!0)},[]),D=t.useCallback(()=>{v||l(!1)},[v]),P=t.useCallback(async()=>{m(!0);try{await aa(e.id),await k(),n.success("Integradora excluÃda com sucesso"),l(!1)}catch(b){n.error(b.response?.data?.message||"Não foi possÃvel excluir a integradora")}finally{m(!1)}},[n,e.id,k]),y=t.useCallback(()=>{x(),o.push({search:`integradora=${e.id}`})},[o,e.id]),B=t.useCallback(()=>{x(),a(e)},[e,a]);return!i&&!E?null:t.createElement(t.Fragment,null,t.createElement(He,{tooltip:"Ações",onClick:p},t.createElement(Ge,{color:"inherit"})),t.createElement(Ve,{anchorEl:d,open:!!d,onClose:x,onClick:b=>b.stopPropagation(),getContentAnchorEl:null,elevation:0,anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},classes:{paper:"border-1 border-solid border-gray-200 rounded-8 shadow-md"},keepMounted:!1},i&&t.createElement(I,{className:"py-12 text-16",onClick:B},t.createElement(Ft,{className:"mr-12 text-gray-500",fontSize:"small"}),"Editar integrador"),E&&t.createElement(I,{className:"py-12 text-16",onClick:C},t.createElement(Zt,{className:"mr-12 text-gray-500",fontSize:"small"}),"Copiar token"),i&&t.createElement(I,{className:"py-12 text-16",onClick:y},t.createElement(Qt,{className:"mr-12 text-gray-500",fontSize:"small"}),"Gerenciar aplicativos"),i&&t.createElement(I,{className:"py-12 text-16",onClick:_},t.createElement(Ye,{className:"mr-12 text-gray-500",fontSize:"small"}),e.active?"Desativar integrador":"Ativar integrador"),i&&t.createElement(I,{className:"py-12 text-16 text-red-dark",onClick:R},t.createElement(Lt,{className:"mr-12",fontSize:"small"}),"Excluir integrador")),t.createElement(rt,{title:"Confirmação de exclusão de integrador",open:g,loading:v,onClose:D,onConfirm:P}))}const Ja={approved:qe,pending:Mt,rejected:ze,disabled:Ot};function Ka({statusSummary:e={}}){return De.some(r=>Number(e[r])>0)?t.createElement("div",{className:"flex flex-wrap items-center gap-6"},De.map(r=>{const n=e[r];if(!n||n<=0)return null;const o=Ja[r];return t.createElement(H,{key:r,color:ye[r],className:"inline-flex h-24 min-w-0 items-center justify-center gap-4 roun
3ded-4 px-6 py-0 text-12 font-bold leading-none"},t.createElement(o,{style:{fontSize:12}}),t.createElement("span",null,n))})):t.createElement("span",{className:"text-14 text-gray-400"},"â")}function Xa({email:e,site:a}){return e&&a?`${e} - ${a}`:e||a||null}function Qa({row:e}){const a=Xa(e);return t.createElement("div",{className:"min-w-0 py-4"},t.createElement("div",{className:"truncate text-16 font-semibold leading-tight text-gray-600",title:e.name},e.name),a&&t.createElement("div",{className:"mt-4 truncate text-14 font-normal leading-tight text-gray-400",title:a},a))}function Za({active:e}){return e?t.createElement(H,{color:"green",className:"text-13 font-semibold"},"Ativo"):t.createElement(H,{color:"grey",className:"text-13 font-semibold"},"Desativado")}function er({openIntegratorDialog:e}){const a=oe(l=>l.filters),r=oe(l=>l.updateFilter),{data:n,totalRecords:o,mutate:s,isLoading:u,isError:d}=Qe(a),f=l=>{r("page",l+1)},g=l=>{r("per_page",l)};return t.createElement(Bt,{data:n,totalRows:o,onChangePage:f,onChangeRowsPerPage:g,onRowClick:l=>e(l),resetCurrentPage:a.page===1,loading:u,loadingRowsQuantity:5,showError:d,stickyHeader:!0,columns:[{Header:"Status",accessor:"active",sortable:!1,className:"w-120 min-w-120",formatDataFunction:l=>t.createElement(Za,{active:l})},{Header:"Integrador",sortable:!1,className:"min-w-300",Cell:Qa},{Header:"Criado",accessor:"created_at",sortable:!1,className:"w-120 min-w-120 whitespace-nowrap text-16 text-gray-600",formatDataFunction:l=>Ce(l).format("DD/MM/YYYY")},{Header:"Ãltimo uso",accessor:"token_last_used_at",sortable:!1,className:"w-160 min-w-160 whitespace-nowrap text-16 text-gray-600",formatDataFunction:l=>l?Ce(l).format("DD/MM/YYYY HH:mm"):t.createElement("span",{className:"text-14 text-gray-400"},"â")},{Header:"Aplicativos",sortable:!1,className:"min-w-220",Cell:({row:l})=>t.createElement(Ka,{statusSummary:l.marketplace_apps_status_summary})},{Header:"",sortable:!1,align:"right",className:"w-56 min-w-56",Cell:({row:l})=>t.createElement("div",{className:"flex items-center justify-end pr-4",onClick:v=>v.stopPropagation()},t.createElement(Ya,{integrator:l,openIntegratorDialog:e,onMutate:s}))}]})}function hr(){const[e,a]=t.useState({open:!1,data:null}),r=t.useCallback(o=>{a({open:!0,data:o||null})},[]),n=t.useCallback(()=>{a({open:!1,data:null})},[]);return t.createElement(Wt,null,t.createElement("div",{className:"flex w-full flex-1 flex-col space-y-24 overflow-auto px-12 py-24 sm:px-28"},t.createElement(Va,{openIntegratorDialog:r}),t.createElement(er,{openIntegratorDialog:r}),t.createElement(la,{open:e.open,defaultValues:e.data,onClose:n}),t.createElement(za,null)))}export{hr as default}; 4 5//# debugId=87e8c020-2c80-51fa-9e9d-4c11a518ed87
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.