"use strict";(()=>{var a={};a.id=42586,a.ids=[42586],a.modules={51455:a=>{a.exports=require("node:fs/promises")},176760:a=>{a.exports=require("node:path")},200261:a=>{a.exports=require("next/dist/shared/lib/router/utils/app-paths")},237368:(a,b,c)=>{c.d(b,{WU:()=>e});let d=[{min:500,label:"Inner circle",color:"#6366f1",rank:4},{min:100,label:"Strong",color:"#22c55e",rank:3},{min:20,label:"Active",color:"#3b82f6",rank:2},{min:1,label:"Weak",color:"#f59e0b",rank:1},{min:0,label:"Cold",color:"#94a3b8",rank:0}];function e(a){let b="string"==typeof a?Number(a):a??0;if(!Number.isFinite(b)||b<0){let a=d[d.length-1];return{label:a.label,color:a.color,rank:a.rank}}for(let a of d)if(b>=a.min)return{label:a.label,color:a.color,rank:a.rank};let c=d[d.length-1];return{label:c.label,color:c.color,rank:c.rank}}},257975:a=>{a.exports=require("node:util")},354826:(a,b,c)=>{c.d(b,{A:()=>f,J:()=>e});var d=c(748866);function e(a,b){if(!a||"string"!=typeof a)return null;let c=a.trim();if(!c)return null;if(c.includes("@")||c.includes("<")){let a=(0,d.OE)(c);if(!a)return null;let e=(0,d.EQ)(a.address,b);return e?g(e):null}let e=c.toLowerCase().replace(/^https?:\/\//,"").replace(/^www\./,"").replace(/\/.*$/,"");if(!e||e.includes(" ")||!e.includes("."))return null;let f=(0,d.EQ)(`x@${e}`,b);return f?g(f):null}function f(a,b){let c=e(a,b);return c?c.replace(/^https?:\/\//,"").replace(/\/$/,""):null}function g(a){return`https://${a.toLowerCase()}`}},529294:a=>{a.exports=require("next/dist/server/app-render/work-async-storage.external.js")},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")},735441:(a,b,c)=>{c.r(b),c.d(b,{handler:()=>J,patchFetch:()=>I,routeModule:()=>E,serverHooks:()=>H,workAsyncStorage:()=>F,workUnitAsyncStorage:()=>G});var d={};c.r(d),c.d(d,{GET:()=>B,dynamic:()=>z,runtime:()=>A});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),w=c(748866),x=c(354826),y=c(237368);let z="force-dynamic",A="nodejs";async function B(a,b){let{id:c}=await b.params,d=c?.trim();if(!d)return Response.json({error:"Missing person id."},{status:400});let e=await (0,v.y3)(),f=(0,v.gt)({objectId:u.zq.people,fieldMap:e.people,aliasedFields:[{name:"Full Name",alias:"name"},{name:"Email Address",alias:"email"},{name:"Phone Number",alias:"phone"},{name:"Company",alias:"company_id"},{name:"Status",alias:"status"},{name:"Source",alias:"source"},{name:"Strength Score",alias:"strength_score"},{name:"Last Interaction At",alias:"last_interaction_at"},{name:"Job Title",alias:"job_title"},{name:"LinkedIn URL",alias:"linkedin_url"},{name:"Avatar URL",alias:"avatar_url"},{name:"Notes",alias:"notes"}],whereSql:`e.id = ${(0,v.Qw)(d)}`}),g=await (0,v.Ez)(f);if(0===g.length)return Response.json({error:"Person not found."},{status:404});let h=g[0],i=h.strength_score?Number(h.strength_score):0,j=(0,y.WU)(i),k=null,l=h.company_id?.trim()||null;if(l){let a=await C(l,e.company);(a.name||a.domain)&&(k=a)}if(!k){let a=h.email?(0,w.S)(h.email):null,b=e.company.Domain;if(a&&b){let c=a.replace(/'/g,"''"),d=await (0,v.Ez)(`
        SELECT entry_id FROM entry_fields
        WHERE field_id = ${(0,v.Qw)(b)}
          AND (LOWER(value) = '${c}' OR '${c}' LIKE '%.' || LOWER(value))
        LIMIT 1;
      `);d.length>0&&(k=await C(d[0].entry_id,e.company))}}let m={id:String(h.entry_id),name:h.name,email:h.email,company_id:l,company_name:k?.name??null,phone:h.phone,status:h.status,source:h.source,strength_score:Number.isFinite(i)?i:null,strength_label:j.label,strength_color:j.color,last_interaction_at:h.last_interaction_at,job_title:h.job_title,linkedin_url:h.linkedin_url,avatar_url:h.avatar_url,notes:h.notes,created_at:h.created_at,updated_at:h.updated_at},n=e.email_thread.Participants,o=[];if(n){(0,v.x6)(`MAX(CASE WHEN ef.field_id = '${n.replace(/'/g,"''")}' THEN ef.value END)`,m.id);let a=(0,v.gt)({objectId:u.zq.email_thread,fieldMap:e.email_thread,aliasedFields:[{name:"Subject",alias:"subject"},{name:"Last Message At",alias:"last_message_at"},{name:"Message Count",alias:"message_count"},{name:"Gmail Thread ID",alias:"gmail_thread_id"}]}),b=m.id.replace(/"/g,'""').replace(/'/g,"''"),c=n.replace(/'/g,"''"),d="candidate_threads",f=(0,v.Ut)({emailMessageFieldMap:e.email_message,candidateThreadIdsCte:d}),g=`
      WITH base AS (${a}),
      ${d} AS (
        SELECT entry_id FROM base
        WHERE EXISTS (
          SELECT 1 FROM entry_fields p
          WHERE p.entry_id = base.entry_id
            AND p.field_id = '${c}'
            AND p.value LIKE '%"${b}"%'
        )
        ORDER BY last_message_at DESC NULLS LAST
        LIMIT 50
      )${f?`, ${f.cte}`:""}
      SELECT
        base.*${f?`,
        latest_msg.sender_type AS sender_type,
        latest_msg.snippet AS snippet,
        latest_msg.from_person_id AS from_person_id`:`,
        NULL AS sender_type, NULL AS snippet, NULL AS from_person_id`}
      FROM base
      ${f?f.joinClause:""}
      WHERE base.entry_id IN (SELECT entry_id FROM ${d})
      ORDER BY base.last_message_at DESC NULLS LAST;
    `,h=await (0,v.Ez)(g),i=new Set;for(let a of h)a.from_person_id&&i.add(a.from_person_id);let j=await (0,v.cH)(Array.from(i),e.people);o=h.map(a=>{let b=a.from_person_id??null,c=b?j.get(b)??null:null;return{id:String(a.entry_id),subject:a.subject,last_message_at:a.last_message_at,message_count:a.message_count?Number(a.message_count):null,gmail_thread_id:a.gmail_thread_id,snippet:a.snippet,primary_sender_type:a.sender_type,primary_sender_id:b,primary_sender_name:c?.name??null,primary_sender_email:c?.email??null,primary_sender_avatar_url:c?.avatar_url??null}})}let p=e.calendar_event.Attendees,q=[];if(p){let a=(0,v.gt)({objectId:u.zq.calendar_event,fieldMap:e.calendar_event,aliasedFields:[{name:"Title",alias:"title"},{name:"Start At",alias:"start_at"},{name:"End At",alias:"end_at"},{name:"Meeting Type",alias:"meeting_type"},{name:"Google Event ID",alias:"google_event_id"}]}),b=`
      SELECT * FROM (${a}) sub
      WHERE EXISTS (
        SELECT 1 FROM entry_fields a
        WHERE a.entry_id = sub.entry_id
          AND a.field_id = '${p.replace(/'/g,"''")}'
          AND a.value LIKE '%"${m.id.replace(/"/g,'""').replace(/'/g,"''")}"%'
      )
      ORDER BY start_at DESC NULLS LAST
      LIMIT 50;
    `;q=(await (0,v.Ez)(b)).map(a=>({id:String(a.entry_id),title:a.title,start_at:a.start_at,end_at:a.end_at,meeting_type:a.meeting_type,google_event_id:a.google_event_id}))}let r=await D(m.id,e);return Response.json({person:m,company:k?{...k,website:k.website??(0,x.J)(k.domain??null)}:null,derived_website:(0,x.J)(m.email),threads:o,events:q,interactions_summary:r})}async function C(a,b){let c=(0,v.gt)({objectId:u.zq.company,fieldMap:b,aliasedFields:[{name:"Company Name",alias:"name"},{name:"Domain",alias:"domain"},{name:"Website",alias:"website"},{name:"Industry",alias:"industry"},{name:"Type",alias:"type"},{name:"Source",alias:"source"},{name:"Strength Score",alias:"strength_score"}],whereSql:`e.id = ${(0,v.Qw)(a)}`}),d=(await (0,v.Ez)(c))[0]??null;return{id:a,name:d?.name??null,domain:d?.domain??null,website:d?.website??null,industry:d?.industry??null,type:d?.type??null,source:d?.source??null,strength_score:d?.strength_score?Number(d.strength_score):null}}async function D(a,b){let c=b.interaction.Person,d=b.interaction.Type,e=b.interaction["Occurred At"],f=b.interaction.Direction;if(!c)return{email_count:0,meeting_count:0,total:0,last_outbound_at:null,last_inbound_at:null};let g=a.replace(/'/g,"''"),h=`
    SELECT
      COUNT(DISTINCT i.entry_id) AS total,
      SUM(CASE WHEN i.type = 'Email' THEN 1 ELSE 0 END) AS email_count,
      SUM(CASE WHEN i.type = 'Meeting' THEN 1 ELSE 0 END) AS meeting_count,
      MAX(CASE WHEN i.direction = 'Sent' THEN i.occurred_at END) AS last_outbound_at,
      MAX(CASE WHEN i.direction = 'Received' THEN i.occurred_at END) AS last_inbound_at
    FROM (
      SELECT
        e.id AS entry_id,
        ${d?`MAX(CASE WHEN ef.field_id = '${d.replace(/'/g,"''")}' THEN ef.value END)`:"NULL"} AS type,
        ${e?`MAX(CASE WHEN ef.field_id = '${e.replace(/'/g,"''")}' THEN ef.value END)`:"NULL"} AS occurred_at,
        ${f?`MAX(CASE WHEN ef.field_id = '${f.replace(/'/g,"''")}' THEN ef.value END)`:"NULL"} AS direction
      FROM entries e
      JOIN entry_fields person_rel ON person_rel.entry_id = e.id
        AND person_rel.field_id = '${c.replace(/'/g,"''")}'
        AND person_rel.value = '${g}'
      LEFT JOIN entry_fields ef ON ef.entry_id = e.id
      WHERE e.object_id = '${u.zq.interaction}'
      GROUP BY e.id
    ) i;
  `,i=(await (0,v.Ez)(h))[0];return{email_count:i?.email_count?Number(i.email_count):0,meeting_count:i?.meeting_count?Number(i.meeting_count):0,total:i?.total?Number(i.total):0,last_outbound_at:i?.last_outbound_at??null,last_inbound_at:i?.last_inbound_at??null}}let E=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/crm/people/[id]/route",pathname:"/api/crm/people/[id]",filename:"route",bundlePath:"app/api/crm/people/[id]/route"},distDir:".next",relativeProjectDir:"",resolvedPagePath:"/home/runner/work/DenchClaw/DenchClaw/apps/web/app/api/crm/people/[id]/route.ts",nextConfigOutput:"standalone",userland:d}),{workAsyncStorage:F,workUnitAsyncStorage:G,serverHooks:H}=E;function I(){return(0,g.patchFetch)({workAsyncStorage:F,workUnitAsyncStorage:G})}async function J(a,b,c){var d;let e="/api/crm/people/[id]/route";"/index"===e&&(e="/");let g=await E.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:B,resolvedPathname:C}=g,D=(0,j.normalizeAppPath)(e),F=!!(y.dynamicRoutes[D]||y.routes[C]);if(F&&!x){let a=!!y.routes[C],b=y.dynamicRoutes[D];if(b&&!1===b.fallback&&!a)throw new s.NoFallbackError}let G=null;!F||E.isDev||x||(G="/index"===(G=C)?"/":G);let H=!0===E.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)=>E.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=>E.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&&B&&!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 E.onRequestError(a,b,{routerKind:"App Router",routePath:e,routeType:"route",revalidateReason:(0,n.c)({isRevalidate:I,isOnDemandRevalidate:A})},z),b}},l=await E.handleResponse({req:a,nextConfig:w,cacheKey:G,routeKind:f.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:y,isRoutePPREnabled:!1,isOnDemandRevalidate:A,revalidateOnlyGenerated:B,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 E.onRequestError(a,b,{routerKind:"App Router",routePath:D,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}}},744870:a=>{a.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},848161:a=>{a.exports=require("node:os")},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,34531,93349,66131,99419],()=>b(b.s=735441));module.exports=c})();