"use strict";(()=>{var a={};a.id=55152,a.ids=[55152],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()}`}},518918:(a,b,c)=>{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,{GET:()=>A,dynamic:()=>y,runtime:()=>z});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(354826),x=c(237368);let y="force-dynamic",z="nodejs";async function A(a,b){let{id:c}=await b.params,d=c?.trim();if(!d)return Response.json({error:"Missing company id."},{status:400});let e=await (0,v.y3)(),f=(0,v.gt)({objectId:u.zq.company,fieldMap:e.company,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"},{name:"Last Interaction At",alias:"last_interaction_at"},{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:"Company not found."},{status:404});let h=g[0],i=h.strength_score?Number(h.strength_score):0,j=(0,x.WU)(i),k={id:String(h.entry_id),name:h.name,domain:h.domain,website:h.website??(0,w.J)(h.domain??null),industry:h.industry,type:h.type,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,notes:h.notes,created_at:h.created_at,updated_at:h.updated_at},l=[],m=(0,w.A)(k.domain??k.website),n=e.people.Company,o=[];if(n&&o.push(`sub.company_id = ${(0,v.Qw)(k.id)}`,(0,v.x6)("sub.company_id",k.id)),m){let a=(0,v.Qw)(m.toLowerCase()),b="LOWER(SUBSTR(sub.email, INSTR(sub.email, '@') + 1))";o.push(`${b} = ${a}`,`${b} LIKE '%.' || ${a}`)}if(o.length>0){let a=(0,v.gt)({objectId:u.zq.people,fieldMap:e.people,aliasedFields:[{name:"Full Name",alias:"name"},{name:"Email Address",alias:"email"},{name:"Company",alias:"company_id"},{name:"Job Title",alias:"job_title"},{name:"Strength Score",alias:"strength_score"},{name:"Last Interaction At",alias:"last_interaction_at"},{name:"Avatar URL",alias:"avatar_url"}]}),b=`
      SELECT * FROM (
        SELECT DISTINCT ON (COALESCE(LOWER(TRIM(sub.email)), sub.entry_id)) sub.*
        FROM (${a}) sub
        WHERE ${o.map(a=>`(${a})`).join("\n           OR ")}
        ORDER BY COALESCE(LOWER(TRIM(sub.email)), sub.entry_id),
                 TRY_CAST(sub.strength_score AS DOUBLE) DESC NULLS LAST,
                 sub.last_interaction_at DESC NULLS LAST
      ) deduped
      ORDER BY TRY_CAST(deduped.strength_score AS DOUBLE) DESC NULLS LAST,
               deduped.last_interaction_at DESC NULLS LAST
      LIMIT 100;
    `;l=(await (0,v.Ez)(b)).map(a=>{let b=a.strength_score?Number(a.strength_score):0,c=(0,x.WU)(b);return{id:String(a.entry_id),name:a.name,email:a.email,job_title:a.job_title,strength_score:Number.isFinite(b)?b:null,strength_label:c.label,strength_color:c.color,last_interaction_at:a.last_interaction_at,avatar_url:a.avatar_url}})}let p=e.email_thread.Companies,q=[];if(p){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=k.id.replace(/"/g,'""').replace(/'/g,"''"),c=p.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 c
          WHERE c.entry_id = base.entry_id
            AND c.field_id = '${c}'
            AND c.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);q=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 r=e.calendar_event.Companies,s=[];if(r){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"}]}),b=k.id.replace(/"/g,'""').replace(/'/g,"''"),c=`
      SELECT * FROM (${a}) sub
      WHERE EXISTS (
        SELECT 1 FROM entry_fields c
        WHERE c.entry_id = sub.entry_id
          AND c.field_id = '${r.replace(/'/g,"''")}'
          AND c.value LIKE '%"${b}"%'
      )
      ORDER BY start_at DESC NULLS LAST
      LIMIT 50;
    `;s=(await (0,v.Ez)(c)).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}))}let t={people_count:l.length,thread_count:q.length,event_count:s.length,strongest_contact:l[0]?.name??l[0]?.email??null};return Response.json({company:k,people:l,threads:q,events:s,summary:t})}let B=new e.AppRouteRouteModule({definition:{kind:f.RouteKind.APP_ROUTE,page:"/api/crm/companies/[id]/route",pathname:"/api/crm/companies/[id]",filename:"route",bundlePath:"app/api/crm/companies/[id]/route"},distDir:".next",relativeProjectDir:"",resolvedPagePath:"/home/runner/work/DenchClaw/DenchClaw/apps/web/app/api/crm/companies/[id]/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/crm/companies/[id]/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}}},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")},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=518918));module.exports=c})();