or give me the part that you modified
- User
or give me the part that you modified
- Assistant
Sure! Please provide the original text or code you want me to modify, and I’ll highlight or share just the part that I changed.
- User
import React, { useState, useEffect, useRef } from "react"; import { FwTabs, FwTab, FwTabPanel, FwSpinner, ToastController, FwToast, FwPagination, FwButton, FwIcon, FwListOptions, FwPopover, FwModal, } from "@freshworks/crayons/react"; import AutomationCard from "./AutomationCard"; import SummaryContent from "./SummaryContent"; import { getTicketCreationRules, getTicketUpdationRules, getHourlyRules, getAgents, pagination, } from "../common";
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 getRuleSignature = (rule) => { const conditions = rule.summary?.conditions || rule.conditions; const actions = rule.summary?.actions || rule.actions; return JSON.stringify({ conditions, 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; const filtered = response.records .map((record) => ({ ...record.data, display_id: record.display_id, rule_id: record.data.rule_id, automation_type_id: record.data.automation_type_id, id: record.data.rule_id || record.data.id, })) .filter((record) => record.active === "true"); allRecords = allRecords.concat(filtered); 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 AutomationTabs = ({ client }) => { const [isRulesDBReady, setIsRulesDBReady] = useState(false); const [loadingBannerVisible, setLoadingBannerVisible] = useState(true); const intervalIdRef = useRef(null); const [showSearchHint, setShowSearchHint] = useState(false);
const [searchTerm, setSearchTerm] = useState(""); const [searchQuery, setSearchQuery] = useState(""); const [searchTriggered, setSearchTriggered] = useState(false);
const [activeTab, setActiveTab] = useState("ticketcreate"); const [tabsInitialized, setTabsInitialized] = useState(false); const modalRef = useRef(null);
const [ticketCreationRules, setTicketCreationRules] = useState([]); const [ticketUpdateRules, setTicketUpdateRules] = useState([]); const [hourlyTriggerRules, setHourlyTriggerRules] = useState([]);
const [loading, setLoading] = useState(false); const [agent, setAgent] = useState([]); // const [ruleViewFilter, setRuleViewFilter] = useState(ruleViewOptions[0]);
const rulesPerPage = 30;
const [currentPage, setCurrentPage] = useState({ ticketcreate: 1, ticketupdate: 1, hourly: 1, });
const toast = useRef(ToastController({ position: "top-center" }));
const newRulePloadDB5 = useRef(null);
const ticketCreate = 1; const ticketUpdate = 4; const hourlyTriggers = 3;
// ===== CHANGE: initial fetchFromApi to false to fetch entity data initially ===== const [fetchFromApi, setFetchFromApi] = useState(false);
const [showPagination, setShowPagination] = useState(false);
// ======= Grouped state arrays to hold duplicate groups ======= const [ticketCreationRuleGroups, setTicketCreationRuleGroups] = useState([]); const [ticketUpdateRuleGroups, setTicketUpdateRuleGroups] = useState([]); const [hourlyRuleGroups, setHourlyRuleGroups] = useState([]); // =============================================================
// ----- NEW: rule view filter for 'All Rules' or 'Duplicate Rules' ----- const ruleViewOptions = [ { value: "all_rules", text: "All Rules", graphicsProps: { name: "list" }, }, { value: "duplicate_rules", text: "Duplicate Rules", graphicsProps: { name: "warning" }, }, ]; const [ruleViewFilter, setRuleViewFilter] = useState(ruleViewOptions[0]); // ---------------------------------------------------------------------
useEffect(() => { setShowPagination(false);
let timer = setTimeout(() => { setShowPagination(true); }, 2000); return () => clearTimeout(timer);}, [activeTab, currentPage]);
useEffect(() => { const initializeDatabase = async () => { console.log("🟡 Initializing database and fetching tabs..."); const entity = await client.db.entity({ version: "v1" }); newRulePloadDB5.current = entity.get("newRulePloadDB5");
// Initial fetch already handled by useEffect below (on fetchFromApi change) // So no need to fetch here to avoid duplication keeping consistent with new fetch logic. const agentdaa = await getAgents(client); console.log("Available agent :", agentdaa); setAgent(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]);
// Whenever activeTab changes, reset its page to 1 useEffect(() => { setCurrentPage((prev) => ({ ...prev, [activeTab]: 1, })); }, [activeTab]);
// ===== NEW EFFECT ===== // On activeTab or fetchFromApi change, fetch data accordingly useEffect(() => { const fetchOnTabOrModeChange = async () => { setLoading(true); if (fetchFromApi) { try { if (activeTab === "ticketcreate") { await getTicketCreationRules(client, setTicketCreationRules); } else if (activeTab === "ticketupdate") { await getTicketUpdationRules(client, setTicketUpdateRules); } else if (activeTab === "hourly") { await getHourlyRules(client, setHourlyTriggerRules); } await getAgents(client, setAgent); } catch (err) { console.error("Error fetching API data:", err); } } else { if (!newRulePloadDB5.current) { console.error("❌ Entity DB reference not initialized."); setLoading(false); return; } try { if (activeTab === "ticketcreate") { const data = await Filterrecords(ticketCreate, newRulePloadDB5.current); setTicketCreationRules(data); } else if (activeTab === "ticketupdate") { const data = await Filterrecords(ticketUpdate, newRulePloadDB5.current); setTicketUpdateRules(data); } else if (activeTab === "hourly") { const data = await Filterrecords(hourlyTriggers, newRulePloadDB5.current); setHourlyTriggerRules(data); } } catch (err) { console.error("Error fetching entity data:", err); } } setLoading(false); };
if (tabsInitialized && isRulesDBReady) { fetchOnTabOrModeChange(); }}, [activeTab, fetchFromApi, client, tabsInitialized, isRulesDBReady]);
const handlePageChange = (tab) => (event) => { setCurrentPage((prev) => ({ ...prev, [tab]: event.detail.page, })); };
useEffect(() => { const fwTabs = document.querySelector("fw-tabs");
const saveActiveTab = async (e) => { const newActiveTab = e.target.panel; setActiveTab(newActiveTab); try { let tabData = (await client.db.get("TabDB")) || {}; tabData.LastVisitedTab = newActiveTab; await client.db.set("TabDB", tabData); } 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]);
// ===== UPDATE: fetchData now just toggles fetchFromApi and triggers data fetch on that state change ===== const fetchData = async () => { // Toggle mode and data fetch will happen automatically in useEffect above setFetchFromApi((prev) => !prev);
// Show toast for user info toast.current.trigger({ type: "info", content: `Fetching ${ fetchFromApi ? "Entity Data" : "Recent API Data" }...`, });};
const checkAndSetButtonState = async () => { try { const storedvalue1 = await client.db.get("RulesDB"); const isButtonEnabled = !!storedvalue1.stored; if (isButtonEnabled) { setIsRulesDBReady(true); setLoadingBannerVisible(false);
if (intervalIdRef.current) { clearInterval(intervalIdRef.current); intervalIdRef.current = null; } } else { setIsRulesDBReady(false); setLoadingBannerVisible(true); if (!intervalIdRef.current) { intervalIdRef.current = setInterval(checkAndSetButtonState, 60000); } } } catch (error) { if (error.status === 404) { setIsRulesDBReady(true); setLoadingBannerVisible(false); if (intervalIdRef.current) { clearInterval(intervalIdRef.current); intervalIdRef.current = null; } } else { console.error("❌ Error retrieving stored value from RulesDB:", error); } }};
useEffect(() => { checkAndSetButtonState();
return () => { if (intervalIdRef.current) clearInterval(intervalIdRef.current); };}, []);
const getFilteredRules = (rules) => { if (!searchQuery.trim()) return rules; // If searchQuery is empty, show all rules
return rules.filter( (rule) => rule.name?.toLowerCase().includes(searchQuery.toLowerCase()) || rule.description?.toLowerCase().includes(searchQuery.toLowerCase()) );};
const flattenGroups = (groups) => groups.flat();
const getPaginatedRules = (rules, tab) => { const filtered = getFilteredRules(rules); return pagination(filtered, currentPage[tab]); };
// const AnimatedSearchInput = () => { // const [expanded, setExpanded] = useState(false); // const inputRef = useRef(null);
// // Imperatively update fw-input's internal value when React state changes // useEffect(() => { // if (inputRef.current) { // inputRef.current.value = searchTerm; // } // }, [searchTerm]);
// return ( // <div style={{ width: "100%", transition: "width 0.3s ease-in-out", padding: "6px", maxWidth: "500px" }}> // <fw-input // ref={inputRef} // icon-left="search" // hint-text="Please Enter Keyword to Search" // warning-text="Please Enter Keyword to Search" // error-text="Enter a Rule" // state="normal" // placeholder="Search Rules" // clear-input // style={{ width: "100%" }} // onFocus={() => setExpanded(true)} // onBlur={() => setExpanded(false)} // onInput={(e) => { // setSearchTerm(e.target.value); // sync React state with input event // if (showSearchHint) setShowSearchHint(false); // }} // onKeyDown={(e) => { // if (e.key === "Enter") { // const trimmed = e.target.value.trim(); // if (!trimmed) { // setSearchQuery(""); // setShowSearchHint(false); // } else { // setSearchQuery(trimmed); // setShowSearchHint(false); // } // } // }} // // NOTE: Do NOT set value={searchTerm} here! // /> // // ); // };
const inputRef = useRef(null);
useEffect(() => { if (inputRef.current) { inputRef.current.value = searchTerm; } }, [searchTerm]);
const searchInputs = ( <div style={{ display: "flex", alignItems: "center", marginBottom: 10, marginLeft: 20, marginTop: 15, maxWidth: "100%", gap: "20px", }} > {/* "All Rules" button on the left /} <div style={{ flexShrink: 0 }}> {ruleViewFilter.text} <div slot="popover-content" style={{ width: 220 }}> {/ list options code here... */} <span style={{ fontStyle: "italic" }} className="row fw-flex fw-type-xs fw-p-4 fw-type-semibold" > Select Rule View <hr style={{ margin: 0 }} /> <FwListOptions onFwChange={(event) => { const selected = event.detail?.meta?.selectedOptions[0]; if (selected) { setRuleViewFilter(selected); setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
if (selected.value === "all_rules") { setTicketCreationRuleGroups([]); setTicketUpdateRuleGroups([]); setHourlyRuleGroups([]); } else if (selected.value === "duplicate_rules") { handleFilterApiClick(); } } }} selectedOptions={[ruleViewFilter]} options={ruleViewOptions} variant="icon" /> </div> </FwPopover> </div> <div style={{ flex: 1, display: "flex", justifyContent: "center", marginTop: 20 }}><fw-input ref={inputRef} icon-left="search" hint-text="Do not enter your user ID" warning-text="Please use numbers for user ID" placeholder="Enter a Keyword to Search..." error-text="Invalid user ID" clear-input style={{ width: "400px", height: "60px", // Positive height value fontSize: "18px", }} onInput={(e) => { setSearchTerm(e.target.value); if (showSearchHint) setShowSearchHint(false); }} onKeyDown={(e) => { if (e.key === "Enter") { const trimmed = e.target.value.trim(); if (!trimmed) { setSearchQuery("");
setShowSearchHint(false); } else { setSearchQuery(trimmed);
setShowSearchHint(false); } } }}/>
{/* "Add New Rule" button aligned right */} <div style={{ flexShrink: 0 }}> <FwButton color="primary" onFwClick={() => {/* Add your handler here */}}> Add New Rule </FwButton> </div> </div>);
const renderRulesOrGroups = () => { let groups = []; let flatRules = [];
if (activeTab === "ticketcreate") { groups = ticketCreationRuleGroups; flatRules = ticketCreationRules; } else if (activeTab === "ticketupdate") { groups = ticketUpdateRuleGroups; flatRules = ticketUpdateRules; } else if (activeTab === "hourly") { groups = hourlyRuleGroups; flatRules = hourlyTriggerRules; } if (loading) { return ( <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "200px", }} > <FwSpinner size="medium" color="green" /> </div> ); } if (ruleViewFilter.value === "duplicate_rules" && groups.length > 0) { // Flatten, filter, paginate on flat filtered groups const flattenedFiltered = getFilteredRules(flattenGroups(groups)); const paginatedRules = pagination(flattenedFiltered, currentPage[activeTab]); const paginatedRuleIds = new Set(paginatedRules.map((r) => r.id)); return ( <div style={{ marginLeft: 10, marginRight: "auto" }}> {groups.map((group, idx) => { const rulesToShow = group.filter((rule) => paginatedRuleIds.has(rule.id) ); if (rulesToShow.length === 0) return null; return ( <div key={`group-${idx}`} style={{ marginBottom: "12px" }}> {rulesToShow.map((rule, i) => ( <div key={rule.id} className="fw-card-1" style={{ marginBottom: "10px", marginTop: i === 0 ? "10px" : "2px", padding: "5px 8px", marginLeft: "20px", borderRadius: "4px", }} > <AutomationCard rule={rule} index={i + 1} isFirstInGroup={i === 0} onDelete={() => deleteRule(rule, flattenGroups(groups)) } activeTab={activeTab} onSelect={openRuleDetails} agent={agent} /> </div> ))} </div> ); })} </div> ); } else { const filteredFlatRules = getFilteredRules(flatRules); const paginatedFlatRules = pagination(filteredFlatRules, currentPage[activeTab]); if (paginatedFlatRules.length === 0) { return ( <p style={{ textAlign: "center", marginTop: "20px" }}> {/* No Rules Found Matched Your Search: {searchTerm} */} No Duplicate Rules Found. </p> ); } return paginatedFlatRules.map((rule, idx) => ( <div key={rule.id || idx} className="fw-card-1" style={{ marginBottom: "5px", marginTop: "10px", padding: "5px 8px", marginLeft: 10, marginRight: "auto", }} > <AutomationCard rule={rule} index={idx + 1} isFirstInGroup={true} onDelete={() => deleteRule(rule, filteredFlatRules)} activeTab={activeTab} onSelect={openRuleDetails} agent={agent} /> </div> )); }};
const deleteRule = async (rule, allRulesList) => { const { id } = rule; const matchedRecord = allRulesList.find((rec) => rec.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; } const targetDisplayId = matchedRecord ? matchedRecord.display_id : undefined; if (targetDisplayId && newRulePloadDB5.current) { try { await newRulePloadDB5.current.delete(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) { if (activeTab === "ticketcreate") { setTicketCreationRules(ticketCreationRules.filter((r) => r.id !== id)); setTicketCreationRuleGroups([]); } else if (activeTab === "ticketupdate") { setTicketUpdateRules(ticketUpdateRules.filter((r) => r.id !== id)); setTicketUpdateRuleGroups([]); } else if (activeTab === "hourly") { setHourlyTriggerRules(hourlyTriggerRules.filter((r) => r.id !== id)); setHourlyRuleGroups([]); } toast.current.trigger({ type: "success", content: "Rule deleted successfully!" }); } else { toast.current.trigger({ type: "error", content: "Failed to delete rule." }); } } catch (error) { console.error("Error deleting rule:", error); toast.current.trigger({ type: "error", content: "Error deleting rule." }); }};
const openRuleDetails = (rule) => { };
const closeRuleDetails = () => { };
const handleFilterApiClick = () => { if (activeTab === "ticketcreate") { const grouped = groupDuplicates(ticketCreationRules);
const duplicateGroups = grouped .filter((group) => group.length > 1) .sort((a, b) => b.length - a.length); console.log("Grouped Ticket Creation Rules (duplicates only):", duplicateGroups); setTicketCreationRuleGroups(duplicateGroups); setCurrentPage((prev) => ({ ...prev, ticketcreate: 1 })); toast.current.trigger({ type: "success", content: `Grouped Ticket Creation Rules into ${duplicateGroups.length} duplicate groups.`, }); } else if (activeTab === "ticketupdate") { const grouped = groupDuplicates(ticketUpdateRules); const duplicateGroups = grouped .filter((group) => group.length > 1) .sort((a, b) => b.length - a.length); console.log("Grouped Ticket Update Rules (duplicates only):", duplicateGroups); setTicketUpdateRuleGroups(duplicateGroups); setCurrentPage((prev) => ({ ...prev, ticketupdate: 1 })); toast.current.trigger({ type: "success", content: `Grouped Ticket Update Rules into ${duplicateGroups.length} duplicate groups.`, }); } else if (activeTab === "hourly") { const grouped = groupDuplicates(hourlyTriggerRules); const duplicateGroups = grouped .filter((group) => group.length > 1) .sort((a, b) => b.length - a.length); console.log("Grouped Hourly Rules (duplicates only):", duplicateGroups); setHourlyRuleGroups(duplicateGroups); setCurrentPage((prev) => ({ ...prev, hourly: 1 })); toast.current.trigger({ type: "success", content: `Grouped Hourly Rules into ${duplicateGroups.length} duplicate groups.`, }); }};
const getPaginatedItemCount = () => { let rules = []; if (activeTab === "ticketcreate") rules = ticketCreationRules; else if (activeTab === "ticketupdate") rules = ticketUpdateRules; else if (activeTab === "hourly") rules = hourlyTriggerRules;
let groups = []; if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups; else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups; else if (activeTab === "hourly") groups = hourlyRuleGroups; // Show counts based on current ruleViewFilter if (ruleViewFilter.value === "duplicate_rules" && groups.length > 0) { const flatList = flattenGroups(groups); const filtered = getFilteredRules(flatList); const paginated = pagination(filtered, currentPage[activeTab]); return paginated.length; } else { const flatList = rules; const filtered = getFilteredRules(flatList); const paginated = pagination(filtered, currentPage[activeTab]); return paginated.length; }};
const getCurrentTotalCount = () => { // Show counts based on current ruleViewFilter if (activeTab === "ticketcreate") { if (ruleViewFilter.value === "duplicate_rules" && ticketCreationRuleGroups.length > 0) { return flattenGroups(ticketCreationRuleGroups).filter( (r) => !searchQuery.trim() || r.name?.toLowerCase().includes(searchQuery.toLowerCase()) || r.description?.toLowerCase().includes(searchQuery.toLowerCase()) ).length; } return getFilteredRules(ticketCreationRules).length; } else if (activeTab === "ticketupdate") { if (ruleViewFilter.value === "duplicate_rules" && ticketUpdateRuleGroups.length > 0) { return flattenGroups(ticketUpdateRuleGroups).filter( (r) => !searchQuery.trim() || r.name?.toLowerCase().includes(searchQuery.toLowerCase()) || r.description?.toLowerCase().includes(searchQuery.toLowerCase()) ).length; } return getFilteredRules(ticketUpdateRules).length; } else if (activeTab === "hourly") { if (ruleViewFilter.value === "duplicate_rules" && hourlyRuleGroups.length > 0) { return flattenGroups(hourlyRuleGroups).filter( (r) => !searchQuery.trim() || r.name?.toLowerCase().includes(searchQuery.toLowerCase()) || r.description?.toLowerCase().includes(searchQuery.toLowerCase()) ).length; } return getFilteredRules(hourlyTriggerRules).length; } return 0; };
return ( <> Automations - Rules
{/* <div style={{ marginBottom: 10 }}> <FwButton color="secondary" onFwClick={handleFilterApiClick}> Filter API (Based on Duplicates (High to Low)) </FwButton> </div> */} {showSearchHint && ( <p style={{ color: "red", marginTop: "4px", fontSize: "0.9em" }}> Please enter a search term before searching. </p> )}{loadingBannerVisible && !isRulesDBReady && (
{tabsInitialized && (
{/* {loadingBannerVisible && !isRulesDBReady && ( <div style={{ display: "flex", alignItems: "center", marginBottom: 15 }}> <FwSpinner size="medium" color="green" /> <span style={{ marginLeft: "8px" }}>Waiting for rules to be ready...</span> </div> )} */} <div style={{ display: "flex", justifyContent: "flex-end", marginBottom: 15, }} > {/* Fetch button is always visible but disabled before DB is ready */} <FwButton color="secondary" onFwClick={fetchData} disabled={!isRulesDBReady}> {fetchFromApi ? "Get Entity Data" : "Get Recent Data"} </FwButton> </div> <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"> {searchInputs} {renderRulesOrGroups()} {showPagination && getPaginatedItemCount() > 0 && ( <div style={{ marginTop: 10 }}> <div style={{ display: "flex", justifyContent: "center" }}> <FwPagination per-page={rulesPerPage} total={getCurrentTotalCount()} page={currentPage.ticketcreate} onFwChange={handlePageChange("ticketcreate")} /> </div> </div> )} </FwTabPanel> <FwTabPanel name="ticketupdate"> {searchInputs} {renderRulesOrGroups()} {showPagination && getPaginatedItemCount() > 0 && ( <div style={{ marginTop: 10 }}> <div style={{ display: "flex", justifyContent: "center" }}> <FwPagination per-page={rulesPerPage} total={getCurrentTotalCount()} page={currentPage.ticketupdate} onFwChange={handlePageChange("ticketupdate")} /> </div> </div> )} </FwTabPanel> <FwTabPanel name="hourly"> {searchInputs} {renderRulesOrGroups()} {showPagination && getPaginatedItemCount() > 0 && ( <div style={{ marginTop: 10 }}> <div style={{ display: "flex", justifyContent: "center" }}> <FwPagination per-page={rulesPerPage} total={getCurrentTotalCount()} page={currentPage.hourly} onFwChange={handlePageChange("hourly")} /> </div> </div> )} </FwTabPanel> </FwTabs><FwToast /> </>);
};
export default AutomationTabs;
in this code, on choosing duplicate how the logic is filtered
- Assistant
The filtering logic for "Duplicate Rules" view in your code happens mainly inside the
handleFilterApiClickfunction and then how you render based on the current filter state (ruleViewFilter).
Here is the part explaining how duplicates are filtered and shown:
const handleFilterApiClick = () => { if (activeTab === "ticketcreate") { const grouped = groupDuplicates(ticketCreationRules); const duplicateGroups = grouped .filter((group) => group.length > 1) // <-- Only groups with more than 1 rule considered duplicates .sort((a, b) => b.length - a.length); console.log("Grouped Ticket Creation Rules (duplicates only):", duplicateGroups); setTicketCreationRuleGroups(duplicateGroups); // save groups of duplicates to state setCurrentPage((prev) => ({ ...prev, ticketcreate: 1 })); // reset page to 1 for this tab toast.current.trigger({ type: "success", content: `Grouped Ticket Creation Rules into ${duplicateGroups.length} duplicate groups.`, }); } // similar logic for "ticketupdate" and "hourly" tabs ... };groupDuplicatesis the helper function that groups rules by their signature (the combination of their conditions and actions serialized).- After grouping, only groups with more than one item (
group.length > 1) are considered duplicates and saved in state (setTicketCreationRuleGroupsetc). - Then, the UI renders from those duplicate groups instead of the full list.
Render logic that switches between All Rules and Duplicate Rules:
const renderRulesOrGroups = () => { let groups = []; let flatRules = []; if (activeTab === "ticketcreate") { groups = ticketCreationRuleGroups; flatRules = ticketCreationRules; } else if (activeTab === "ticketupdate") { groups = ticketUpdateRuleGroups; flatRules = ticketUpdateRules; } else if (activeTab === "hourly") { groups = hourlyRuleGroups; flatRules = hourlyTriggerRules; } if (loading) { return <FwSpinner ... />; } if (ruleViewFilter.value === "duplicate_rules" && groups.length > 0) { // Flatten groups and paginate on the flat filtered list const flattenedFiltered = getFilteredRules(flattenGroups(groups)); const paginatedRules = pagination(flattenedFiltered, currentPage[activeTab]); const paginatedRuleIds = new Set(paginatedRules.map((r) => r.id)); return ( <div> {groups.map((group, idx) => { const rulesToShow = group.filter((rule) => paginatedRuleIds.has(rule.id) ); if (rulesToShow.length === 0) return null; return ( <div key={`group-${idx}`}> {rulesToShow.map((rule, i) => ( <AutomationCard ... /> ))} </div> ); })} </div> ); } else { // Normal full flattened rules with filtering & pagination const filteredFlatRules = getFilteredRules(flatRules); const paginatedFlatRules = pagination(filteredFlatRules, currentPage[activeTab]); if (paginatedFlatRules.length === 0) { return <p>No Duplicate Rules Found.</p>; } return paginatedFlatRules.map((rule, idx) => <AutomationCard ... />); } };- When
"duplicate_rules"is selected, you grab the duplicate groups (groups) instead of the full rules list. - You flatten all groups (
flattenGroups(groups)), then apply your search filtering (getFilteredRules) and pagination (pagination). - Then you map over the filtered and paginated rules, but group them visually using the original groups array, showing only the rules that exist in the current page.
- If the filter is NOT
"duplicate_rules", you just use the full flat list of rules with search and pagination as normal.
Summary
- When user chooses the Duplicate Rules view (
ruleViewFilter.value === "duplicate_rules"):handleFilterApiClickgroups the current tab's rules by a signature of their conditions/actions.- Only sets groups that have duplicates (
length > 1). - Then the UI uses those groups to render duplicates only.
- Search and pagination operate on the flattened duplicate groups.
- When user chooses All Rules view, it simply uses the full list of rules without grouping.
If you want me, I can extract or highlight only the key modified or added parts regarding duplicates. Just let me know!
- User
in this, on rendering after this it should be based on duplicates group ie. 5 set of duplicate groups per pagination
scenario 1 : if 1st group has 28 and another set has 4 (and it exceeds per pagination 30), that set should be moved to another page. scenario 2 : if 1st group has 35 (which already exceeds per pagination 30), that whole 35 should be in one pagination other set should be moved to next pagination
- Assistant
Got it! You want the pagination to work on groups of duplicates as a whole, not individual rules within groups. Pagination should page the duplicate groups themselves (not flattened rules), and each group should either fit entirely on one page or be alone on a page if it exceeds the page size.
Current behavior:
- You paginate after flattening all duplicates from all groups — so large groups and small groups are mixed within pages, breaking groups across pages.
- You want instead:
- Each duplicate group counts as a "pagination item".
- Page size is counted in groups, with special handling if a single group exceeds the page size by itself (then it occupies a whole page alone).
- You show all the rules in that group's card(s) on that page.
What you need is:
- Paginate the array of groups based on count of groups (not count of rules inside).
- On a page, show all rules inside each group.
- If one group has more rules than the page size, put that one group alone in a page.
- Pagination "per-page" counts groups, not rules.
Here's what to modify in your code:
1. Change your pagination usage — paginate on groups array, not flattened rules
2. Adjust rendering logic to display whole groups for that page
Modified render logic for
renderRulesOrGroups:const renderRulesOrGroups = () => { let groups = []; let flatRules = []; if (activeTab === "ticketcreate") { groups = ticketCreationRuleGroups; flatRules = ticketCreationRules; } else if (activeTab === "ticketupdate") { groups = ticketUpdateRuleGroups; flatRules = ticketUpdateRules; } else if (activeTab === "hourly") { groups = hourlyRuleGroups; flatRules = hourlyTriggerRules; } if (loading) { return ( <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "200px" }}> <FwSpinner size="medium" color="green" /> </div> ); } if (ruleViewFilter.value === "duplicate_rules" && groups.length > 0) { // Pagination applied on groups array, not flattened rules // Special chunking of groups based on rules count per group to accommodate large groups as whole pages const paginatedGroups = []; let currentPageGroups = []; let currentGroupCount = 0; for (let group of groups) { const groupSize = group.length; // If one group exceeds rulesPerPage, put it alone on a page if (groupSize > rulesPerPage) { // Push current buffer page if not empty if (currentGroupCount > 0) { paginatedGroups.push(currentPageGroups); currentPageGroups = []; currentGroupCount = 0; } // Then push this single large group as its own page paginatedGroups.push([group]); } else { // Add group to current page if it fits in rulesPerPage if (currentGroupCount + groupSize <= rulesPerPage) { currentPageGroups.push(group); currentGroupCount += groupSize; } else { // Current group doesn't fit, push current groups as page and start new one if (currentGroupCount > 0) { paginatedGroups.push(currentPageGroups); } currentPageGroups = [group]; currentGroupCount = groupSize; } } } // Push leftover if (currentGroupCount > 0) { paginatedGroups.push(currentPageGroups); } // Now get current page groups const pageIndex = currentPage[activeTab] - 1; const groupsToShow = paginatedGroups[pageIndex] || []; // Flatten the groups on the page for filtering & deletion logic const flattenedRulesOnPage = flattenGroups(groupsToShow); const filteredRulesOnPage = getFilteredRules(flattenedRulesOnPage); return ( <div style={{ marginLeft: 10, marginRight: "auto" }}> {groupsToShow.map((group, idx) => { // Filter group's rules based on search query const rulesToShow = group.filter(rule => filteredRulesOnPage.some(filteredRule => filteredRule.id === rule.id) ); if (rulesToShow.length === 0) return null; return ( <div key={`group-${pageIndex}-${idx}`} style={{ marginBottom: "12px" }}> {rulesToShow.map((rule, i) => ( <div key={rule.id} className="fw-card-1" style={{ marginBottom: "10px", marginTop: i === 0 ? "10px" : "2px", padding: "5px 8px", marginLeft: "20px", borderRadius: "4px", }} > <AutomationCard rule={rule} index={i + 1} isFirstInGroup={i === 0} onDelete={() => deleteRule(rule, flattenedRulesOnPage)} activeTab={activeTab} onSelect={openRuleDetails} agent={agent} /> </div> ))} </div> ); })} </div> ); } else { // ALL rules view: no change needed, paginate flattened filtered rules const filteredFlatRules = getFilteredRules(flatRules); const paginatedFlatRules = pagination(filteredFlatRules, currentPage[activeTab]); if (paginatedFlatRules.length === 0) { return ( <p style={{ textAlign: "center", marginTop: "20px" }}> No Rules Found. </p> ); } return paginatedFlatRules.map((rule, idx) => ( <div key={rule.id || idx} className="fw-card-1" style={{ marginBottom: "5px", marginTop: "10px", padding: "5px 8px", marginLeft: 10, marginRight: "auto", }} > <AutomationCard rule={rule} index={idx + 1} isFirstInGroup={true} onDelete={() => deleteRule(rule, filteredFlatRules)} activeTab={activeTab} onSelect={openRuleDetails} agent={agent} /> </div> )); } };
3. Also adjust your pagination component to use the correct total pages count (based on groups chunks count when duplicate rules view)
Add a helper:
const getTotalPages = () => { if (ruleViewFilter.value === "duplicate_rules") { // Calculate number of pages based on chunked groups like above const groups = activeTab === "ticketcreate" ? ticketCreationRuleGroups : activeTab === "ticketupdate" ? ticketUpdateRuleGroups : hourlyRuleGroups; if (!groups || groups.length === 0) return 0; let paginatedGroups = []; let currentPageGroups = []; let currentGroupCount = 0; for (let group of groups) { const groupSize = group.length; if (groupSize > rulesPerPage) { if (currentGroupCount > 0) { paginatedGroups.push(currentPageGroups); currentPageGroups = []; currentGroupCount = 0; } paginatedGroups.push([group]); } else { if (currentGroupCount + groupSize <= rulesPerPage) { currentPageGroups.push(group); currentGroupCount += groupSize; } else { if (currentGroupCount > 0) { paginatedGroups.push(currentPageGroups); } currentPageGroups = [group]; currentGroupCount = groupSize; } } } if (currentGroupCount > 0) { paginatedGroups.push(currentPageGroups); } return paginatedGroups.length; } else { // Use your existing getCurrentTotalCount logic const count = getCurrentTotalCount(); return Math.ceil(count / rulesPerPage); } };Then in your pagination component inside each tab panel, set
total={getTotalPages()}andper-page={1}, since now one page means one set of groups (which can hold multiple rules).
4. Summary of changes needed:
- Pagination is applied to groups instead of flat rules.
- Create chunks of groups according to rules count so that groups fit pages as per your scenario.
- Render all rules inside each group on the page.
- Pagination controls reflect the count of group chunks/pages.
- For “All Rules” mode keep current pagination.
If you want me, I can prepare a full minimal diff/patched version of relevant portions for you. Would you like that?
- User
yes
- Assistant
Below is the full updated code diff for the key changes you need to implement the pagination based on duplicate groups (handling groups as pagination units, including oversize groups).
1. Replace the
renderRulesOrGroupsfunction with this updated version:const renderRulesOrGroups = () => { let groups = []; let flatRules = []; if (activeTab === "ticketcreate") { groups = ticketCreationRuleGroups; flatRules = ticketCreationRules; } else if (activeTab === "ticketupdate") { groups = ticketUpdateRuleGroups; flatRules = ticketUpdateRules; } else if (activeTab === "hourly") { groups = hourlyRuleGroups; flatRules = hourlyTriggerRules; } if (loading) { return ( <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "200px" }}> <FwSpinner size="medium" color="green" /> </div> ); } if (ruleViewFilter.value === "duplicate_rules" && groups.length > 0) { // Create paginated group chunks according to rulesPerPage and group sizes const paginatedGroups = []; let currentPageGroups = []; let currentGroupCount = 0; for (const group of groups) { const groupSize = group.length; if (groupSize > rulesPerPage) { // Large group alone on page if (currentGroupCount > 0) { paginatedGroups.push(currentPageGroups); currentPageGroups = []; currentGroupCount = 0; } paginatedGroups.push([group]); } else { // Fit group in current page or start new page if (currentGroupCount + groupSize <= rulesPerPage) { currentPageGroups.push(group); currentGroupCount += groupSize; } else { if (currentGroupCount > 0) { paginatedGroups.push(currentPageGroups); } currentPageGroups = [group]; currentGroupCount = groupSize; } } } if (currentGroupCount > 0) { paginatedGroups.push(currentPageGroups); } const pageIndex = currentPage[activeTab] - 1; const groupsToShow = paginatedGroups[pageIndex] || []; // Flatten rules shown on this page for filtering and delete operations const flattenedRulesOnPage = flattenGroups(groupsToShow); const filteredRulesOnPage = getFilteredRules(flattenedRulesOnPage); return ( <div style={{ marginLeft: 10, marginRight: "auto" }}> {groupsToShow.map((group, idx) => { const rulesToShow = group.filter(rule => filteredRulesOnPage.some(filteredRule => filteredRule.id === rule.id) ); if (rulesToShow.length === 0) return null; return ( <div key={`group-${pageIndex}-${idx}`} style={{ marginBottom: "12px" }}> {rulesToShow.map((rule, i) => ( <div key={rule.id} className="fw-card-1" style={{ marginBottom: "10px", marginTop: i === 0 ? "10px" : "2px", padding: "5px 8px", marginLeft: "20px", borderRadius: "4px", }} > <AutomationCard rule={rule} index={i + 1} isFirstInGroup={i === 0} onDelete={() => deleteRule(rule, flattenedRulesOnPage)} activeTab={activeTab} onSelect={openRuleDetails} agent={agent} /> </div> ))} </div> ); })} </div> ); } else { // All rules view paginated by rules as before const filteredFlatRules = getFilteredRules(flatRules); const paginatedFlatRules = pagination(filteredFlatRules, currentPage[activeTab]); if (paginatedFlatRules.length === 0) { return ( <p style={{ textAlign: "center", marginTop: "20px" }}> No Rules Found. </p> ); } return paginatedFlatRules.map((rule, idx) => ( <div key={rule.id || idx} className="fw-card-1" style={{ marginBottom: "5px", marginTop: "10px", padding: "5px 8px", marginLeft: 10, marginRight: "auto", }} > <AutomationCard rule={rule} index={idx + 1} isFirstInGroup={true} onDelete={() => deleteRule(rule, filteredFlatRules)} activeTab={activeTab} onSelect={openRuleDetails} agent={agent} /> </div> )); } };
2. Add a new helper function to calculate total pages for the pagination on groups or flat rules:
const getTotalPages = () => { if (ruleViewFilter.value === "duplicate_rules") { const groups = activeTab === "ticketcreate" ? ticketCreationRuleGroups : activeTab === "ticketupdate" ? ticketUpdateRuleGroups : hourlyRuleGroups; if (!groups || groups.length === 0) return 0; const paginatedGroups = []; let currentPageGroups = []; let currentGroupCount = 0; for (const group of groups) { const groupSize = group.length; if (groupSize > rulesPerPage) { if (currentGroupCount > 0) { paginatedGroups.push(currentPageGroups); currentPageGroups = []; currentGroupCount = 0; } paginatedGroups.push([group]); } else { if (currentGroupCount + groupSize <= rulesPerPage) { currentPageGroups.push(group); currentGroupCount += groupSize; } else { if (currentGroupCount > 0) { paginatedGroups.push(currentPageGroups); } currentPageGroups = [group]; currentGroupCount = groupSize; } } } if (currentGroupCount > 0) paginatedGroups.push(currentPageGroups); return paginatedGroups.length; } else { const count = getCurrentTotalCount(); return Math.ceil(count / rulesPerPage); } };
3. Update your pagination components inside each
<FwTabPanel>to use the newgetTotalPages()and setper-page={1}(since each page is one or more groups):Example for Ticket Create TabPanel pagination:
<FwPagination per-page={1} // one group-page per pagination page total={getTotalPages()} page={currentPage.ticketcreate} onFwChange={handlePageChange("ticketcreate")} />Similarly, update for the other two tabs:
- Ticket Updates:
page={currentPage.ticketupdate},onFwChange={handlePageChange("ticketupdate")} - Hourly:
page={currentPage.hourly},onFwChange={handlePageChange("hourly")}
4. Optional: For UX clarity, consider disabling pagination if total pages = 0 or 1.
Summary:
- Pagination now chunks duplicate groups, each chunk contains groups whose total rules ≤
rulesPerPage. - Oversized group (>
rulesPerPage) placed alone on page. - Renders all rules inside group(s) of current page.
- Pagination counts "pages" as group chunks.
- Others unchanged (search/filter, all rules view).
If you want, I can also help you with the diff or full updated component code including these changes. Just ask!
- Ticket Updates: