@@ -30,16 +30,37 @@ const useGraphQlApi = ({ initialPeriodsToLoad = DOCUMENT_LIST_SHARDS_PER_DAY * 2
3030 logger . debug ( 'setDocumentsDeduped called with:' , documentValues ) ;
3131 setDocuments ( ( currentDocuments ) => {
3232 const documentValuesdocumentIds = documentValues . map ( ( c ) => c . ObjectKey ) ;
33- const updatedDocuments = [
34- ...currentDocuments . filter ( ( c ) => ! documentValuesdocumentIds . includes ( c . ObjectKey ) ) ,
35- ...documentValues . map ( ( document ) => ( {
36- ...document ,
37- ListPK : document . ListPK || currentDocuments . find ( ( c ) => c . ObjectKey === document . ObjectKey ) ?. ListPK ,
38- ListSK : document . ListSK || currentDocuments . find ( ( c ) => c . ObjectKey === document . ObjectKey ) ?. ListSK ,
39- } ) ) ,
40- ] ;
41- logger . debug ( 'Documents state updated, new count:' , updatedDocuments . length ) ;
42- return updatedDocuments ;
33+
34+ // Remove old entries with matching ObjectKeys
35+ const filteredCurrentDocuments = currentDocuments . filter ( ( c ) => ! documentValuesdocumentIds . includes ( c . ObjectKey ) ) ;
36+
37+ // Add new entries with PK/SK preserved
38+ const newDocuments = documentValues . map ( ( document ) => ( {
39+ ...document ,
40+ ListPK : document . ListPK || currentDocuments . find ( ( c ) => c . ObjectKey === document . ObjectKey ) ?. ListPK ,
41+ ListSK : document . ListSK || currentDocuments . find ( ( c ) => c . ObjectKey === document . ObjectKey ) ?. ListSK ,
42+ } ) ) ;
43+
44+ // Combine and deduplicate by ObjectKey, keeping only the latest entry per ObjectKey
45+ const allDocuments = [ ...filteredCurrentDocuments , ...newDocuments ] ;
46+ const deduplicatedByObjectKey = Object . values (
47+ allDocuments . reduce ( ( acc , doc ) => {
48+ const existing = acc [ doc . ObjectKey ] ;
49+ // Keep the document with the most recent CompletionTime or InitialEventTime
50+ if ( ! existing ) {
51+ acc [ doc . ObjectKey ] = doc ;
52+ } else {
53+ const existingTime = existing . CompletionTime || existing . InitialEventTime || '0' ;
54+ const newTime = doc . CompletionTime || doc . InitialEventTime || '0' ;
55+ if ( newTime > existingTime ) {
56+ acc [ doc . ObjectKey ] = doc ;
57+ }
58+ }
59+ return acc ;
60+ } , { } ) ,
61+ ) ;
62+
63+ return deduplicatedByObjectKey ;
4364 } ) ;
4465 } , [ ] ) ;
4566
0 commit comments