Files
cirux/.next/server/app/api/v1/evolution-webhook/route.js
T
2026-06-03 15:08:40 -05:00

1 line
10 KiB
JavaScript

(()=>{var a={};a.id=891,a.ids=[891],a.modules={261:a=>{"use strict";a.exports=require("next/dist/shared/lib/router/utils/app-paths")},3295:a=>{"use strict";a.exports=require("next/dist/server/app-render/after-task-async-storage.external.js")},10846:a=>{"use strict";a.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},19121:a=>{"use strict";a.exports=require("next/dist/server/app-render/action-async-storage.external.js")},29294:a=>{"use strict";a.exports=require("next/dist/server/app-render/work-async-storage.external.js")},44870:a=>{"use strict";a.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},63033:a=>{"use strict";a.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},71517:(a,b,c)=>{"use strict";c.r(b),c.d(b,{handler:()=>G,patchFetch:()=>F,routeModule:()=>B,serverHooks:()=>E,workAsyncStorage:()=>C,workUnitAsyncStorage:()=>D});var d={};c.r(d),c.d(d,{POST:()=>A});var e=c(95736),f=c(9117),g=c(4044),h=c(39326),i=c(32324),j=c(261),k=c(54290),l=c(85328),m=c(38928),n=c(46595),o=c(3421),p=c(17679),q=c(41681),r=c(63446),s=c(86439),t=c(51356),u=c(10641),v=c(34885),w=c(91010);let x=require("crypto"),y=process.env.EVOLUTION_API_KEY,z=v.Ik({event:v.eu("messages.upsert"),instance:v.Yj().optional(),data:v.Ik({key:v.Ik({remoteJid:v.Yj(),fromMe:v.zM(),id:v.Yj().optional()}),message:v.Ik({conversation:v.Yj().optional(),extendedTextMessage:v.Ik({text:v.Yj()}).optional()}),messageType:v.Yj().optional(),pushName:v.Yj().optional()}).optional()});async function A(a){if(!y)return u.NextResponse.json({error:"Webhook not configured"},{status:500});let b=a.headers.get("apikey")??a.headers.get("x-api-key")??"";if(!(b.length===y.length&&(0,x.timingSafeEqual)(Buffer.from(b),Buffer.from(y))))return u.NextResponse.json({error:"Unauthorized"},{status:401});let c=(0,w.Z)();try{let b,d,e=await a.json(),f=z.safeParse(e);if(!f.success)return u.NextResponse.json({status:"ignored",reason:"invalid payload format"});let{data:g}=f,h=g.data?.key,i=g.data?.message;if(!h||!i)return u.NextResponse.json({status:"ignored",reason:"no key or message"});if(h.fromMe)return u.NextResponse.json({status:"ignored",reason:"fromMe"});if(h.remoteJid.includes("@g.us"))return u.NextResponse.json({status:"ignored",reason:"group message"});let j=i.conversation??i.extendedTextMessage?.text??"";if(!j)return u.NextResponse.json({status:"ignored",reason:"no text content"});let k=h.remoteJid.replace(/@.*$/,""),{data:l}=await c.from("patients").select("id, name").eq("phone",k).maybeSingle();if(l)b=l.id,l.name;else{let{data:a,error:d}=await c.from("patients").insert({phone:k,name:g.data?.pushName?.trim().slice(0,120)||`Paciente ${k}`,status:"prospecto"}).select("id, name").single();if(d||!a)return console.error("Error creating patient:",d?.message??"unknown"),u.NextResponse.json({error:"failed to create patient"},{status:500});b=a.id,a.name}let{data:m}=await c.from("conversations").select("id").eq("patient_id",b).eq("channel","whatsapp").maybeSingle();if(m)d=m.id;else{let{data:a,error:e}=await c.from("conversations").insert({patient_id:b,channel:"whatsapp",status:"pending_human",last_message_at:new Date().toISOString()}).select("id").single();if(e||!a)return console.error("Error creating conversation:",e),u.NextResponse.json({error:"failed to create conversation"},{status:500});d=a.id}let{error:n}=await c.from("messages").insert({patient_id:b,conversation_id:d,channel:"whatsapp",direction:"in",type:"text",content:j.trim().slice(0,4e3),transcript:j.trim().slice(0,4e3)});if(n)return console.error("Error inserting message:",n?.message??"unknown"),u.NextResponse.json({error:"failed to save message"},{status:500});return await c.from("conversations").update({last_message_at:new Date().toISOString(),status:"pending_human"}).eq("id",d),console.log("[Evolution Webhook] Message saved"),u.NextResponse.json({status:"ok"})}catch(a){return console.error("Evolution webhook error:",a.message),u.NextResponse.json({error:"internal error"},{status:500})}}let B=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/v1/evolution-webhook/route",pathname:"/api/v1/evolution-webhook",filename:"route",bundlePath:"app/api/v1/evolution-webhook/route"},distDir:".next",relativeProjectDir:"",resolvedPagePath:"/home/silvio/Develop/APP-ESTETICA/cirux/src/app/api/v1/evolution-webhook/route.ts",nextConfigOutput:"standalone",userland:d}),{workAsyncStorage:C,workUnitAsyncStorage:D,serverHooks:E}=B;function F(){return(0,g.patchFetch)({workAsyncStorage:C,workUnitAsyncStorage:D})}async function G(a,b,c){var d;let e="/api/v1/evolution-webhook/route";"/index"===e&&(e="/");let g=await B.prepare(a,b,{srcPage:e,multiZoneDraftMode:!1});if(!g)return b.statusCode=400,b.end("Bad Request"),null==c.waitUntil||c.waitUntil.call(c,Promise.resolve()),null;let{buildId:u,params:v,nextConfig:w,isDraftMode:x,prerenderManifest:y,routerServerContext:z,isOnDemandRevalidate:A,revalidateOnlyGenerated:C,resolvedPathname:D}=g,E=(0,j.normalizeAppPath)(e),F=!!(y.dynamicRoutes[E]||y.routes[D]);if(F&&!x){let a=!!y.routes[D],b=y.dynamicRoutes[E];if(b&&!1===b.fallback&&!a)throw new s.NoFallbackError}let G=null;!F||B.isDev||x||(G="/index"===(G=D)?"/":G);let H=!0===B.isDev||!F,I=F&&!H,J=a.method||"GET",K=(0,i.getTracer)(),L=K.getActiveScopeSpan(),M={params:v,prerenderManifest:y,renderOpts:{experimental:{cacheComponents:!!w.experimental.cacheComponents,authInterrupts:!!w.experimental.authInterrupts},supportsDynamicResponse:H,incrementalCache:(0,h.getRequestMeta)(a,"incrementalCache"),cacheLifeProfiles:null==(d=w.experimental)?void 0:d.cacheLife,isRevalidate:I,waitUntil:c.waitUntil,onClose:a=>{b.on("close",a)},onAfterTaskError:void 0,onInstrumentationRequestError:(b,c,d)=>B.onRequestError(a,b,d,z)},sharedContext:{buildId:u}},N=new k.NodeNextRequest(a),O=new k.NodeNextResponse(b),P=l.NextRequestAdapter.fromNodeNextRequest(N,(0,l.signalFromNodeResponse)(b));try{let d=async c=>B.handle(P,M).finally(()=>{if(!c)return;c.setAttributes({"http.status_code":b.statusCode,"next.rsc":!1});let d=K.getRootSpanAttributes();if(!d)return;if(d.get("next.span_type")!==m.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${d.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let e=d.get("next.route");if(e){let a=`${J} ${e}`;c.setAttributes({"next.route":e,"http.route":e,"next.span_name":a}),c.updateName(a)}else c.updateName(`${J} ${a.url}`)}),g=async g=>{var i,j;let k=async({previousCacheEntry:f})=>{try{if(!(0,h.getRequestMeta)(a,"minimalMode")&&A&&C&&!f)return b.statusCode=404,b.setHeader("x-nextjs-cache","REVALIDATED"),b.end("This page could not be found"),null;let e=await d(g);a.fetchMetrics=M.renderOpts.fetchMetrics;let i=M.renderOpts.pendingWaitUntil;i&&c.waitUntil&&(c.waitUntil(i),i=void 0);let j=M.renderOpts.collectedTags;if(!F)return await (0,o.I)(N,O,e,M.renderOpts.pendingWaitUntil),null;{let a=await e.blob(),b=(0,p.toNodeOutgoingHttpHeaders)(e.headers);j&&(b[r.NEXT_CACHE_TAGS_HEADER]=j),!b["content-type"]&&a.type&&(b["content-type"]=a.type);let c=void 0!==M.renderOpts.collectedRevalidate&&!(M.renderOpts.collectedRevalidate>=r.INFINITE_CACHE)&&M.renderOpts.collectedRevalidate,d=void 0===M.renderOpts.collectedExpire||M.renderOpts.collectedExpire>=r.INFINITE_CACHE?void 0:M.renderOpts.collectedExpire;return{value:{kind:t.CachedRouteKind.APP_ROUTE,status:e.status,body:Buffer.from(await a.arrayBuffer()),headers:b},cacheControl:{revalidate:c,expire:d}}}}catch(b){throw(null==f?void 0:f.isStale)&&await B.onRequestError(a,b,{routerKind:"App Router",routePath:e,routeType:"route",revalidateReason:(0,n.c)({isRevalidate:I,isOnDemandRevalidate:A})},z),b}},l=await B.handleResponse({req:a,nextConfig:w,cacheKey:G,routeKind:f.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:y,isRoutePPREnabled:!1,isOnDemandRevalidate:A,revalidateOnlyGenerated:C,responseGenerator:k,waitUntil:c.waitUntil});if(!F)return null;if((null==l||null==(i=l.value)?void 0:i.kind)!==t.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==l||null==(j=l.value)?void 0:j.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});(0,h.getRequestMeta)(a,"minimalMode")||b.setHeader("x-nextjs-cache",A?"REVALIDATED":l.isMiss?"MISS":l.isStale?"STALE":"HIT"),x&&b.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let m=(0,p.fromNodeOutgoingHttpHeaders)(l.value.headers);return(0,h.getRequestMeta)(a,"minimalMode")&&F||m.delete(r.NEXT_CACHE_TAGS_HEADER),!l.cacheControl||b.getHeader("Cache-Control")||m.get("Cache-Control")||m.set("Cache-Control",(0,q.getCacheControlHeader)(l.cacheControl)),await (0,o.I)(N,O,new Response(l.value.body,{headers:m,status:l.value.status||200})),null};L?await g(L):await K.withPropagatedContext(a.headers,()=>K.trace(m.BaseServerSpan.handleRequest,{spanName:`${J} ${a.url}`,kind:i.SpanKind.SERVER,attributes:{"http.method":J,"http.target":a.url}},g))}catch(b){if(b instanceof s.NoFallbackError||await B.onRequestError(a,b,{routerKind:"App Router",routePath:E,routeType:"route",revalidateReason:(0,n.c)({isRevalidate:I,isOnDemandRevalidate:A})}),F)throw b;return await (0,o.I)(N,O,new Response(null,{status:500})),null}}},78335:()=>{},86439:a=>{"use strict";a.exports=require("next/dist/shared/lib/no-fallback-error.external")},91010:(a,b,c)=>{"use strict";c.d(b,{U:()=>f,Z:()=>g});var d=c(67596),e=c(86802);async function f(){let a=await (0,e.UL)();return(0,d.createServerClient)("https://supabase.silvioalzate.shop","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYW5vbiIsImlzcyI6InN1cGFiYXNlIiwiaWF0IjoxNzc5MTYzNDQ1LCJleHAiOjE5MzY4NDM0NDV9.RGVwyQdA7oigXmMylP2Df7DKpNno_8_rSTwd0471zLk",{cookies:{getAll:()=>a.getAll(),setAll(b){try{b.forEach(({name:b,value:c,options:d})=>a.set(b,c,d))}catch{}}}})}function g(){let a=process.env.SUPABASE_SERVICE_ROLE_KEY;if(!a)throw Error("SUPABASE_SERVICE_ROLE_KEY environment variable is not set.");return(0,d.createServerClient)("https://supabase.silvioalzate.shop",a,{cookies:{getAll:()=>[],setAll(){}}})}},96487:()=>{}};var b=require("../../../../webpack-runtime.js");b.C(a);var c=b.X(0,[331,21,692,647],()=>b(b.s=71517));module.exports=c})();