"use strict";(()=>{var a={};a.id=74279,a.ids=[74279],a.modules={51455:a=>{a.exports=require("node:fs/promises")},102631:(a,b,c)=>{c.r(b),c.d(b,{handler:()=>E,patchFetch:()=>D,routeModule:()=>z,serverHooks:()=>C,workAsyncStorage:()=>A,workUnitAsyncStorage:()=>B});var d={};c.r(d),c.d(d,{GET:()=>y,dynamic:()=>w,runtime:()=>x});var e=c(940527),f=c(41752),g=c(633335),h=c(573615),i=c(301769),j=c(200261),k=c(405563),l=c(439285),m=c(443399),n=c(295860),o=c(161730),p=c(728392),q=c(976618),r=c(406527),s=c(986439),t=c(975973),u=c(612839),v=c(567472);let w="force-dynamic",x="nodejs";async function y(a){let b=new URL(a.url),c=b.searchParams.get("q")?.trim().toLowerCase()??"",d=b.searchParams.get("from")?.trim()||null,e=b.searchParams.get("to")?.trim()||null,f=function(a,b,c){let d=a?parseInt(a,10):NaN;return!Number.isFinite(d)||d<=0?100:Math.min(d,500)}(b.searchParams.get("limit"),100,500),g=Math.max(0,parseInt(b.searchParams.get("offset")??"0",10)||0),h=await (0,v.y3)(),i=(0,v.gt)({objectId:u.zq.calendar_event,fieldMap:h.calendar_event,aliasedFields:[{name:"Title",alias:"title"},{name:"Start At",alias:"start_at"},{name:"End At",alias:"end_at"},{name:"Organizer",alias:"organizer"},{name:"Meeting Type",alias:"meeting_type"},{name:"Google Event ID",alias:"google_event_id"},{name:"Attendees",alias:"attendees_json"}]}),j="1=1";if(c){let a=c.replace(/'/g,"''");j+=` AND LOWER(COALESCE(title, '')) LIKE '%${a}%'`}if(d){let a=d.replace(/'/g,"''");j+=` AND start_at >= '${a}'`}if(e){let a=e.replace(/'/g,"''");j+=` AND start_at <= '${a}'`}let k=`
    WITH base AS (${i})
    SELECT * FROM base
    WHERE ${j}
    ORDER BY start_at DESC NULLS LAST
    LIMIT ${f} OFFSET ${g};
  `,l=`WITH base AS (${i}) SELECT COUNT(*) AS total FROM base WHERE ${j};`,[m,n]=await Promise.all([(0,v.Ez)(k),(0,v.Ez)(l)]),o=n[0]?.total?Number(n[0].total):0,p=new Set,q=m.map(a=>{let b=function(a){if(!a)return[];let b=a.trim();if(!b)return[];if(b.startsWith("["))try{let a=JSON.parse(b);if(Array.isArray(a))return a.map(String).filter(Boolean)}catch{}return[b]}(a.attendees_json);for(let a of b)p.add(a);return{row:a,attendeeIds:b}}),r=h.people["Full Name"],s=h.people["Email Address"],t=h.people["Avatar URL"],w=new Map;if(p.size>0&&(r||s)){let a=Array.from(p).map(a=>`'${a.replace(/'/g,"''")}'`).join(", "),b=`
      SELECT
        e.id AS person_id,
        ${r?`MAX(CASE WHEN ef.field_id = '${r}' THEN ef.value END)`:"NULL"} AS name,
        ${s?`MAX(CASE WHEN ef.field_id = '${s}' THEN ef.value END)`:"NULL"} AS email,
        ${t?`MAX(CASE WHEN ef.field_id = '${t}' THEN ef.value END)`:"NULL"} AS avatar_url
      FROM entries e
      LEFT JOIN entry_fields ef ON ef.entry_id = e.id
      WHERE e.object_id = '${u.zq.people}'
        AND e.id IN (${a})
      GROUP BY e.id;
    `;for(let a of(await (0,v.Ez)(b)))w.set(a.person_id,{id:a.person_id,name:a.name,email:a.email,avatar_url:a.avatar_url})}let x=q.map(({row:a,attendeeIds:b})=>({id:String(a.entry_id),title:a.title,start_at:a.start_at,end_at:a.end_at,organizer:a.organizer,meeting_type:a.meeting_type,google_event_id:a.google_event_id,attendees:b.map(a=>w.get(a)).filter(a=>!!a)}));return Response.json({events:x,total:o,limit:f,offset:g})}let z=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/crm/calendar/route",pathname:"/api/crm/calendar",filename:"route",bundlePath:"app/api/crm/calendar/route"},distDir:".next",relativeProjectDir:"",resolvedPagePath:"/home/runner/work/DenchClaw/DenchClaw/apps/web/app/api/crm/calendar/route.ts",nextConfigOutput:"standalone",userland:d}),{workAsyncStorage:A,workUnitAsyncStorage:B,serverHooks:C}=z;function D(){return(0,g.patchFetch)({workAsyncStorage:A,workUnitAsyncStorage:B})}async function E(a,b,c){var d;let e="/api/crm/calendar/route";"/index"===e&&(e="/");let g=await z.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:A,isOnDemandRevalidate:B,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||z.isDev||x||(G="/index"===(G=D)?"/":G);let H=!0===z.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)=>z.onRequestError(a,b,d,A)},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=>z.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")&&B&&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 z.onRequestError(a,b,{routerKind:"App Router",routePath:e,routeType:"route",revalidateReason:(0,n.c)({isRevalidate:I,isOnDemandRevalidate:B})},A),b}},l=await z.handleResponse({req:a,nextConfig:w,cacheKey:G,routeKind:f.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:y,isRoutePPREnabled:!1,isOnDemandRevalidate:B,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",B?"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 z.onRequestError(a,b,{routerKind:"App Router",routePath:E,routeType:"route",revalidateReason:(0,n.c)({isRevalidate:I,isOnDemandRevalidate:B})}),F)throw b;return await (0,o.I)(N,O,new Response(null,{status:500})),null}}},161730:(a,b,c)=>{Object.defineProperty(b,"I",{enumerable:!0,get:function(){return g}});let d=c(554226),e=c(884327),f=c(728392);async function g(a,b,c,g){if((0,d.isNodeNextResponse)(b)){var h;b.statusCode=c.status,b.statusMessage=c.statusText;let d=["set-cookie","www-authenticate","proxy-authenticate","vary"];null==(h=c.headers)||h.forEach((a,c)=>{if("x-middleware-set-cookie"!==c.toLowerCase())if("set-cookie"===c.toLowerCase())for(let d of(0,f.splitCookiesString)(a))b.appendHeader(c,d);else{let e=void 0!==b.getHeader(c);(d.includes(c.toLowerCase())||!e)&&b.appendHeader(c,a)}});let{originalResponse:i}=b;c.body&&"HEAD"!==a.method?await (0,e.pipeToNodeResponse)(c.body,i,g):i.end()}}},176760:a=>{a.exports=require("node:path")},200261:a=>{a.exports=require("next/dist/shared/lib/router/utils/app-paths")},257975:a=>{a.exports=require("node:util")},529294:a=>{a.exports=require("next/dist/server/app-render/work-async-storage.external.js")},567472:(a,b,c)=>{c.d(b,{Ez:()=>l,Qw:()=>h,Ut:()=>m,cH:()=>n,fW:()=>k,gt:()=>j,x6:()=>i,y3:()=>g});var d=c(693349),e=c(612839);let f=null;async function g(a=!1){if(f&&!a)return f;let b=await (0,e.W3)(e.zq.people),c=await (0,e.W3)(e.zq.company),d=await (0,e.W3)(e.zq.email_thread),h=await (0,e.W3)(e.zq.email_message);return f={people:b,company:c,email_thread:d,email_message:h,calendar_event:await (0,e.W3)(e.zq.calendar_event),interaction:await (0,e.W3)(e.zq.interaction)}}function h(a){return`'${a.replace(/'/g,"''")}'`}function i(a,b){let c=b.replace(/'/g,"''").replace(/"/g,'""');return`${a} LIKE '%"${c}"%'`}function j(a){let b=a.objectId.replace(/'/g,"''"),c=a.aliasedFields.map(({name:b,alias:c})=>{let d=a.fieldMap[b];if(!d)return`NULL AS "${c}"`;let e=d.replace(/'/g,"''");return`MAX(CASE WHEN ef.field_id = '${e}' THEN ef.value END) AS "${c}"`}).join(",\n      "),d=a.whereSql?`AND ${a.whereSql}`:"",e=a.orderBySql?`ORDER BY ${a.orderBySql}`:"",f=void 0!==a.limit?`LIMIT ${Math.max(0,Math.floor(a.limit))}`:"";return`
    SELECT
      e.id AS entry_id,
      e.created_at,
      e.updated_at,
      ${c}
    FROM entries e
    LEFT JOIN entry_fields ef ON ef.entry_id = e.id
    WHERE e.object_id = '${b}'
      ${d}
    GROUP BY e.id, e.created_at, e.updated_at
    ${e}
    ${f}
  `}function k(a,b,c){let d=void 0!==c?`LIMIT ${Math.max(0,Math.floor(c))}`:"";return`
    SELECT * FROM (${a}) sub
    ${b?`ORDER BY ${b}`:""}
    ${d}
  `}async function l(a,b=[]){try{return await (0,d.AI)(a)}catch{return b}}function m(a){let b=a.emailMessageFieldMap,c=b.Thread,d=b["Sent At"];if(!c||!d)return null;let f=b["Sender Type"],g=b["Body Preview"],h=b.From,i=[c,d];f&&i.push(f),g&&i.push(g),h&&i.push(h);let j=i.map(a=>`'${a.replace(/'/g,"''")}'`).join(", "),k=a.candidateThreadIdsCte?`WHERE m.thread_value IN (SELECT entry_id FROM ${a.candidateThreadIdsCte})`:"WHERE m.thread_value IS NOT NULL";return{cte:`
    latest_msg AS (
      SELECT
        thread_value AS thread_id,
        ${f?"ARG_MAX(sender_type_value, sent_at_value)":"NULL"} AS sender_type,
        ${g?"ARG_MAX(preview_value, sent_at_value)":"NULL"} AS snippet,
        ${h?"ARG_MAX(from_value, sent_at_value)":"NULL"} AS from_person_id
      FROM (
        SELECT
          e.id AS msg_id,
          MAX(CASE WHEN ef.field_id = '${c}' THEN ef.value END) AS thread_value,
          MAX(CASE WHEN ef.field_id = '${d}' THEN ef.value END) AS sent_at_value,
          ${f?`MAX(CASE WHEN ef.field_id = '${f}' THEN ef.value END)`:"NULL"} AS sender_type_value,
          ${g?`MAX(CASE WHEN ef.field_id = '${g}' THEN ef.value END)`:"NULL"} AS preview_value,
          ${h?`MAX(CASE WHEN ef.field_id = '${h}' THEN ef.value END)`:"NULL"} AS from_value
        FROM entries e
        JOIN entry_fields ef
          ON ef.entry_id = e.id
         AND ef.field_id IN (${j})
        WHERE e.object_id = '${e.zq.email_message}'
        GROUP BY e.id
      ) m
      ${k}
      GROUP BY thread_value
    )
  `,joinClause:"LEFT JOIN latest_msg ON latest_msg.thread_id = base.entry_id"}}async function n(a,b){let c=new Map;if(0===a.length)return c;let d=b["Full Name"],f=b["Email Address"],g=b["Avatar URL"];if(!d&&!f)return c;let h=a.map(a=>`'${a.replace(/'/g,"''")}'`).join(", "),i=`
    SELECT
      e.id AS person_id,
      ${d?`MAX(CASE WHEN ef.field_id = '${d}' THEN ef.value END)`:"NULL"} AS name,
      ${f?`MAX(CASE WHEN ef.field_id = '${f}' THEN ef.value END)`:"NULL"} AS email,
      ${g?`MAX(CASE WHEN ef.field_id = '${g}' THEN ef.value END)`:"NULL"} AS avatar_url
    FROM entries e
    LEFT JOIN entry_fields ef ON ef.entry_id = e.id
    WHERE e.object_id = '${e.zq.people}'
      AND e.id IN (${h})
    GROUP BY e.id;
  `;for(let a of(await l(i)))c.set(a.person_id,{id:a.person_id,name:a.name,email:a.email,avatar_url:a.avatar_url});return c}},663033:a=>{a.exports=require("next/dist/server/app-render/work-unit-async-storage.external.js")},710846:a=>{a.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},719771:a=>{a.exports=require("process")},731421:a=>{a.exports=require("node:child_process")},744870:a=>{a.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},848161:a=>{a.exports=require("node:os")},940527:(a,b,c)=>{a.exports=c(744870)},973024:a=>{a.exports=require("node:fs")},979428:a=>{a.exports=require("buffer")},986439:a=>{a.exports=require("next/dist/shared/lib/no-fallback-error.external")}};var b=require("../../../../webpack-runtime.js");b.C(a);var c=b.X(0,[76973,22137,93349,66131],()=>b(b.s=102631));module.exports=c})();