Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

import React, { useState, useEffect, useRef } from "react"; import { FwTabs, FwTab,…

  1. User

    import React, { useState, useEffect, useRef } from "react"; import { FwTabs, FwTab, FwTabPanel, FwSpinner, ToastController, FwToast } from "@freshworks/crayons/react"; import AutomationCard from "./AutomationCard"; import { getTicketCreationRules, getTicketUpdationRules, getHourlyRules, getAgents } from '../common';

    const getRuleSignature = (rule) => JSON.stringify({ conditions: rule.summary.conditions, actions: rule.summary.actions, });

    // const Filterrecords = async (automationTypeId, newRulePloadDB3) => { // let allRecords = []; // let nextMarker = null;

    // try { // do { // const queryObj = { query: { automation_type_id: automationTypeId } }; // if (nextMarker) queryObj.next = { marker: nextMarker };

    // const response = await newRulePloadDB3.getAll(queryObj); // if (!response.records || !Array.isArray(response.records)) break;

    // allRecords = allRecords.concat(response.records.map(record => record.data)); // nextMarker = response.links?.next?.marker || null; // } while (nextMarker);

    // console.log(✅ Filtered Records for Type ${automationTypeId}:, allRecords); // return allRecords; // } catch (error) { // console.error("❌ Error fetching filtered records:", error); // return []; // } // };

    const Filterrecords = async (automationTypeId, newRulePloadDB3) => { let allRecords = []; let nextMarker = null;

    try { do { const queryObj = { query: { automation_type_id: automationTypeId } }; if (nextMarker) queryObj.next = { marker: nextMarker };

      const response = await newRulePloadDB3.getAll(queryObj);
      if (!response.records || !Array.isArray(response.records)) break;
    
      allRecords = allRecords.concat(response.records.map(record => ({
        ...record.data,
        display_id: record.display_id,              // add this line
        rule_id: record.data.rule_id,                // ensure rule_id included
        automation_type_id: record.data.automation_type_id,
        id: record.data.rule_id || record.data.id,  // make sure id is always set
      })));
    
      nextMarker = response.links?.next?.marker || null;
    } while (nextMarker);
    
    console.log(`✅ Filtered Records for Type ${automationTypeId}:`, allRecords);
    return allRecords;
    

    } catch (error) { console.error("❌ Error fetching filtered records:", error); return []; } };

    const groupDuplicates = (rules) => { const grouped = {}; rules.forEach((rule) => { const signature = getRuleSignature(rule); if (!grouped[signature]) grouped[signature] = []; grouped[signature].push(rule); }); return Object.values(grouped); };

    const AutomationTabs = ({ client }) => { const [searchTerm, setSearchTerm] = useState(""); const [searchTriggered, setSearchTriggered] = useState(false); const [activeTab, setActiveTab] = useState("ticketcreate"); const [tabsInitialized, setTabsInitialized] = useState(false);

    const [ticketCreationRules, setTicketCreationRules] = useState([]); const [ticketUpdateRules, setTicketUpdateRules] = useState([]); const [hourlyTriggerRules, setHourlyTriggerRules] = useState([]); const [loading, setLoading] = useState(false); const [currentPage, setCurrentPage] = useState(1); const [agent, setAgent] = useState([]);

    const toast = useRef(ToastController({ position: "top-right" }));

    const ticketCreateFilteredRecords = useRef([]); const ticketUpdateFilteredRecords = useRef([]); const hourlyFilteredRecords = useRef([]);

    const newRulePloadDB5 = useRef(null);

    const rulesPerPage = 5;

    const ticketCreate = 1; const ticketUpdate = 4; const hourlyTriggers = 3;

    useEffect(() => { const initializeDatabase = async () => { console.log("🟡 Initializing database and fetching tabs..."); const entity = await client.db.entity({ version: "v1" }); newRulePloadDB5.current = entity.get("newRulePloadDB5");

    // Use newRulePloadDB5.current for all further usage inside initializeDatabase const entticketcreate = await Filterrecords(ticketCreate, newRulePloadDB5.current); const enthourly = await Filterrecords(hourlyTriggers, newRulePloadDB5.current); const entticketupdate = await Filterrecords(ticketUpdate, newRulePloadDB5.current);

    ticketCreateFilteredRecords.current = entticketcreate; hourlyFilteredRecords.current = enthourly; ticketUpdateFilteredRecords.current = entticketupdate;

      setTicketCreationRules(entticketcreate);
      setTicketUpdateRules(entticketupdate);
      setHourlyTriggerRules(enthourly);
      
      const agentdaa = await getAgents(client);
      console.log("Available agent :", agentdaa);
    
      try {
        const tabData = await client.db.get("TabDB");
        if (!tabData || !tabData.LastVisitedTab) {
          await client.db.set("TabDB", { LastVisitedTab: "ticketcreate" });
          console.log("🟢 No tab stored before. Defaulting to 'ticketcreate'");
          setActiveTab("ticketcreate");
        } else {
          console.log("🟢 Loaded tab from DB:", tabData.LastVisitedTab);
          setActiveTab(tabData.LastVisitedTab);
        }
      } catch (error) {
        console.error("❌ Error retrieving TabDB:", error);
        await client.db.set("TabDB", { LastVisitedTab: "ticketcreate" });
        setActiveTab("ticketcreate");
      } finally {
        setTabsInitialized(true);
      }
    };
    
    initializeDatabase();
    

    }, [client]);

    useEffect(() => {

    const fwTabs = document.querySelector("fw-tabs");
    
    const saveActiveTab = async (e) => {
      const newActiveTab = e.target.panel;
      console.log("🟡 Tab clicked:", newActiveTab);
      setActiveTab(newActiveTab);
    
      try {
        let tabData = await client.db.get("TabDB") || {};
        tabData.LastVisitedTab = newActiveTab;
        await client.db.set("TabDB", tabData);
        console.log(`💾 Saved active tab to DB:`, newActiveTab);
      } catch (error) {
        console.error(`❌ Error setting active tab in DB:`, error);
      }
    };
    
    if (fwTabs) {
      fwTabs.addEventListener("fwChange", saveActiveTab);
    }
    
    return () => {
      if (fwTabs) {
        fwTabs.removeEventListener("fwChange", saveActiveTab);
      }
    };
    

    }, [client]);

    useEffect(() => { setCurrentPage(1); }, [activeTab]);

    const fetchRecentData = async () => { setLoading(true); await Promise.all([ getTicketCreationRules(client, setTicketCreationRules), getTicketUpdationRules(client, setTicketUpdateRules), getHourlyRules(client, setHourlyTriggerRules), getAgents(client, setAgent)

    ]);
    // console.log("Agent in tab :", agent);
    setLoading(false);
    

    };

    const getFilteredGroups = (rules) => {

    // console.log("Rule Data :", rules);
    
    const groupedRules = groupDuplicates(rules);
    if (!searchTriggered || !searchTerm.trim()) return groupedRules;
    
    return groupedRules.filter((group) =>
      group.some(
        (rule) =>
          rule.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
          rule.description?.toLowerCase().includes(searchTerm.toLowerCase())
      )
    );
    

    };

    const renderGroupedRules = (groups) => { const startIndex = (currentPage - 1) * rulesPerPage; const paginatedGroups = groups.slice(startIndex, startIndex + rulesPerPage);

    if (loading) {
      return (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '200px' }}>
          <FwSpinner size="medium" color="green" />
        </div>
      );
    }
    
    return paginatedGroups.length > 0 ? (
      paginatedGroups.map((group, index) => (
        <div
          key={index}
          className="fw-card-1"
          style={{
            border: "1px solid #ddd",
            borderRadius: "8px",
            marginBottom: "20px",
            marginTop: "20px",
            padding: "10px 16px",
            boxShadow: "0 4px 8px rgba(0, 0, 0, 0.1)",
            width: "80%",
            marginLeft: "auto",
            marginRight: "auto",
          }}
        >
          {group.map((rule, idx) => (          
            <AutomationCard
              key={idx}
              rule={rule}
              index={idx + 1}
              isFirstInGroup={idx === 0}              
              // onDelete={() => deleteRule(rule)}
              onDelete={() => deleteRule(rule, getFilteredRecordsForActiveTab())} 
              activeTab={activeTab}   
              agent={agent}        
            />
          ))}
        </div>
      ))
    ) : (
      <p style={{ textAlign: "center", marginTop: "20px" }}>
        No Rules Found Matched Your Search: {searchTerm}
      </p>
    );
    

    };

    const getFilteredRecordsForActiveTab = () => { switch(activeTab) { case "ticketcreate": return ticketCreateFilteredRecords.current; case "ticketupdate": return ticketUpdateFilteredRecords.current; case "hourly": return hourlyFilteredRecords.current; default: return []; } }

    const deleteRule = async (rule, filteredRecords) => { const { id, display_id, rule_id, automation_type_id } = rule;

    console.log("Entire filtered records from this tab at initialization:", filteredRecords);

    // Find matching filteredRecord by comparing rule.id (API ruleid) with filteredRecords ids const matchedRecord = filteredRecords.find(rec => rec.id === id);

    if (matchedRecord) { console.log("✅ Matched filtered record:", matchedRecord); console.log("Matched record's display_id:", matchedRecord.display_id); } else { console.warn("⚠️ No matching filtered record found for rule id:", id); }

    let automationTypeId; switch (activeTab) { case "ticketcreate": automationTypeId = ticketCreate; break; case "ticketupdate": automationTypeId = ticketUpdate; break; case "hourly": automationTypeId = hourlyTriggers; break; default: console.error("Unknown active tab: ", activeTab); return; }

    console.log("---------------Entity Data-----------"); console.log("Entity - display_id:", rule.display_id); console.log("Entity - rule_id:", rule_id); console.log("Entity - automation_type_id:", automation_type_id);

    console.log("---------------API Data-----------"); console.log("API - ruleid:", id); console.log("API From Tab:", activeTab); console.log("API - Automation id:", automationTypeId);

    // Use matchedRecord.display_id if matchedRecord exists, else fallback to rule.display_id or undefined const targetDisplayId = matchedRecord.display_id;

    console.log("Record to be deleted :", targetDisplayId);

    if (targetDisplayId && newRulePloadDB5.current) {

    try {
      await newRulePloadDB5.current.delete(targetDisplayId);
      console.log("✅ Successfully deleted entity record with display_id:", targetDisplayId);
    } catch (err) {
      console.error("❌ Error deleting entity record:", err);
    }
    

    } else if (!newRulePloadDB5.current) { console.error("❌ Entity DB reference not initialized yet."); }

    try { const response = await client.request.invokeTemplate("deleterule", { context: { automationid: automationTypeId, ruleid: id, }, });

    if (response.status === 204) {
      console.log("Rule deleted successfully!");
      if (activeTab === "ticketcreate") {
        setTicketCreationRules(ticketCreationRules.filter(r => r.id !== id));
      } else if (activeTab === "ticketupdate") {
        setTicketUpdateRules(ticketUpdateRules.filter(r => r.id !== id));
      } else if (activeTab === "hourly") {
        setHourlyTriggerRules(hourlyTriggerRules.filter(r => r.id !== id));
      }
    
      toast.current.trigger({ type: "success", content: "Rule deleted successfully!" });
    
    } else {
      console.error("Failed to delete rule.");      
      toast.current.trigger({ type: "error", content: "Failed to delete rule." });
    }
    

    } catch (error) { console.error("Error deleting rule:", error); }

    };

    const handlePageChange = (pageNumber) => setCurrentPage(pageNumber);

    const renderPagination = (groups) => { const totalPages = Math.ceil(groups.length / rulesPerPage); return ( <div style={{ textAlign: "center", marginTop: "20px" }}> {Array.from({ length: totalPages }, (_, index) => ( <button key={index + 1} onClick={() => handlePageChange(index + 1)} style={{ margin: "0 5px", padding: "5px 10px", cursor: "pointer", background: currentPage === index + 1 ? "#4CAF50" : "#ddd", }} > {index + 1} ))} ); };

    // console.log("🟢 Rendering AutomationTabs with activeTab:", activeTab);

    return ( <> Automations - Rules <input type="text" placeholder="Search by name or description" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} /> <button onClick={() => { setSearchTriggered(true); setCurrentPage(1); }}>Search <button onClick={fetchRecentData} style={{ marginLeft: "10px" }}>Recent API Data

      {tabsInitialized && (
        <FwTabs activeTab={activeTab}>
          <FwTab slot="tab" panel="ticketcreate" onClick={() => setActiveTab("ticketcreate")}>Ticket Creation</FwTab>
          <FwTab slot="tab" panel="ticketupdate" onClick={() => setActiveTab("ticketupdate")}>Ticket Updates</FwTab>
          <FwTab slot="tab" panel="hourly" onClick={() => setActiveTab("hourly")}>Hourly Triggers</FwTab>
    
          <FwTabPanel name="ticketcreate">
            {renderGroupedRules(getFilteredGroups(ticketCreationRules))}
            {renderPagination(getFilteredGroups(ticketCreationRules))}
          </FwTabPanel>
    
          <FwTabPanel name="ticketupdate">
            {renderGroupedRules(getFilteredGroups(ticketUpdateRules))}
            {renderPagination(getFilteredGroups(ticketUpdateRules))}
          </FwTabPanel>
    
          <FwTabPanel name="hourly">
            {renderGroupedRules(getFilteredGroups(hourlyTriggerRules))}
            {renderPagination(getFilteredGroups(hourlyTriggerRules))}
          </FwTabPanel>
        </FwTabs>
      )}
    
    </>
    

    ); };

    export default AutomationTabs;

    on populating data with entity storage, why pagination is not working it should work on both entity and api pagination also grouping of duplicates not working in entity why fix that too

  2. Assistant

    Let's carefully analyze the problem:


    Problem Summary

    • Pagination is not working when showing data from entity storage (your newRulePloadDB5 entity).
    • Grouping duplicates is not working for entity-fetched data but works for API data.
    • You want pagination and grouping to work seamlessly regardless of whether data comes from entity or from API.

    Root Cause Analysis & Fixes


    1. Pagination not working when data is from Entity storage

    Cause:

    Pagination is implemented on ticketCreationRules, ticketUpdateRules, and hourlyTriggerRules states.

    • But you are fetching entity data at init (Filterrecords), then storing these entity results in three refs:

      ticketCreateFilteredRecords.current = entticketcreate;
      ticketUpdateFilteredRecords.current = entticketupdate;
      hourlyFilteredRecords.current = enthourly;
      
    • And at the same time, you set states with these entity arrays:

      setTicketCreationRules(entticketcreate);
      setTicketUpdateRules(entticketupdate);
      setHourlyTriggerRules(enthourly);
      
    • The pagination is implemented on the state variables because getFilteredGroups gets passed these states as rules.

    • However, there's a catch in your deleteRule function you pass different data for the filtered records from ref arrays, which you use to find the display_id for deletion.

    • Your pagination depends on rules.length in state. So far so good.

    • But you have a search/filter logic tied to searchTriggered and searchTerm. Before searching, you return grouped rules as is, after searching, you filter those groups.

    Potential cause of pagination failure:

    • The entity data you fetch might contain duplicates that are not getting grouped properly (which I'll address below).

    • Because of duplicates not grouped properly, groups.length for pagination may be off.

    • Also, when the user switches tab or updates search, currentPage resets to 1, which is good.

    • But your render methods apply grouping and pagination over the state data, which should be OK.

    • So why pagination is lost? Usually because the groups array is always length=1 or length < rulesPerPage.

    Another cause could be related to how your groupDuplicates works on entity data:


    2. Grouping duplicates not working on entity data, but works on API data

    Code for grouping duplicates:

    const getRuleSignature = (rule) => JSON.stringify({
      conditions: rule.summary.conditions,
      actions: rule.summary.actions,
    });
    
    • It groups rules by signature which is a JSON string of conditions and actions.

    Problem:

    • The entity rules JSON structure might be different or missing summary or the nesting is different.

    • So rule.summary could be undefined or not structured exactly.

    Suggestion:

    • Add debugging in your getRuleSignature to check the structure:
    const getRuleSignature = (rule) => {
      if (!rule.summary) {
        console.warn("No summary found in rule:", rule);
        return JSON.stringify({});
      }
      return JSON.stringify({
        conditions: rule.summary.conditions,
        actions: rule.summary.actions,
      });
    };
    

    If entity rules have a different structure, adjust getRuleSignature to the entity field names, or normalize entity data before calling grouping.


    3. Fixes to apply


    A. Normalize entity Data Consistently

    Entity records may have fields like summary, conditions, or actions with different casing or nesting.

    Add normalization function like:

    const normalizeEntityRule = (rule) => {
      // if rule.summary missing, perhaps conditions and actions are top level or differently named
      // adjust accordingly after console.log for entity data
    
      // Example fallback
      return {
        ...rule,
        summary: rule.summary || {
          conditions: rule.conditions || [],
          actions: rule.actions || []
        }
      };
    }
    

    Then in Filterrecords, map entity records as:

    allRecords = allRecords.concat(
      response.records.map(record => {
        const data = normalizeEntityRule(record.data);
        return {
          ...data,
          display_id: record.display_id,
          id: data.rule_id || data.id
        };
    }));
    

    This way, your getRuleSignature can rely on presence of summary.conditions and summary.actions.


    B. Fix getRuleSignature to handle missing fields safely

    const getRuleSignature = (rule) => {
      const conditions = rule.summary?.conditions || rule.conditions || [];
      const actions = rule.summary?.actions || rule.actions || [];
      return JSON.stringify({ conditions, actions });
    };
    

    C. Confirm that rules passed to groupDuplicates are consistent

    • Wherever you call getFilteredGroups(rules) or groupDuplicates inside, log the contents to compare API vs entity:
    console.log("Grouping rules:", rules);
    

    D. Pagination logic works on grouped arrays

    renderPagination divides total groups by rulesPerPage and buttons update currentPage.

    Your render method slices groups accordingly.

    Make sure groups have correct length.


    E. Avoid silent issues in key props and in rendering

    Rendering AutomationCard within group uses:

    {group.map((rule, idx) => (
      <AutomationCard key={idx} ...
    

    key should be unique – better would be:

    <AutomationCard key={rule.id || idx} ...
    

    To avoid potential React re-rendering issues.


    F. Search behavior:

    You never reset searchTriggered to false. So after first search, everything is filtered.

    Maybe add a "Clear search" button that resets searchTerm and searchTriggered.


    G. Debug example

    Add debugging in renderGroupedRules:

    console.log("Paginated groups:", paginatedGroups);
    

    If paginatedGroups is always 0 or 1, pagination buttons won't do much.


    Summary

    • Normalize entity data structure before grouping.
    • Update getRuleSignature to robustly handle missing summary.
    • Verify keys in rendering.
    • Add debugging logs.
    • Possibly refresh example of cleared search states.

    Example Patch Snippet for Filterrecords

    const normalizeEntityRule = (rule) => {
      return {
        ...rule,
        summary: rule.summary || {
          conditions: rule.conditions || [],
          actions: rule.actions || []
        }
      };
    };
    
    const Filterrecords = async (automationTypeId, newRulePloadDB3) => {
      let allRecords = [];
      let nextMarker = null;
    
      try {
        do {
          const queryObj = { query: { automation_type_id: automationTypeId } };
          if (nextMarker) queryObj.next = { marker: nextMarker };
    
          const response = await newRulePloadDB3.getAll(queryObj);
          if (!response.records || !Array.isArray(response.records)) break;
    
          allRecords = allRecords.concat(response.records.map(record => {
            const data = normalizeEntityRule(record.data);
            return {
              ...data,
              display_id: record.display_id,
              id: data.rule_id || data.id,
              automation_type_id: data.automation_type_id,
            };
          }));
    
          nextMarker = response.links?.next?.marker || null;
        } while (nextMarker);
    
        console.log(`✅ Filtered Records for Type ${automationTypeId}:`, allRecords);
        return allRecords;
      } catch (error) {
        console.error("❌ Error fetching filtered records:", error);
        return [];
      }
    };
    

    And getRuleSignature:

    const getRuleSignature = (rule) => {
      const conditions = rule.summary?.conditions || [];
      const actions = rule.summary?.actions || [];
      return JSON.stringify({ conditions, actions });
    };
    

    With above fixes, your grouping should work correctly, yielding the proper groups length to allow pagination.


    If after this you still have issues, please share sample entity data shape so I can help normalize exact field names.

  3. User

    why pagination is not working in entity

  4. Assistant

    Let's focus specifically on why pagination is not working for entity data.


    How your pagination is implemented in brief:

    • Your entity data is fetched and stored in state variables, e.g.:

      setTicketCreationRules(entticketcreate);
      
    • Pagination logic and rendering apply on these states, after grouping duplicates:

      // Group duplicates and filter if search applied
      const groups = getFilteredGroups(ticketCreationRules);
      
      const startIndex = (currentPage - 1) * rulesPerPage;
      const paginatedGroups = groups.slice(startIndex, startIndex + rulesPerPage);
      
      // Render paginatedGroups
      
    • The total number of pages is based on groups.length divided by rulesPerPage.


    Why entity data breaks pagination

    Common reasons:

    1. Grouping duplicates does not work as expected on entity data, so all rules fall into a single group.

      • This means groups.length is always 1 or very small.
      • In pagination, if total groups = 1, page buttons show only one page.
      • Hence you effectively have no pagination.
    2. Entity rules lack fields required for grouping and filtering (like summary.conditions, summary.actions), so getRuleSignature returns identical or empty signatures.

    3. The entity data in state has unexpected structure or missing unique identifiers, causing groupDuplicates() to misbehave.

    4. The entity data's id fields might be missing or duplicated, leading to rendering or state updates issues.


    Debug exactly why:

    Step 1: Log groups count for entity data

    Inside your getFilteredGroups() add:

    console.log("Number of groups:", groupedRules.length);
    

    If this logs 1 for all cases, that’s the cause — all entity data is being grouped as one.


    Step 2: Inspect getRuleSignature

    Check if entity data rule.summary exists and contains conditions and actions.

    Add logging:

    const getRuleSignature = (rule) => {
      if (!rule.summary) {
        console.warn("Missing summary in rule:", rule);
        return JSON.stringify({});
      }
      return JSON.stringify({
        conditions: rule.summary.conditions,
        actions: rule.summary.actions,
      });
    };
    

    If the warning shows always for entity data, then your grouping uses invalid signature — all rules get same signature {}, hence grouped as one.


    Most likely root cause:

    Your entity data has different structure, e.g., no summary object or fields are named differently.


    How to fix:

    Normalize entity data before grouping

    Example normalization (modify according to actual entity structure):

    const normalizeEntityRule = (rule) => {
      // Provide empty conditions/actions if missing to avoid empty signatures
      if (!rule.summary) {
        rule.summary = {
          conditions: rule.conditions || [],
          actions: rule.actions || []
        };
      }
      return rule;
    };
    

    Make sure Filterrecords() applies this:

    allRecords = allRecords.concat(response.records.map(record => {
      const normRule = normalizeEntityRule(record.data);
      return {
        ...normRule,
        display_id: record.display_id,
        id: normRule.rule_id || normRule.id,
      };
    }));
    

    Summary — Why pagination fails for entity data:

    • Entity rules don't have the summary field, so their signature becomes empty or identical.
    • As a result, all rules get grouped into a single group.
    • Your pagination depends on number of groups.
    • Since groups = 1, pagination controls show only a single page → pagination "does not work".

    What to do exactly:

    1. Add logging in getRuleSignature to verify entity data structure.
    2. Adjust getRuleSignature to handle entity data shape safely.
    3. Normalize entity data at fetch time to add any missing summary, conditions, and actions.
    4. Test grouping with normalized entity rules: now the groups count should increase.
    5. Pagination will then work because you get multiple groups to paginate.

    Extra tip:

    You can add a fallback for getRuleSignature when summary missing:

    const getRuleSignature = (rule) => {
      const conditions = rule.summary?.conditions || rule.conditions || [];
      const actions = rule.summary?.actions || rule.actions || [];
      return JSON.stringify({ conditions, actions });
    };
    

    If you want me to help normalize exactly, please share a sample entity data rule object shape.

  5. User

    ok. why grouping duplicates is not working in entity? why?

  6. Assistant

    The reason grouping duplicates is not working for entity data is almost always because the function you use to create the "grouping key" or "signature" — here, getRuleSignature — produces the same signature for all entity rules, or signatures that don't correctly reflect their logical uniqueness.


    In your code, grouping depends on:

    const getRuleSignature = (rule) => JSON.stringify({
      conditions: rule.summary.conditions,
      actions: rule.summary.actions,
    });
    

    Why does this fail for entity data?

    Most likely causes:

    1. Entity data has a different schema than API data.
    • Your API data has rule.summary.conditions and rule.summary.actions.
    • Your entity data might not have a summary field at all, or conditions/actions might be direct properties or under differently named fields.
    1. If rule.summary is undefined or null, then rule.summary.conditions throws error or silently evaluates to undefined.
    • When JSON.stringify({ conditions: undefined, actions: undefined }), you get "{}".

    • So all entity rules produce the same signature: "{}" — causing all rules to be grouped into one group, which breaks duplicate grouping.


    How to verify this:

    Add console logs inside getRuleSignature:

    const getRuleSignature = (rule) => {
      if (!rule.summary) {
        console.warn("[Warning] Rule missing summary:", rule);
      }
      const signature = JSON.stringify({
        conditions: rule.summary?.conditions,
        actions: rule.summary?.actions,
      });
      console.log("Rule signature:", signature);
      return signature;
    };
    

    Check your console output for entity rules.


    How to fix this:


    1. Make getRuleSignature structure-robust:

    Handle missing summary, and fallback to other fields commonly found in entity data:

    const getRuleSignature = (rule) => {
      const conditions = rule.summary?.conditions || rule.conditions || [];
      const actions = rule.summary?.actions || rule.actions || [];
      return JSON.stringify({ conditions, actions });
    };
    

    2. Normalize entity data after fetching to have consistent shape:

    Modify Filterrecords:

    const normalizeEntityRule = (rule) => {
      // If no summary, create one with fallback fields or empty arrays
      if (!rule.summary) {
        rule.summary = {
          conditions: rule.conditions || [],
          actions: rule.actions || [],
        };
      }
      return rule;
    };
    
    allRecords = allRecords.concat(response.records.map(record => {
      const normalizedData = normalizeEntityRule(record.data);
      return {
        ...normalizedData,
        display_id: record.display_id,
        id: normalizedData.rule_id || normalizedData.id,
      };
    }));
    

    3. Ensure fields conditions and actions truly represent the rule's defining logic

    Because grouping depends on these fields being consistent to detect duplicates, make sure those arrays are complete and correctly structured.


    TL;DR

    • Grouping is done by JSON.stringify-ing rule.summary.conditions and rule.summary.actions.
    • Your entity data does not have summary field or it’s empty.
    • Result: all entity rules have identical signatures ("{}") → all grouped as one group.
    • Fix: Adjust getRuleSignature to work with entity data, or normalize entity data to always have summary.

    If you provide a sample of actual entity record data, I can help you craft the exact normalization or signature code.