@@ -54,14 +54,27 @@ Entity name:`;
5454 ) ;
5555 }
5656
57- // Step 2: Query Firestore for existing entity (case-insensitive fuzzy match)
57+ // Step 2: Check if the report already exists in cache
58+ const entityNameLower = entityName . toLowerCase ( ) ;
59+ const cacheCollection = adminDb . collection ( "cache" ) ;
60+ const directCacheDoc = await cacheCollection . doc ( entityNameLower ) . get ( ) ;
61+
62+ if ( directCacheDoc . exists ) {
63+ const cachedData = directCacheDoc . data ( ) ;
64+ return Response . json ( {
65+ found : true ,
66+ reportId : directCacheDoc . id ,
67+ cachedAt : cachedData ?. cached_at || null ,
68+ entityName,
69+ } ) ;
70+ }
71+
72+ // Step 3: Query Firestore entities for case-insensitive fuzzy match
5873 const entitiesRef = adminDb . collection ( "entities" ) ;
5974 const snapshot = await entitiesRef . get ( ) ;
6075
61- let matchedEntity = null ;
62- const entityNameLower = entityName . toLowerCase ( ) ;
76+ let matchedEntity : Record < string , any > | null = null ;
6377
64- // Try exact match first, then fuzzy match
6578 for ( const doc of snapshot . docs ) {
6679 const data = doc . data ( ) ;
6780 const storedName = data . name ?. toLowerCase ( ) || "" ;
@@ -82,16 +95,35 @@ Entity name:`;
8295 }
8396 }
8497
85- // Step 3 : If entity exists , return it
98+ // Step 4 : If entity maps to a cached report , return it
8699 if ( matchedEntity ) {
87- return Response . json ( {
88- found : true ,
89- entity : matchedEntity ,
90- entityName,
91- } ) ;
100+ const possibleCacheIds = [
101+ matchedEntity . cacheId ,
102+ matchedEntity . cache_id ,
103+ matchedEntity . cacheDocId ,
104+ matchedEntity . cache_doc_id ,
105+ matchedEntity . id ,
106+ matchedEntity . name ,
107+ ]
108+ . filter ( Boolean )
109+ . map ( ( value : string ) => value . toLowerCase ( ) ) ;
110+
111+ for ( const cacheId of possibleCacheIds ) {
112+ const cacheDoc = await cacheCollection . doc ( cacheId ) . get ( ) ;
113+ if ( cacheDoc . exists ) {
114+ const cachedData = cacheDoc . data ( ) ;
115+ return Response . json ( {
116+ found : true ,
117+ reportId : cacheDoc . id ,
118+ cachedAt : cachedData ?. cached_at || null ,
119+ entityName,
120+ entity : matchedEntity ,
121+ } ) ;
122+ }
123+ }
92124 }
93125
94- // Step 4 : Entity not found, return entity name for client to trigger deep_security
126+ // Step 5 : Entity not found in cache , return entity name for client to trigger deep_security
95127 // The client will call the deep_security endpoint
96128 return Response . json ( {
97129 found : false ,
0 commit comments