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]="12b1bcd8-c41e-5423-a1cd-1b8624aaf2d3")}catch(e){}}(); 3import{Q as Ee,R as e,a6 as A,bg as ve,dU as be,bf as Ze,X as Ke,W as he,aj as et,ao as Ne,Y as U,C as ye,bk as tt,bs as at,M as nt,k as rt,aN as it,bi as ot,j as le,aJ as xe,gd as H,v as st,x as lt,aR as ct,aY as ce,I as dt,aG as mt}from"./index-Cs-In7Vx.js";import{H as ut}from"./HelpOutlineRounded-BdKAN6Cs.js";import{c as q,B as ee,h as G,w as X}from"./cacheKeys-Px_UUtmK.js";import{g as pt}from"./errors-BL8YlbI8.js";import{C as Te}from"./CardLoadingOverlay-BBx8AjSw.js";import{P as ft,u as Ie,q as gt,H as Et}from"./useIntegrationTemplates-C7sVRBPz.js";import{u as Ce,d as vt,K as bt,T as ht,a as Nt,b as B,c as yt}from"./useTemplateMutations-Bd5usizi.js";import{S as xt}from"./SendRounded-F14-gZ8F.js";import{S as Tt}from"./meta-Bd4svD5c.js";import{H as It}from"./ViewHeadlineRounded-CNvGi08T.js";import{u as Ct,i as St}from"./useIntegrationOverview-Dol5EBAf.js";import"./ArrowBackRounded-d_5Kt6BO.js";import"./FiberManualRecord-B1d1Mzjb.js";import"./useGetCoupons-D015gTvi.js";function Se(t){return t?t.order_notification_setting?t.order_notification_setting:t:{}}async function wt(){const t=await Ee.get("/api/v2/company/order_notification_settings");return Se(t.data)}async function we(t){const n=await Ee.put("/api/v2/company/order_notification_settings",{order_notification_setting:t});return Se(n.data)}function _e(t){return`${t}_notification_active`}function Oe(t){return`${t}_notification_message`}function Ae(t,n){return{...t&&typeof t=="object"?t:{},...n}}function _t(t,n,{enabled:r,textBody:a}){const o={};if(typeof r=="boolean"&&(o[_e(n)]=r),a!==void 0){const l=String(a??"").trim();o[Oe(n)]=l||null}return Ae(t,o)}const ke=["delivery","takeout","onsite"],Ot={delivery:"Entrega",takeout:"Retirada",onsite:"Consumo no local"};function de(t){return Array.isArray(t)?t.filter(n=>ke.includes(n)):[]}async function At(t,n){const r=Ae(t,n);return we(r)}const kt=[{value:"OFFICIAL_META",label:"No número configurado na API oficial da Meta",description:"Configure em: Gerenciar whatsapp > Gestão de números "},{value:"UNOFFICIAL_EXTENSION",label:"No número conectado à extensão de Whatsapp",description:"Configure em: Integrações > Cardapinho"}];function Pt({isActive:t,notificationProvider:n,onToggleActive:r,onChangeProvider:a,portalOrderTypes:o=[],onChangePortalOrderTypes:l,hasOfficialIntegration:u,isSaving:d,isSavingOrderTypes:p}){const f=n??"UNOFFICIAL_EXTENSION",I=d||p,E=d||p,v=s=>{if(I||!l)return;const y=o.includes(s)?o.filter(N=>N!==s):[...o,s];l(y)};return e.createElement("div",{className:"relative rounded-12 border border-solid border-gray-200 bg-white p-20"},e.createElement(Te,{loading:E}),e.createElement("div",{className:"flex items-center justify-between gap-16"},e.createElement("div",{className:"text-16 font-semibold text-gray-800"},"Sistema automatizado de envio de status de pedido via Whatsapp"),e.createElement("div",{className:"flex shrink-0 items-center gap-8"},e.createElement("span",{className:A("rounded-full px-8 py-4 text-12 font-semibold",t?"bg-green-lightest text-green-dark":"bg-gray-100 text-gray-500")},t?"Ativo":"Inativo"),e.createElement(ve,{checked:t,color:"primary",onChange:s=>r(s.target.checked),disabled:d,size:"small"}))),t&&e.createElement("div",{className:"mt-16 grid grid-cols-1 gap-32 sm:grid-cols-2"},u?e.createElement("div",null,e.createElement("div",{className:"mb-8 text-12 font-semibold uppercase tracking-wide text-gray-400"},"Canal de envio"),e.createElement("div",{className:"space-y-16"},kt.map(s=>{const h=f===s.value;return e.createElement("button",{key:s.value,type:"button",disabled:d,onClick:()=>!d&&a(s.value),className:A("w-full rounded-8 border border-solid px-16 py-12 text-left transition-colors",h?"border-purple bg-purple-lightest":"border-gray-200 bg-white hover:border-gray-300",d&&"cursor-not-allowed opacity-60")},e.createElement("div",{className:"flex items-center gap-8"},e.createElement("span",{className:A("flex h-16 w-16 shrink-0 items-center justify-center rounded-full border-2 border-solid",h?"border-purple":"border-gray-300")},h&&e.createElement("span",{className:"h-8 w-8 rounded-full bg-purple"})),e.createElement("span",{className:A("text-16",h?"font-semibold text-purple-dark":"text-gray-700")},s.label)),s.description&&e.createElement("div",{className:"mt-4 pl-24 text-16 text-gray-400"},s.description))}))):e.createElement("div",{className:"flex items-start gap-8 rounded-8 border border-solid border-blue-lighter bg-blue-lightest px-16 py-12"},e.createElement(be,{className:"mt-4 shrink-0 text-16 text-blue-dark"}),e.createElement("div",null,e.createElement("div",{className:"text-16 font-semibold text-blue-darker"},"Nenhum número da API Oficial da Meta foi encontrado."),e.createElement("div",{className:"mt-4 text-16 text-blue-dark"},"Você precisa dessa configuração para enviar modelos de mensagem a clientes que não interagem com você há mais de 24 horas."),e.createElement("div",{className:"mt-12 text-16 text-blue-dark"}
3,e.createElement("strong",null,"Como resolver:")," Vá em Gerenciar WhatsApp > Gestão de Números, clique em Conectar via Meta e vincule a sua conta."))),e.createElement("div",null,e.createElement("div",{className:"mb-8 text-12 font-semibold uppercase tracking-wide text-gray-400"},"Habilitar envio para os tipos de pedido no portal"),e.createElement("div",{className:"space-y-4"},ke.map(s=>e.createElement(Ze,{key:s,control:e.createElement(Ke,{size:"small",color:"primary",checked:o.includes(s),onChange:()=>v(s),disabled:I}),label:e.createElement("span",{className:"text-16 text-gray-700"},Ot[s]),className:"flex items-center"}))))))}const Z=["waiting_confirmation","pending_online_payment","confirmed","scheduled_confirmed","waiting_to_catch","released","closed","canceled"],V={waiting_confirmation:"WAITING_CONFIRMATION",pending_online_payment:"PENDING_ONLINE_PAYMENT",confirmed:"CONFIRMED",scheduled_confirmed:"SCHEDULED_CONFIRMED",waiting_to_catch:"WAITING_TO_CATCH",released:"RELEASED",closed:"CLOSED",canceled:"CANCELED"},Pe=Object.fromEntries(Object.entries(V).map(([t,n])=>[n,t])),te={waiting_confirmation:"Pedido recebido",pending_online_payment:"Aguardando pagamento via Pix",confirmed:"Pedido em preparação",scheduled_confirmed:"Agendamento confirmado",waiting_to_catch:"Pedido pronto",released:"Pedido saiu para entrega",closed:"Pedido concluÃdo",canceled:"Pedido cancelado"},Ft={pending_online_payment:!1},Mt={pending_online_payment:!1};function K(t){return Ft[t]!==!1}function z(t){return Mt[t]!==!1}const Fe={waiting_confirmation:`Olá, {{nome}} ð! *Recebemos o seu pedido* e em breve vamos começar a prepará-lo. 4Vou te atualizando sobre o status do seu pedido por aqui ð.`,confirmed:"Vim aqui te dizer que *já estamos preparando* o seu pedido ð!",scheduled_confirmed:"O agendamento do seu pedido foi confirmado para a data escolhida â !",waiting_to_catch:"Seu pedido já *está pronto* ð¤©!",released:"Seu pedido já está a caminho ðµ!",closed:`Agradecemos a preferência e esperamos te reencontrar em breve ð! 5 6_O que acha de clicar no link abaixo e avaliar o nosso serviço_ ð? 7{{link_avaliacao}}`,canceled:"Infelizmente o seu pedido foi *cancelado* ð. Caso queira mais informações é só falar com a gente."};function Me(t,n){const r=String(n??"").trim();return r||(Fe[t]??"")}function Rt(t){return!String(t??"").trim()}const Lt=Object.fromEntries(Z.map(t=>[t,K(t)?ft:[]])),$=300;function Dt(t,n){return Array.isArray(t)?t.filter(r=>!r?.notificationType||r.notificationType===n):[]}function jt({open:t,onClose:n,companyId:r,integrationId:a,notificationType:o,onPick:l,onTemplateDeleted:u,selectedTemplateId:d=null}){const p=he(),f=et(),I=Pe[o],E=te[I]??o,[v,s]=e.useState(null),[h,y]=e.useState(!1),N=e.useMemo(()=>!t||!r||!a?null:{companyId:r,integrationId:a,page:1,limit:50,type:"NOTIFICATION"},[r,a,t]),{templates:x,isLoadingInitialData:C,isRefreshing:O,refresh:P}=Ie(N?.companyId,N?.integrationId,N?{page:N.page,limit:N.limit,type:N.type,status:gt}:{}),{deleteTemplate:S}=Ce(r,a),M=e.useMemo(()=>Dt(x,o),[o,x]),D=C||O;e.useEffect(()=>{if(!t){s(null);return}s(d||null)},[t,d]);const w=async()=>{if(v){y(!0);try{await l(v)}finally{y(!1)}}},R=e.useCallback(async g=>{try{await f({title:"Remover modelo",description:`Deseja realmente remover o modelo "${g.name}"? Essa ação remove também na Meta.`,cancellationText:"Cancelar",confirmationText:"Remover"})}catch{return}try{await S(g.id),String(v)===String(g.id)&&s(null),await Promise.allSettled([P(),u?.(g)]),p.success("Modelo removido com sucesso.")}catch(m){p.error(m?.response?.data?.message||"Falha ao remover modelo.")}},[p,f,S,u,P,v]),T=h;return e.createElement(Ne,{open:t,onClose:T?void 0:n,title:`Selecionar modelo: ${E}`,maxWidth:"sm",fullWidth:!0,loading:T,Actions:e.createElement(e.Fragment,null,e.createElement(U,{variant:"outlined",onClick:n,disabled:T},"Cancelar"),e.createElement(U,{variant:"contained",color:"primary",disabled:!v||T,onClick:w},"Vincular"))},D?e.createElement("div",{className:"flex items-center justify-center py-24"},e.createElement(ye,{size:28})):M.length===0?e.createElement("div",{className:"py-24 text-center text-16 text-gray-500"},x.length>0?"Todos os modelos de notificação já estão vinculados a um tipo.":"Nenhum modelo de notificação disponÃvel nesta integração."):e.createElement("div",{className:"space-y-8"},M.map(g=>{const m=String(g.status||"").toUpperCase()==="APPROVED",k=String(v)===String(g.id);return e.createElement("div",{key:g.id,className:A("flex w-full items-center rounded-8 border-2 border-solid transition-colors",k?"border-purple bg-purple-lightest":"border-gray-200 bg-white hover:border-gray-300",!m&&"opacity-80")},e.createElement("button",{type:"button",onClick:()=>m&&s(g.id),disabled:!m,className:A("min-w-0 flex-1 border-0 bg-transparent p-16 text-left",m?"cursor-pointer":"cursor-not-allowed")},e.createElement("div",{className:"truncate text-16 font-semibold text-gray-800"},g.name),g.language&&e.createElement("div",{className:"mt-4 text-16 text-gray-400"},g.language),e.createElement("div",{className:"mt-8"},e.createElement(vt,{status:g.status,label:Et(g)}))),e.createElement("div",{className:"shrink-0 pr-8"},e.createElement(tt,{tooltip:"Excluir modelo",color:"text-red-500",onClick:()=>R(g),"aria-label":`Excluir modelo ${g.name}`},e.createElement(at,{fontSize:"small"}))))})))}function Bt({open:t,onClose:n,notificationType:r,typeKey:a,initialText:o,onSave:l}){const[u,d]=e.useState(o??""),[p,f]=e.useState(null),I=e.useRef(null);e.useEffect(()=>{t&&(d(o??""),f(null))},[t,o]);const E=Lt[a]??[],v=s=>{const h=I.current;if(!h){d(C=>{const O=C+s;return O.length>$?C:O}),f(null);return}const y=h.selectionStart??u.length,N=h.selectionEnd??u.length,x=u.substring(0,y)+s+u.substring(N);if(x.length>$){f(null);return}d(x),f(null),setTimeout(()=>{h.focus();const C=y+s.length;h.setSelectionRange(C,C)},0)};return e.createElement(Ne,{open:t,onClose:n,title:`Edite o modelo de: ${r}`,onSubmit:()=>l(u),maxWidth:"sm",fullWidth:!0},e.createElement("div",{className:"space-y-16"},e.createElement("div",null,E.length>0&&e.createElement(e.Fragment,null,e.createElement(U,{size:"small",color:"primary",variant:"outlined",endIcon:e.createElement(bt,null),onClick:s=>f(s.currentTarget)},"Adicionar variável"),e.createElement(nt,{anchorEl:p,open:!!p,onClose:()=>f(null)},E.map(s=>e.createElement(rt,{key:s.token,onClick:()=>v(s.token)},s.label))))),e.createElement(it,{inputRef:I,variant:"outlined",fullWidth:!0,multiline:!0,minRows:6,value:u,inputProps:{maxLength:$},onChange:s=>d(s.target.value),helperText:e.createElement("span",{className:"flex items-center justify-between"},e.createElement("span",null,u.length,"/",$))})))}function me({children:t}){return e.createElement("div",{className:"flex items-center gap-12 rounded-8 bg-blue-lightest px-16 py-12 text-12 text-blue-dark"},e.createElement(be,{className:"shrink-0 text-16 text-blue-dark"}),e.createElement("span",null,t))}function F({children:t,onClick:n,disabled:r,variant:a="default"}){return e.createElement(U,{type:"button",variant:"outlined",color:a==="purple"?"primary":"default",disableElevation:!0,disableRipple:!0,size:"small",onClick:n,disabled:r,className:"bg-white"},t)}function ue({active:t,onClick:n,icon:r,title:a,subtitle:o}){return e.createElement("button",{type:"button",onClick:n,"aria-selected":t,className:A("flex items-start gap-12 rounded-t-12 border border-b-0 border-solid py-12 text-left transition-all sm:w-auto
7sm:px-16",t?"min-w-0 flex-1 px-16":"w-48 justify-center px-8 sm:justify-start",t?"border-purple-lighter bg-purple-lightest text-purple-dark":"border-transparent bg-white text-gray-500 hover:bg-gray-50")},e.createElement("span",{className:"mt-2 shrink-0"},r),e.createElement("div",{className:A("min-w-0",!t&&"hidden sm:block")},e.createElement("p",{className:A("text-16 font-medium",t?"text-purple-dark":"text-gray-700")},a),e.createElement("p",{className:"mt-4 text-14 text-gray-500"},o)))}function zt({typeKey:t,rule:n,isCustomizable:r=!0,supportsClosedTemplate:a=!0,hasOfficialIntegration:o,associatedTemplate:l,onToggleEnabled:u,onSaveText:d,onSelectTemplate:p,onRemoveTemplate:f,onCreateTemplate:I,onCreateTemplateFromMessage:E,isSavingRule:v,isSavingTemplate:s}){const h=te[t]??t,y=n?.enabled??!1,N=n?.textBody??"",x=Me(t,N),C=Rt(N),O=N||Fe[t]||"",P=a&&o,[S,M]=e.useState("open"),[D,w]=e.useState(!1),[R,T]=e.useState(!1),g=async k=>{try{await d(k),w(!1)}catch{}},m=v||s;return e.createElement("div",{className:"relative overflow-hidden rounded-12 border border-solid border-gray-200 bg-white"},e.createElement(Te,{loading:m}),e.createElement("div",{className:"flex items-center justify-between border-0 border-b border-solid border-gray-200 px-16 py-12"},e.createElement("h3",{className:"m-0 text-16 font-semibold text-gray-800"},h),e.createElement("div",{className:"flex shrink-0 items-center gap-8"},e.createElement("span",{className:A("rounded-full px-8 py-4 text-12 font-semibold",y?"bg-green-lightest text-green-dark":"bg-gray-100 text-gray-500")},y?"Ativo":"Inativo"),e.createElement(ve,{checked:y,color:"primary",onChange:k=>u(k.target.checked),disabled:m,size:"small"}))),y&&e.createElement("div",{className:"mx-16 my-12"},P?e.createElement("div",{className:"flex sm:grid sm:grid-cols-2"},e.createElement(ue,{active:S==="open",onClick:()=>M("open"),icon:e.createElement(xt,{className:"h-24 w-24 shrink-0"}),title:"Mensagem para conversa aberta",subtitle:"Usado quando o cliente conversou com você nas últimas 24 horas."}),e.createElement(ue,{active:S==="closed",onClick:()=>M("closed"),icon:e.createElement(Tt,{className:"h-24 w-24 shrink-0"}),title:"Mensagem para conversa fechada",subtitle:"Necessário quando o cliente não conversou com você nas últimas 24 horas."})):!a&&o?e.createElement("div",{className:"pb-12"},e.createElement(me,null,"Esta notificação só funciona com conversa aberta (janela de 24 horas). Modelos da Meta não se aplicam a este evento.")):null,e.createElement("div",{className:A("rounded-12 p-16",o&&"border border-solid border-gray-200",P&&"rounded-t-none")},(S==="open"||!P)&&e.createElement("div",{className:"space-y-12"},r?e.createElement(e.Fragment,null,e.createElement("div",{className:"rounded-8 border border-solid border-gray-200 bg-white p-12"},e.createElement("div",{className:"line-clamp-4 whitespace-pre-wrap text-14 text-gray-600"},e.createElement(It,{text:x}))),e.createElement("div",{className:"text-12 text-gray-400"},e.createElement(ot,{color:C?"grey":"purple"},C?"Mensagem padrão":"Mensagem personalizada")),e.createElement("div",{className:"flex justify-end gap-8"},e.createElement(F,{onClick:()=>w(!0),disabled:m},"Editar"))):e.createElement("div",{className:"rounded-8 border border-solid border-gray-200 bg-gray-50 p-12 text-14 text-gray-600"},"Essa notificação não permite personalização."),!a&&l&&e.createElement("div",{className:"flex flex-wrap items-center justify-between gap-8 rounded-8 border border-solid border-yellow-lighter bg-yellow-lightest px-12 py-8"},e.createElement("span",{className:"text-12 text-yellow-darker"},"Há um modelo Meta vinculado indevidamente a este evento."),e.createElement(F,{onClick:f,disabled:m},"Desvincular modelo"))),P&&S==="closed"&&e.createElement("div",{className:"space-y-12"},e.createElement(me,null,"Vincular um modelo é opcional e seu envio pode gerar custo junto à Meta."),l?e.createElement(e.Fragment,null,e.createElement(ht,{template:l}),e.createElement("div",{className:"flex flex-wrap items-center justify-end gap-8"},e.createElement(F,{onClick:f,disabled:m},"Excluir"),e.createElement(F,{onClick:p,disabled:m},"Selecionar"),e.createElement(le,{title:o?"":"Configure um número na API Oficial da Meta para vincular modelos",placement:"top"},e.createElement("span",null,e.createElement(F,{onClick:I,disabled:!o||m},"Criar"))),e.createElement(F,{variant:"purple",onClick:()=>T(!0),disabled:m},"Preview da mensagem"))):e.createElement("div",{className:"flex flex-col items-center gap-12 py-16"},e.createElement("p",{className:"m-0 text-center text-12 text-gray-500"},"Nenhum modelo vinculado a este evento"),o&&e.createElement(e.Fragment,null,e.createElement(F,{variant:"purple",onClick:p,disabled:m},"Selecionar modelo"),e.createElement(F,{variant:"purple",onClick:E,disabled:m},"Criar template a partir da mensagem para conversa aberta")),e.createElement(le,{title:o?"":"Configure um número na API Oficial da Meta para vincular modelos",placement:"top"},e.createElement("span",null,e.createElement(F,{onClick:I,disabled:!o||m},"Criar modelo"))))))),r&&D&&e.createElement(Bt,{open:!0,onClose:()=>w(!1),notificationType:h,typeKey:t,initialText:O,onSave:g}),e.createElement(Nt,{open:R,onClose:()=>T(!1),template:l}))}async function Ut({companyId:t}){try{return(await q.get(`${ee}/v1/notifications/settings`,{params:{companyId:t}})).data}catch(n){G(n)}}async function Wt(t,n){try{return(await q.put(`/api/v1/user/companies/${t}`,{company:{whatsapp_notification_provider:n}})).data}catch(r){G(r)}}async function pe({companyId:t,notificationIntegrationId:n}){try{return(await q.put(`${ee}/v1/notifications/settings/integration`,{companyId:`${t}`,notificationIntegrationId:n||null})).data}catch(r){G(r)}}async function fe({templateId:t,companyId:n,notificationType:r}){try{return(await q.put(`${ee}/v1/meta/templates/${t}/notification-type`,{companyId:`${n}`,notificationType:r??null})).data}catch(a){G(a)}}function Yt(t){const n=X.notificationSettings(t),{data:r,error:a,mutate:o,isLoading:l}=xe(n,()=>Ut({companyId:t}),{shouldRetryOnError:!1,revalidateOnFocus:!1});return{settings:r??null,isLoading:!!(n&&l),error:a,refresh:o}}function $t(t){const n=X.orderNotificationSettings(t),{data:r,error:a,mutate:o,isLoading:l}=xe(n,wt,{shouldRetryOnError:!1,revalidateOnFocus:!1});return{settings:r??{},isLoading:!!(n&&l),error:a,refresh:o}}function Vt(t){return t===void 0?void 0:String(t??"").trim()||null}async function ge({currentRailsSettings:t,typeKey:n,enabled:r,textBody:a,refreshRailsCache:o}){const l=Vt(a),u=_t(t,n,{enabled:r,...l!==void 0?{textBody:l}:{}}),d=await we(u);try{await o?.(d,{revalidate:!1})}catch{}return d}function Re(t,{companyId:n,integrationId:r,type:a}){if(!Array.isArray(t)||t[0]!=="whatsapp"||t[1]!=="integration-templates")return!1;const o=t[2];return!(String(o?.companyId)!==String(n)||String(o?.integrationId)!==String(r)||a&&o?.type!==a)}function Ht(t,{templateId:n,notificationType:r}){return t?.data?{...t,data:t.data.map(a=>String(a.id)===String(n)?{...a,notificationType:r??null}:r&&a.notificationType===r?{...a,notificationType:null}:a)}:t}function qt(t,{templateId:n,notificationType:r,integrationId:a}){return t?.integrations?{...t,integrations:t.integrations.map(o=>{if(a&&String(o.id??o.integrationId)!==String(a))return o;const l=o.templates??[];return r?{...o,templates:l.filter(u=>u.notificationType!==r||String(u.id)===String(n))}:{...o,templates:l.filter(u=>String(u.id)!==String(n))}})}:t}function Gt(t,n,{type:r}={}){return!t||!n?Promise.resolve():H(a=>Re(a,{companyId:t,integrationId:n,type:r}),void 0,{revalidate:!0})}function Xt(t){return t?H(X.notificationSettings(t)):Promise.resolve()}async function Le({companyId:t,integrationId:n,templateType:r}){await Promise.all([Xt(t),Gt(t,n,{type:r})])}async function Jt({companyId:t,integrationId:n,templateType:r,templateId:a,notificationType:o}){await Promise.all([H(X.notificationSettings(t),l=>qt(l,{templateId:a,notificationType:o,integrationId:n}),{revalidate:!1}),H(l=>Re(l,{companyId:t,integrationId:n,type:r}),l=>Ht(l,{templateId:a,notificationType:o}),{revalidate:!1})]),await Le({companyId:t,integrationId:n,templateType:r})}function Qt(t,n){return!t||typeof t!="object"?{}:n.reduce((r,a)=>{const o=!!t[_e(a)],l=t[Oe(a)]??null;return{...r,[a]:{enabled:o,textBody:l}}},{})}function Zt(t,n){return!Array.isArray(t)||!n?{}:(t.find(a=>String(a?.id??a?.integrationId)===String(n))?.templates??[]).reduce((a,o)=>{const l=Pe[o.notificationType];return l?{...a,[l]:o}:a},{})}function Kt(t,n){if(!Array.isArray(n)||n.length===0)return t??{};const r=Object.fromEntries(n.map(a=>[String(a.id),a]));return Object.fromEntries(Object.entries(t??{}).map(([a,o])=>[a,r[String(o.id)]?{...o,...r[String(o.id)]}
7:o]))}function ea(){const t=he(),n=st(),r=lt(({globalCompany:i})=>i.company),a=r?.id,{settings:o,isLoading:l,error:u,refresh:d}=Yt(a),{settings:p,isLoading:f,error:I,refresh:E}=$t(a),{primaryIntegration:v,error:s,isLoading:h,refresh:y}=Ct(a),[N,x]=e.useState(null),[C,O]=e.useState(null),[P,S]=e.useState(!1),[M,D]=e.useState(!1),[w,R]=e.useState(null),[T,g]=e.useState(null),m=r?.whatsapp_notification_provider??"UNOFFICIAL_EXTENSION",k=v?.integrationStatus==="CONNECTED",_=o?.notificationIntegrationId||v?.integrationId||null,{createTemplate:ae,isCreating:De}=Ce(a,_),je=["OFFICIAL_META","UNOFFICIAL_EXTENSION"].includes(m),j=e.useMemo(()=>Qt(p,Z),[p]),J=e.useMemo(()=>Zt(o?.integrations,_),[o?.integrations,_]),ne=Object.keys(J).length>0,Be=e.useMemo(()=>({type:B.NOTIFICATION,limit:50,page:1}),[]),{templates:re}=Ie(ne?a:null,ne?_:null,Be),W=e.useMemo(()=>Kt(J,re),[J,re]),ze=e.useMemo(()=>de(p?.notify_via_whatsapp_portal_order_types),[p]),ie=e.useCallback(async i=>{a&&(await pe({companyId:a,notificationIntegrationId:i}),await d())},[a,d]);e.useEffect(()=>{m!=="OFFICIAL_META"||!k||!v?.integrationId||!a||o?.notificationIntegrationId===v.integrationId||ie(v.integrationId).catch(()=>{})},[a,o?.notificationIntegrationId,k,m,v?.integrationId,ie]);const L=e.useCallback(async({templateId:i,notificationType:c}={})=>{if(i){await Jt({companyId:a,integrationId:_,templateType:B.NOTIFICATION,templateId:i,notificationType:c});return}await Le({companyId:a,integrationId:_,templateType:B.NOTIFICATION})},[a,_]),Y=e.useCallback(async(i,c=null)=>{await pe({companyId:a,notificationIntegrationId:c}),await Wt(a,i),await n(ct()),await d()},[a,n,d]),Ue=e.useCallback(async i=>{if(!a)return;S(!0);const c=i?"UNOFFICIAL_EXTENSION":"DISABLED";try{await Y(c,null),await E(),t.success(i?"Notificações ativadas.":"Notificações desativadas.")}catch(b){t.error(b?.response?.data?.message||b?.message||"Falha ao atualizar configuração.")}finally{S(!1)}},[t,a,E,Y]),We=e.useCallback(async i=>{if(!(!a||i===m)){S(!0);try{await Y(i,i==="OFFICIAL_META"?_:null),await E(),t.success("Canal de envio atualizado.")}catch(c){t.error(c?.response?.data?.message||c?.message||"Falha ao atualizar o canal de envio.")}finally{S(!1)}}},[t,a,m,E,_,Y]),Ye=e.useCallback(async i=>{if(!(!a||f)){D(!0);try{const c=await At(p,{notify_via_whatsapp_portal_order_types:de(i)});await E(c,{revalidate:!1}),t.success("Tipos de pedido atualizados.")}catch(c){t.error(c?.response?.data?.message||"Falha ao atualizar tipos de pedido.")}finally{D(!1)}}},[t,a,f,p,E]),$e=e.useCallback(async(i,c)=>{if(!(!a||f)){x(i);try{await ge({typeKey:i,currentRailsSettings:p,enabled:c,textBody:j[i]?.textBody??"",refreshRailsCache:E}),t.success(c?"Notificação ativada.":"Notificação desativada.")}catch(b){t.error(b?.response?.data?.message||b?.message||"Falha ao atualizar notificação.")}finally{x(null)}}},[t,a,f,p,E,j]),Ve=e.useCallback(async(i,c)=>{if(!(!a||f||!K(i))){x(i);try{await ge({typeKey:i,currentRailsSettings:p,enabled:j[i]?.enabled??!0,textBody:c,refreshRailsCache:E}),t.success("Mensagem salva com sucesso.")}catch(b){throw t.error(b?.response?.data?.message||b?.message||"Falha ao salvar mensagem."),b}finally{x(null)}}},[t,a,f,p,E,j]),He=e.useCallback(i=>{z(i)&&R({typeKey:i})},[]),qe=e.useCallback(async i=>{if(!w||!a)return;const{typeKey:c}=w;if(z(c)){O(c),R(null);try{await fe({templateId:i,companyId:a,notificationType:V[c]}),await L({templateId:i,notificationType:V[c]}),t.success("Modelo vinculado com sucesso.")}catch(b){t.error(b?.response?.data?.message||"Falha ao vincular modelo.")}finally{O(null)}}},[t,a,w,L]),Ge=e.useCallback(async i=>{const c=W[i];if(!(!c||!a)){O(i);try{await fe({templateId:c.id,companyId:a,notificationType:null}),await L({templateId:c.id,notificationType:null}),t.success("Modelo desvinculado.")}catch(b){t.error(b?.response?.data?.message||"Falha ao desvincular modelo.")}finally{O(null)}}},[t,a,L,W]),oe=e.useCallback((i,c)=>{t.error(i?.response?.data?.message||pt(i?.response?.data?.errorCode))},[t]),Xe=e.useCallback(i=>{t.error(i||"Falha ao processar a imagem.")},[t]),se=e.useCallback((i,{initialBodyText:c}={})=>{z(i)&&g({typeKey:i,initialBodyText:c})},[]),Je=e.useCallback(async i=>{if(!T||!a||!_)return;const{typeKey:c}=T;if(z(c))try{await ae({...i,type:B.NOTIFICATION}),g(null),await L(),t.success("Modelo enviado para aprovação. Após ser aprovado, vincule-o ao tipo de notificação.")}catch(b){oe(b,"Falha ao criar modelo.")}},[t,a,ae,T,oe,L,_]);if(!a)return e.createElement("div",{className:"flex h-full items-center justify-center"},e.createElement(ce,{title:"Não foi possÃvel identificar o estabelecimento atual"}));const Qe=s&&!St(s);if(u||I||Qe)return e.createElement("div",{className:"flex h-full flex-col items-center justify-center space-y-16 p-20"},e.createElement(ce,{title:"Problema ao carregar as configurações de notificação"}),e.createElement(U,{variant:"outlined",onClick:()=>{d(),E(),y()}},"Tentar novamente"));if(l||f||h)return e.createElement("div",{className:"flex h-full items-center justify-center"},e.createElement(ye,{size:32}));if(T){const{typeKey:i,initialBodyText:c}=T,b=te[i]??i;return e.createElement("div",{className:"flex min-h-0 flex-1 flex-col px-16 py-16 sm:px-24"},e.createElement("div",{className:"min-h-0 flex-1 overflow-auto"},e.createElement(yt,{templateType:B.NOTIFICATION,title:`Novo Modelo de ${b}`,initialBodyText:c,onClose:()=>g(null),onSubmit:Je,loading:De,onUploadError:Xe})))}return e.createElement("div",{className:"flex min-h-0 flex-1 flex-col space-y-24 px-16 py-16 sm:px-24"},e.createElement("div",{className:"shrink-0"},e.createElement("div",{className:"flex items-center gap-8"},e.createElement("div",{className:"text-20 font-semibold text-gray-800"},"Notificações de pedido"),e.createElement(dt,{size:"small",className:"text-purple","aria-label":"Saiba mais sobre notificações"},e.createElement(ut,{fontSize:"small"}))),e.createElement("div",{className:"mt-4 text-16 text-gray-500"},"Configure as mensagens automáticas enviadas aos clientes em c
7ada etapa do pedido.")),e.createElement(Pt,{isActive:je,notificationProvider:m,onToggleActive:Ue,onChangeProvider:We,portalOrderTypes:ze,onChangePortalOrderTypes:Ye,hasOfficialIntegration:k,isSaving:P,isSavingOrderTypes:M}),e.createElement("div",{className:"space-y-12"},Z.map(i=>{const c=j[i]??null,b=W[i]??null;return e.createElement(zt,{key:i,typeKey:i,rule:c,isCustomizable:K(i),supportsClosedTemplate:z(i),hasOfficialIntegration:k,associatedTemplate:b,onToggleEnabled:Q=>$e(i,Q),onSaveText:Q=>Ve(i,Q),onSelectTemplate:()=>He(i),onRemoveTemplate:()=>Ge(i),onCreateTemplate:()=>se(i),onCreateTemplateFromMessage:()=>se(i,{initialBodyText:Me(i,j[i]?.textBody)}),isSavingRule:N===i,isSavingTemplate:C===i})})),w&&e.createElement(jt,{open:!0,onClose:()=>R(null),companyId:a,integrationId:_,notificationType:V[w.typeKey],selectedTemplateId:W[w.typeKey]?.id??null,onPick:qe,onTemplateDeleted:()=>L()}))}function ga(){return e.createElement(mt,null,e.createElement("div",{className:"flex h-full min-h-0 flex-col overflow-auto"},e.createElement(ea,null)))}export{ga as default}; 8 9//# debugId=12b1bcd8-c41e-5423-a1cd-1b8624aaf2d3
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.