does in this code does have any pagination limit of max… · The Chat Archive
Explore / Programming does in this code does have any pagination limit of max. import React, { useState,… Save Share Download ▾ ReportJump to turn (10) 1 does in this code does have any pagination limit of max. import React, { useStat 2 in my given code, when i click x which is in search why it is not removing and r 3 please check in this code and give me the final code., import React, { useState, 4 it clears but not resets the search it says as in searched filtere 5 no when i click x it clears the word but not reseting the searchterm and searchq 6 yes give me complete minimal code snippet of what fixed 7 no it still stays as it is only searhterm from search input is removed not reset 8 yes 9 give me separate 10 not working at all. Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 10 (20 messages)
Language en
Conversation date May 10, 2025
Added to archive Nov 16, 2026
ID 01m7h42saynad355nrq39tbsqvSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: f4a27ad177a67ec466c4fb364ccf7d16
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
does in this code does have any pagination limit of max.
import React, { useState, useEffect, useRef } from "react";
import {
FwTabs,
FwTab,
FwTabPanel,
FwSpinner,
ToastController,
FwToast,
FwPagination,
FwModalTitle,
FwModalContent,
FwToggle,
FwButton,
FwIcon,
FwListOptions,
FwPopover,
FwModal,
} from "@freshworks/crayons/react";
// import SummaryContent from "./SummaryContent";
import {
getTicketCreationRules,
getTicketUpdationRules,
getHourlyRules,
getAgents,
pagination,
} from "../common";
// Utility: clean and normalize text
const cleanText = (text) =>
String(text || "")
.toLowerCase()
.replace(/<img[^>]>/gi, "") // remove tags
.replace(/ /gi, " ") // replace non-breaking space
.replace(/<[^>] >/g, "") // remove any other HTML tags
.replace(/[,.]/g, "") // remove commas and periods
.replace(/([a-zA-Z])(\d)/g, "1 1 1 2") // split letters & digits
.replace(/(\d)([a-zA-Z])/g, "1 1 1 2")
.replace(/\s+/g, " ") // collapse spaces
.trim()
.replace(/\bcomma\b\s*\bfull\s*stop\b/g, "comma fullstop");
// Normalize the condition parts similarly to original code logic
const normalizeConditionParts = (rawConditions) => {
let parts = [];
if (typeof rawConditions === "string") {
parts = rawConditions.split(",");
} else if (Array.isArray(rawConditions)) {
parts = rawConditions;
} else {
// if conditions is null, undefined, object etc.
parts = [];
}
const set1 = [];
const set2 = [];
let currentSet = null;
for (let part of parts) {
const cleaned = cleanText(part);
if (cleaned === "condition set 1") {
currentSet = set1;
continue;
}
if (cleaned === "condition set 2") {
currentSet = set2;
continue;
}
if (currentSet) currentSet.push(cleaned);
}
set1.sort();
set2.sort();
return { set1, set2 };
};
// Normalize actions (handle string or array)
const normalizeActions = (actions) => {
if (Array.isArray(actions)) {
return actions
.map((action) =>
Object.values(action)
.map((v) => cleanText(v))
.join(" ")
)
.sort()
.join(",");
} else if (typeof actions === "string") {
return actions
.split(",")
.map((a) => cleanText(a))
.sort()
.join(",");
}
return "";
};
// Main normalized signature function combining conditions, actions, and operator
const getRuleSignatureNormalized = (rule) => {
const rawConditions = rule.summary?.conditions || rule.conditions || "";
const rawActions = rule.summary?.actions || rule.actions || "";
const operator = rule.operator || "";
const { set1, set2 } = normalizeConditionParts(rawConditions);
const normalizedActions = normalizeActions(rawActions);
const normalizedOperator = cleanText(operator);
// The signature should consider the fact conditions might be interchangeable
// between set1 and set2 (commutative)
const key1 = JSON.stringify({ set1, set2, actions: normalizedActions, operator: normalizedOperator });
const key2 = JSON.stringify({ set1: set2, set2: set1, actions: normalizedActions, operator: normalizedOperator });
// Return lexicographically smallest key for commutative sets
return key1 < key2 ? key1 : key2;
};
// Group duplicates by normalized signature
const groupDuplicates = (rules) => {
const groups = {};
rules
.filter((rule) => rule.active === "true" || rule.active === true) // handle boolean or string "true"
.forEach((rule) => {
const signature = getRuleSignatureNormalized(rule);
if (!groups[signature]) groups[signature] = [];
groups[signature].push(rule);
});
return Object.values(groups);
};
// export { groupDuplicates, getRuleSignatureNormalized };
// 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 [];
// }
// };
// ===== AutomationCard Component Inlined =====
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 };
code Copy code
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);
// Sort by `position` ascending before returning
allRecords.sort((a, b) => {
// If position undefined/missing, treat as larger - push to bottom
const posA = typeof a.position === "number" ? a.position : Number.MAX_SAFE_INTEGER;
const posB = typeof b.position === "number" ? b.position : Number.MAX_SAFE_INTEGER;
return posA - posB;
});
console.log(`✅ Filtered Records for Type ${automationTypeId}:`, allRecords);
return allRecords;
} catch (error) {
console.error("❌ Error fetching filtered records:", error);
return [];
}
};
const calculateLastModified = (updated_at) => {
const updatedDate = new Date(updated_at);
const currentDate = new Date();
const diffInMilliseconds = currentDate - updatedDate;
const seconds = Math.floor(diffInMilliseconds / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const months = Math.floor(days / 30);
const years = Math.floor(days / 365);
if (years > 0) return years === 1 ? "a year ago" : ${years} years ago;
if (months > 0) return months === 1 ? "a month ago" : ${months} months ago;
if (days > 0) return ${days} day${days > 1 ? "s" : ""} ago;
if (hours > 0) return ${hours} hour${hours > 1 ? "s" : ""} ago;
if (minutes > 0) return ${minutes} minute${minutes > 1 ? "s" : ""} ago;
return "Just now";
};
const AutomationCard = ({
rule = {},
index,
isFirstInGroup = false,
onDelete,
agent,
activeTab,
onSelect,
}) => {
const {
id,
name = "Default Rule Name",
summary = "",
description = "",
updated_at = "N/A",
last_updated_by = "Unknown",
affected_tickets_count = "--",
active = false,
position,
automation_type_id,
} = rule;
const [menuOpen, setMenuOpen] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const modalRef = useRef(null);
const menuContainerRef = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (
menuContainerRef.current &&
!menuContainerRef.current.contains(event.target)
) {
setMenuOpen(false);
}
};
code Copy code
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
// Imperatively open modal if showDeleteModal became true
useEffect(() => {
if (showDeleteModal && modalRef.current) {
modalRef.current.open();
}
}, [showDeleteModal]);
const openModal = () => setShowDeleteModal(true);
const closeModal = () => {
setShowDeleteModal(false);
if (modalRef.current) modalRef.current.close();
};
const handleConfirmDelete = () => {
closeModal();
if (onDelete) onDelete(rule);
};
const handleClick = () => {
if (onSelect) {
onSelect(rule);
}
};
const renderAgentName = () => {
if (rule.agentName) {
return rule.agentName;
}
if (!agent || !Array.isArray(agent)) {
return last_updated_by || "Unknown";
} else {
const foundAgent = agent.find((e) => e.value === last_updated_by);
return foundAgent ? foundAgent.text : last_updated_by || "Unknown";
}
};
function extractText(htmlString) {
if (!htmlString || typeof htmlString !== "string") return "";
let text = htmlString.replace(/<[^>]+>/g, "").trim();
if (text.toLowerCase().startsWith("if ")) {
text = text.substring(3).trim();
}
return text.toLowerCase();
}
function generateSummary(summary) {
if (!summary) return "";
if (typeof summary === "string") {
return summary;
}
let conditionTexts = [];
if (summary.conditions) {
for (const setKey in summary.conditions) {
if (Object.prototype.hasOwnProperty.call(summary.conditions, setKey)) {
const conditionsVal = summary.conditions[setKey];
const conditionsArray = Array.isArray(conditionsVal)
? conditionsVal
: [conditionsVal];
const cleanConditions = conditionsArray.map(extractText);
conditionTexts.push(cleanConditions.join(", "));
}
}
}
const conditionsStr = conditionTexts.join(", ");
let actionsStr = "";
if (summary.actions && Array.isArray(summary.actions)) {
const cleanActions = summary.actions.map(extractText);
actionsStr = cleanActions.join(", ");
}
if (conditionsStr && actionsStr) {
return if ${conditionsStr}, then ${actionsStr};
} else if (conditionsStr) {
return if ${conditionsStr};
} else if (actionsStr) {
return actionsStr;
}
return "";
}
function MenuList({ visible, onEdit, onClone, rule }) {
return (
<ul
style={{
position: "absolute",
backgroundColor: "white",
boxShadow: "0 8px 24px rgba(0, 0, 0, 0.15)",
borderRadius: 6,
padding: "8px 0",
minWidth: 160,
right: 0,
top: 28,
listStyle: "none",
zIndex: 9999,
margin: 0,
opacity: visible ? 1 : 0,
transform: visible
? "translateY(0px) scale(1)"
: "translateY(-10px) scale(0.98)",
transition: "opacity 300ms ease, transform 300ms ease",
pointerEvents: visible ? "auto" : "none",
willChange: "opacity, transform",
}}
>
{[
{ name: "edit", label: "Edit", onClick: onEdit },
{ name: "clone", label: "Clone", onClick: onClone },
{
name: "delete",
label: "Delete",
onClick: () => {
console.log("Delete icon clicked for rule id:", rule.id);
setMenuOpen(false);
openModal();
},
},
].map(({ name, label, onClick }) => (
<li
key={name}
style={{
display: "flex",
alignItems: "center",
gap: 8,
padding: "8px 16px",
cursor: "pointer",
color: "#333",
fontWeight: 500,
userSelect: "none",
backgroundColor: "transparent",
transition: "background-color 0.2s",
}}
onClick={(e) => {
e.stopPropagation();
onClick?.();
setMenuOpen(false);
}}
onMouseEnter={(e) =>
(e.currentTarget.style.backgroundColor = "#f5f7f9")
}
onMouseLeave={(e) =>
(e.currentTarget.style.backgroundColor = "transparent")
}
>
{label}
))}
);
}
return (
<>
<div
className="fw-card-1 fw-flex fw-flex-column"
style={{
overflow: "visible",
border: "0.5px solid #ddd",
backgroundColor: isFirstInGroup ? "#fff" : "#e5f2fd",
cursor: "pointer",
}}
onClick={handleClick}
>
<section
className="fw-flex-grow fw-px-16 fw-flex fw-flex-row"
style={{
justifyContent: "space-between",
alignItems: "center",
marginBottom: "40px",
}}
>
<div
style={{
paddingLeft: "16px",
maxWidth: "80%",
flexBasis: "80%",
flexShrink: 0,
whiteSpace: "normal",
}}
>
{position}. {name}
<p
className="fw-type-xs fw-mt-0 fw-mb-20"
style={{ marginBottom: "10px", fontSize: "14px" }}
>
{generateSummary(rule.summary)}
code Copy code
<div
style={{
display: "flex",
alignItems: "center",
gap: "8px",
padding: "8px 16px",
flexBasis: "20%",
flexShrink: 0,
marginTop: "-50px",
justifyContent: "flex-end",
position: "relative",
}}
>
<FwToggle size="medium" checked={active} />
<div ref={menuContainerRef} style={{ position: "relative" }}>
<div
role="button"
tabIndex={0}
onClick={(e) => {
e.stopPropagation();
setMenuOpen(!menuOpen);
}}
style={{
zIndex: 1,
background: "none",
border: "none",
cursor: "pointer",
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
className="app-icon dropdown-toggle"
>
<path
fillRule="evenodd"
d="M12 5c-1.38 0-2.5-1.12-2.5-2.5S10.62 0 12 0s2.5 1.12 2.5 2.5S13.38 5 12 5zM12 14c-1.38 0-2.5-1.12-2.5-2.5S10.62 9 12 9s2.5 1.12 2.5 2.5S13.38 14 12 14zM12 24c-1.38 0-2.5-1.12-2.5-2.5S10.62 19 12 19s2.5 1.12 2.5 2.5S13.38 24 12 24z"
/>
</svg>
</div>
<MenuList
visible={menuOpen}
onEdit={() => alert("Edit clicked")}
onClone={() => alert("Clone clicked")}
rule={rule}
/>
</div>
</div>
</section>
<section
className="fw-type-xs fw-flex fw-flex-row fw-items-center options"
style={{
background: "#f5f7f9",
padding: "10px 16px",
borderRadius: "5px",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-evenly",
width: "100%",
fontSize: "14px",
color: "#666",
textAlign: "center",
}}
>
<span>
Last Modified: <strong>{calculateLastModified(updated_at)}</strong>
</span>
<span>|</span>
<span>By: {renderAgentName()}</span>
<span>|</span>
<span>Impacted tickets (Last 7 days): {affected_tickets_count}</span>
</div>
</section>
</div>
{/* Delete Confirmation Modal */}
<FwModal
id={`delete-modal-${id}`}
ref={modalRef}
size="small"
submit-color="danger"
submit-text="Delete"
onFwSubmit={(e) => {
e.preventDefault?.();
handleConfirmDelete();
}}
onFwClose={() => {
setShowDeleteModal(false);
if (modalRef.current) modalRef.current.close();
}}
>
<FwModalTitle>
<span>Delete message</span>
</FwModalTitle>
<FwModalContent>
<span>Are you sure you want to delete this Message?</span>
</FwModalContent>
</FwModal>
</>
);
};
// ===== AutomationTabs Component =====
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 [errorMessage, setErrorMessage] = useState(null);
const [activeTab, setActiveTab] = useState("ticketcreate");
const [inputState, setInputState] = useState("normal"); // <-- added
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 warningTimerRef = useRef(null); // <-- added
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(() => {
if (!loading) {
const timer = setTimeout(() => {
setShowPagination(true);
}, 200);
return () => clearTimeout(timer);
} else {
setShowPagination(false);
}
}, [loading, 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");
code Copy code
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,
}));
code Copy code
if (ruleViewFilter.value === "duplicate_rules") {
setRuleViewFilter(ruleViewOptions[0]); // Reset to 'All Rules' on tab switch
}
}, [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]);
useEffect(() => {
const fetchOnTabOrModeChange = async () => {
setLoading(true);
setErrorMessage(null); // clear previous errors
try {
let error = null;
if (fetchFromApi) {
if (activeTab === "ticketcreate") {
error = await getTicketCreationRules(client, setTicketCreationRules);
} else if (activeTab === "ticketupdate") {
error = await getTicketUpdationRules(client, setTicketUpdateRules);
} else if (activeTab === "hourly") {
error = await getHourlyRules(client, setHourlyTriggerRules);
}
await getAgents(client, setAgent); // this can also set errors if you want
} else {
if (!newRulePloadDB5.current) {
console.error("❌ Entity DB reference not initialized.");
setLoading(false);
return;
}
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);
}
}
code Copy code
if (error) {
setErrorMessage(error);
}
} catch (err) {
console.error("Error fetching data:", err);
setErrorMessage("An unexpected error occurred while fetching data.");
}
setLoading(false);
};
if (tabsInitialized && isRulesDBReady) {
fetchOnTabOrModeChange();
}
}, [activeTab, fetchFromApi, client, tabsInitialized, isRulesDBReady]);
const handlePageChange = (tab) => (event) => {
setCurrentPage((prev) => ({
...prev,
[tab]: event.detail.page,
}));
};
useEffect(() => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}, [activeTab]);
useEffect(() => {
const fwTabs = document.querySelector("fw-tabs");
code Copy code
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]);
// const fetchData = async () => {
// if (!fetchFromApi) {
// setSearchTerm("");
// setSearchQuery("");
// setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
// }
// setFetchFromApi((prev) => !prev);
// toast.current.trigger({
// type: "info",
// content: ${fetchFromApi ? "Going Back" : "Fetching Recent Data"}...,
// });
// };
const fetchData = async () => {
code Copy code
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setFetchFromApi((prev) => !prev);
// Toast content depends on current mode before toggling
toast.current.trigger({
type: "info",
content: `${fetchFromApi ? "Going Back" : "Fetching Recent Data"}...`,
});
};
const checkAndSetButtonState = async () => {
try {
const storedvalue1 = await client.db.get("RulesDB");
const isButtonEnabled = !!storedvalue1.stored;
if (isButtonEnabled) {
setIsRulesDBReady(true);
setLoadingBannerVisible(false);
code Copy code
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;
code Copy code
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 inputRef = useRef(null);
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 }));
code Copy code
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="Type Keyword to Search"
placeholder="Enter a Keyword to Search..."
warning-text="Please Enter a Keyword to Search..."
state={inputState}
clear-input
style={{
width: "400px",
height: "60px",
fontSize: "18px",
}}
value={searchTerm}
onInput={(e) => {
const val = e.target.value;
if (val.length < searchTerm.length) {
setSearchQuery(""); // Clear filter to show all rules
}
setSearchTerm(val);
if (showSearchHint) setShowSearchHint(false);
if (inputState !== "normal") setInputState("normal");
code Copy code
// Clear warning timeout if user starts typing
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setShowSearchHint(false);
setInputState("warning");
// Show warning for 3 seconds
warningTimerRef.current = setTimeout(() => {
setInputState("normal");
warningTimerRef.current = null;
}, 3000);
} else {
setSearchQuery(trimmed);
setShowSearchHint(false);
setInputState("normal");
}
}
}}
onFwClear={() => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
/>
code Copy code
<div style={{ flexShrink: 0 }}>
<FwButton color="primary" onFwClick={() => { /* Add your handler here */ }}>
<fw-icon name="plus" size="16" style={{ marginRight: "8px" }}></fw-icon>
Add New Rule
</FwButton>
</div>
</div>
);
const getTotalPages = () => {
if (ruleViewFilter.value === "duplicate_rules") {
const groups =
activeTab === "ticketcreate"
? ticketCreationRuleGroups
: activeTab === "ticketupdate"
? ticketUpdateRuleGroups
: hourlyRuleGroups;
code Copy code
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);
}
};
const renderRulesOrGroups = () => {
let groups = [];
let flatRules = [];
};
const deleteRule = async (rule, allRulesList) => {
console.log("deleteRule called with rule:", rule);
code Copy code
const { id } = rule;
const matchedRecord = allRulesList.find((rec) => rec.id === id);
let automationTypeId;
let currentRules, setRulesFunc, groupSetterFunc, currentTabPage, tabKey;
switch (activeTab) {
case "ticketcreate":
automationTypeId = ticketCreate;
currentRules = ticketCreationRules;
setRulesFunc = setTicketCreationRules;
groupSetterFunc = setTicketCreationRuleGroups;
currentTabPage = currentPage.ticketcreate;
tabKey = "ticketcreate";
break;
case "ticketupdate":
automationTypeId = ticketUpdate;
currentRules = ticketUpdateRules;
setRulesFunc = setTicketUpdateRules;
groupSetterFunc = setTicketUpdateRuleGroups;
currentTabPage = currentPage.ticketupdate;
tabKey = "ticketupdate";
break;
case "hourly":
automationTypeId = hourlyTriggers;
currentRules = hourlyTriggerRules;
setRulesFunc = setHourlyTriggerRules;
groupSetterFunc = setHourlyRuleGroups;
currentTabPage = currentPage.hourly;
tabKey = "hourly";
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) {
// Update rules state after deletion
const updatedRules = currentRules.filter((r) => r.id !== id);
setRulesFunc(updatedRules);
// Clear duplicates group cache if any
groupSetterFunc([]);
// Pagination check: get filtered rules based on current searchQuery & ruleViewFilter
// Here using your getFilteredRules function to apply search filtering
let filteredRules = getFilteredRules(updatedRules);
// Calculate items on current page after deletion
const paginatedItems = pagination(
filteredRules,
currentTabPage
);
// If current page is now empty and not already on first page, go back one page
if (paginatedItems.length === 0 && currentTabPage > 1) {
setCurrentPage((prev) => ({
...prev,
[tabKey]: prev[tabKey] - 1,
}));
}
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);
code Copy code
const duplicateGroups = grouped
.filter((group) => group.length > 1)
.sort((a, b) => b.length - a.length);
console.log("Grouping duplicates for tab: ticketcreate");
console.log("All Ticket Creation Rules:", ticketCreationRules);
console.log("Grouped Rules:", grouped);
console.log("Duplicate Groups (length > 1):", duplicateGroups);
setTicketCreationRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketcreate: 1 }));
} 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("Grouping duplicates for tab: ticketupdate");
console.log("All Ticket Update Rules:", ticketUpdateRules);
console.log("Grouped Rules:", grouped);
console.log("Duplicate Groups (length > 1):", duplicateGroups);
setTicketUpdateRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketupdate: 1 }));
} 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("Grouping duplicates for tab: hourly");
console.log("All Hourly Trigger Rules:", hourlyTriggerRules);
console.log("Grouped Rules:", grouped);
console.log("Duplicate Groups (length > 1):", duplicateGroups);
setHourlyRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, hourly: 1 }));
}
};
const getPaginatedItemCount = () => {
let rules = [];
if (activeTab === "ticketcreate") rules = ticketCreationRules;
else if (activeTab === "ticketupdate") rules = ticketUpdateRules;
else if (activeTab === "hourly") rules = hourlyTriggerRules;
code Copy code
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
// {showSearchHint && (
// <p style={{ color: "red", marginTop: "4px", fontSize: "0.9em" }}>
// Please enter a search term before searching.
//
// )}
// {loadingBannerVisible && !isRulesDBReady && (
// <div
// style={{
// justifyContent: "center",
// alignItems: "center",
// height: "40px",
// width: "50%",
// margin: "0 auto",
// }}
// >
//
// <span style={{ marginLeft: "8px" }}>Waiting for rules to be ready...
//
// )}
// {tabsInitialized && (
// <div style={{ width: "60%", marginRight: "auto" }}>
// <div
// style={{
// display: "flex",
// justifyContent: fetchFromApi ? "flex-start" : "flex-end",
// marginBottom: 15,
// }}
// >
//
// {fetchFromApi ? (
// <>
// <FwIcon
// slot="before-label"
// name="arrow-left"
// size={16}
// style={{ marginRight: "8px" }}
// />
// Back
// </>
// ) : (
// <>
// Get Recent Data
// <FwIcon
// slot="after-label"
// name="refresh"
// size={16}
// style={{ marginLeft: "8px" }}
// />
// </>
// )}
//
//
//
// <FwTab slot="tab" panel="ticketcreate" onClick={() => setActiveTab("ticketcreate")}>
// Ticket Creation
//
// <FwTab slot="tab" panel="ticketupdate" onClick={() => setActiveTab("ticketupdate")}>
// Ticket Updates
//
// <FwTab slot="tab" panel="hourly" onClick={() => setActiveTab("hourly")}>
// Hourly Triggers
//
//
// {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")}
// />
//
//
// )}
//
//
// {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")}
// />
//
//
// )}
//
//
// {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")}
// />
//
//
// )}
//
//
//
// )}
//
// {/* Error message below the tabs container */}
// {errorMessage && (
// <div
// style={{
// width: "60%",
// marginRight: "auto",
// color: "red",
// marginTop: "8px",
// marginBottom: "10px",
// fontSize:"2rem",
// textAlign: "center",
// fontWeight: "bold",
// }}
// >
// {errorMessage}
//
// )}
// </>
// );
return (
<>
{errorMessage ? (
</>
);
};
export default AutomationTabs;
Show full message · 1,758 lines Assistant2025-05-10 05:11 UTC Copy response
Looking at the provided React component code, specifically the pagination logic and the data fetching parts, here is the analysis regarding pagination limits:
Does this code have any pagination limit / max?
Short answer:
Yes, it paginates rules with a fixed page size of 30 items per page, but there is no explicit max limit on how many pages can be navigated through — pagination happens over all available filtered data.
Supporting Details:
Pagination Page Size (rulesPerPage):
There is a constant defined near the top:
js Copy code
const rulesPerPage = 30;
This means that at most 30 rules are displayed per page.
Current Page State:
The currentPage state tracks the current page number per tab (ticketcreate, ticketupdate, hourly):
js Copy code
const [currentPage, setCurrentPage] = useState({
ticketcreate: 1,
ticketupdate: 1,
hourly: 1,
});
Pagination Calculation:
To calculate total pages, the code uses the total count divided by rulesPerPage and rounds up:
For example, in getCurrentTotalCount and getTotalPages functions:
js Copy code
return Math.ceil(count / rulesPerPage);
And count here refers to the total filtered rules count (taking duplicates and filters into account).
Pagination Component:
The pagination UI component (FwPagination) is used with the following props:
jsx Copy code
<FwPagination
per-page={rulesPerPage}
total={getCurrentTotalCount()}
page={currentPage.ticketcreate}
onFwChange={handlePageChange("ticketcreate")}
/>
This component receives the total number of records and page size and should handle displaying the correct set of pages accordingly.
Data Fetching for Pagination:
The fetched data (such as from Filterrecords()) accumulates records — it does multiple fetches internally paging through the backend via until all records are fetched:
in my given code, when i click x which is in search why it is not removing and reseting the search term so that all rules show.
Assistant2025-05-10 05:19 UTC Copy response
Good question! You said clicking "x" in the search input (the clear button) does not reset the search term and does not show all rules again.
Let's analyze the relevant code snippet you have for the search input, especially the onFwClear handler:
jsx Copy code
<fw-input
...
value={searchTerm}
...
onFwClear={() => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
/>
Why might clearing not reset the search and show all rules?
Potential reasons:
The fw-input clear button (onFwClear event) not firing / recognized?
fw-input is presumably a web component from the Freshworks Crayons UI. Verify that your version supports onFwClear event on the React wrapper or see if you need to attach event listener differently.
In React, for web components, you sometimes need to attach native event listeners with .addEventListener.
Check browser console to see if onFwClear is triggered when clicking "x".
State update is not causing refresh
Setting setSearchTerm("") and setSearchQuery("") clears the state. Your filtering is based on searchQuery (per getFilteredRules).
Do rules refresh immediately after state update? React state updates are async but should trigger re-render.
However, note the filtering logic depends on searchQuery. Maybe you also need to reset related pagination or filtered data to reflect search cleared.
The UI is caching filtered rules somewhere else
For example, in your code, filtered and paginated lists are computed on render, so clearing searchTerm and searchQuery should cause all rules to show via getFilteredRules.
Confirm the render logic re-runs when changes.
please check in this code and give me the final code.,
import React, { useState, useEffect, useRef } from "react";
import {
FwTabs,
FwTab,
FwTabPanel,
FwSpinner,
ToastController,
FwToast,
FwPagination,
FwModalTitle,
FwModalContent,
FwToggle,
FwButton,
FwIcon,
FwListOptions,
FwPopover,
FwModal,
} from "@freshworks/crayons/react";
// import SummaryContent from "./SummaryContent";
import {
getTicketCreationRules,
getTicketUpdationRules,
getHourlyRules,
getAgents,
pagination,
} from "../common";
// Utility: clean and normalize text
const cleanText = (text) =>
String(text || "")
.toLowerCase()
.replace(/<img[^>]>/gi, "") // remove tags
.replace(/ /gi, " ") // replace non-breaking space
.replace(/<[^>] >/g, "") // remove any other HTML tags
.replace(/[,.]/g, "") // remove commas and periods
.replace(/([a-zA-Z])(\d)/g, "1 1 1 2") // split letters & digits
.replace(/(\d)([a-zA-Z])/g, "1 1 1 2")
.replace(/\s+/g, " ") // collapse spaces
.trim()
.replace(/\bcomma\b\s*\bfull\s*stop\b/g, "comma fullstop");
// Normalize the condition parts similarly to original code logic
const normalizeConditionParts = (rawConditions) => {
let parts = [];
if (typeof rawConditions === "string") {
parts = rawConditions.split(",");
} else if (Array.isArray(rawConditions)) {
parts = rawConditions;
} else {
// if conditions is null, undefined, object etc.
parts = [];
}
const set1 = [];
const set2 = [];
let currentSet = null;
for (let part of parts) {
const cleaned = cleanText(part);
if (cleaned === "condition set 1") {
currentSet = set1;
continue;
}
if (cleaned === "condition set 2") {
currentSet = set2;
continue;
}
if (currentSet) currentSet.push(cleaned);
}
set1.sort();
set2.sort();
return { set1, set2 };
};
// Normalize actions (handle string or array)
const normalizeActions = (actions) => {
if (Array.isArray(actions)) {
return actions
.map((action) =>
Object.values(action)
.map((v) => cleanText(v))
.join(" ")
)
.sort()
.join(",");
} else if (typeof actions === "string") {
return actions
.split(",")
.map((a) => cleanText(a))
.sort()
.join(",");
}
return "";
};
Show full message · 1,610 lines Assistant2025-05-10 05:20 UTC Copy response
Certainly! The main issue with clearing the search input is likely that <fw-input> is a web component and React doesn’t automatically recognize its custom fwClear event as a React prop like onFwClear. To reliably capture the clear event, you need to add an event listener using a ref and addEventListener.
Here is the minimal patch to fix the search clear behavior in your existing code (leaving your original structure mostly unchanged):
What to do:
Remove the JSX onFwClear prop from <fw-input> .
Add a useEffect that attaches a native event listener on the web component ref for the fwClear event .
In that handler, clear your search state and page number as you intended.
Updated relevant code snippet inside AutomationTabs (replace the existing <fw-input> code and add the listener):
jsx Copy code
// Define ref for fw-input
const inputRef = useRef(null);
// Attach native fwClear event listener to fw-input web component
useEffect(() => {
const inputEl = inputRef.current;
if (!inputEl) return;
const onFwClear = () => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
};
inputEl.addEventListener("fwClear", onFwClear);
return () => {
inputEl.removeEventListener("fwClear", onFwClear);
};
}, [activeTab]); // re-bind on tab change to reset currentPage properly
Then your <fw-input> JSX becomes:
it clears but not resets the search it says as in searched filtere
Assistant2025-05-10 05:23 UTC Copy response
Thanks for the update! If clicking clear removes the visible text from the input (i.e., clears searchTerm), but the filtered rules still act as if a search is active (i.e., filtered list stays filtered, shows "No Rules Found" or filtered subset) , that indicates that although searchTerm was cleared, the searchQuery state is not being cleared or updated properly to reset filtering, or the filtering logic is not responding to the updates as expected .
Why does this happen?
Looking at your onInput and other handlers, you do:
onInput: updates searchTerm, and if characters are removed (val.length < searchTerm.length), you call setSearchQuery("") to clear filter.
You also clear searchTerm and searchQuery on clear (fwClear) event.
However, I suspect the issue is timing or key behavior between searchTerm and searchQuery:
searchTerm is controlled by input events.
searchQuery is your actual filter term applied in getFilteredRules.
You trigger filtering only on explicit Enter key press or clearing searchQuery.
But when clear happens , maybe the searchQuery isn't actually changing quickly enough or causing the UI to rerender.
Suggested proper fix:
Instead of maintaining two separate states (searchTerm and searchQuery), simplify by controlling just one state for the search string, and base filtering on that . Or, make sure searchQuery updates immediately whenever searchTerm is cleared.
How to fix in your code:
On clear (fwClear event), do:
js Copy code
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
On normal input change (onInput), update both searchTerm and searchQuery immediately:
no when i click x it clears the word but not reseting the searchterm and searchquery
fix that logic in this code.
import React, { useState, useEffect, useRef } from "react";
import {
FwTabs,
FwTab,
FwTabPanel,
FwSpinner,
ToastController,
FwToast,
FwPagination,
FwModalTitle,
FwModalContent,
FwToggle,
FwButton,
FwIcon,
FwListOptions,
FwPopover,
FwModal,
} from "@freshworks/crayons/react";
// import SummaryContent from "./SummaryContent";
import {
getTicketCreationRules,
getTicketUpdationRules,
getHourlyRules,
getAgents,
pagination,
} from "../common";
// Utility: clean and normalize text
const cleanText = (text) =>
String(text || "")
.toLowerCase()
.replace(/<img[^>]>/gi, "") // remove tags
.replace(/ /gi, " ") // replace non-breaking space
.replace(/<[^>] >/g, "") // remove any other HTML tags
.replace(/[,.]/g, "") // remove commas and periods
.replace(/([a-zA-Z])(\d)/g, "1 1 1 2") // split letters & digits
.replace(/(\d)([a-zA-Z])/g, "1 1 1 2")
.replace(/\s+/g, " ") // collapse spaces
.trim()
.replace(/\bcomma\b\s*\bfull\s*stop\b/g, "comma fullstop");
// Normalize the condition parts similarly to original code logic
const normalizeConditionParts = (rawConditions) => {
let parts = [];
if (typeof rawConditions === "string") {
parts = rawConditions.split(",");
} else if (Array.isArray(rawConditions)) {
parts = rawConditions;
} else {
// if conditions is null, undefined, object etc.
parts = [];
}
const set1 = [];
const set2 = [];
let currentSet = null;
for (let part of parts) {
const cleaned = cleanText(part);
if (cleaned === "condition set 1") {
currentSet = set1;
continue;
}
if (cleaned === "condition set 2") {
currentSet = set2;
continue;
}
if (currentSet) currentSet.push(cleaned);
}
set1.sort();
set2.sort();
return { set1, set2 };
};
// Normalize actions (handle string or array)
const normalizeActions = (actions) => {
if (Array.isArray(actions)) {
return actions
.map((action) =>
Object.values(action)
.map((v) => cleanText(v))
.join(" ")
)
.sort()
.join(",");
} else if (typeof actions === "string") {
return actions
.split(",")
.map((a) => cleanText(a))
.sort()
.join(",");
}
return "";
};
Show full message · 1,613 lines Assistant2025-05-10 05:26 UTC Copy response
Your main problem is that clicking the clear (x) only clears the input's visible text but does not effectively reset the searchTerm and searchQuery state in your React component due to how <fw-input> (a web component) handles the fwClear event and React event handler compatibility.
The exact fix
Because onFwClear as a React prop does NOT work reliably with Freshworks fw-input (web component), you need to use a ref + manual event listener :
1. Attach native event listener for "fwClear" event on your <fw-input> using a useEffect() hook:
Add this inside your AutomationTabs component:
jsx Copy code
const inputRef = useRef(null);
useEffect(() => {
if (inputRef.current) {
const onClear = () => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
};
inputRef.current.addEventListener("fwClear", onClear);
return () => {
if (inputRef.current) {
inputRef.current.removeEventListener("fwClear", onClear);
}
};
}
}, [activeTab]);
2. Change your <fw-input> to remove the onFwClear prop and add the ref properly:
yes give me complete minimal code snippet of what fixed
Assistant2025-05-10 05:30 UTC Copy response
Certainly! Here is a minimal, focused snippet for the search input and the related React logic that fixes the clear ("x") button behavior for your <fw-input> component in React.
Minimal Fixed Example for Search Input Clear Behavior in React
jsx Copy code
import React, { useState, useEffect, useRef } from "react";
const AutomationTabs = ({ activeTab, setActiveTab }) => {
const [searchTerm, setSearchTerm] = useState("");
const [searchQuery, setSearchQuery] = useState("");
const [inputState, setInputState] = useState("normal");
const [currentPage, setCurrentPage] = useState({
ticketcreate: 1,
ticketupdate: 1,
hourly: 1,
});
const warningTimerRef = useRef(null);
const inputRef = useRef(null);
// Add fwClear native event listener on fw-input web component
useEffect(() => {
const inputEl = inputRef.current;
if (!inputEl) return;
const onClear = () => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
};
inputEl.addEventListener("fwClear", onClear);
return () => {
inputEl.removeEventListener("fwClear", onClear);
};
}, [activeTab]);
return (
<fw-input
ref={inputRef}
icon-left="search"
hint-text="Type Keyword to Search"
placeholder="Enter a Keyword to Search..."
warning-text="Please Enter a Keyword to Search..."
state={inputState}
clear-input
style={{ width: "400px", height: "60px", fontSize: "18px" }}
value={searchTerm}
onInput={(e) => {
const val = e.target.value;
if (val.length < searchTerm.length) {
setSearchQuery(""); // Clear filter to show all rules when deleting chars
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}
setSearchTerm(val);
if (inputState !== "normal") setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setInputState("warning");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
warningTimerRef.current = setTimeout(() => {
setInputState("normal");
warningTimerRef.current = null;
}, 3000);
} else {
setSearchQuery(trimmed);
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
}
}
}}
/>
);
};
export default AutomationTabs;
no it still stays as it is only searhterm from search input is removed not resetted the serarch (backend) so it still statys at search active fltered
please fix in this code.
import React, { useState, useEffect, useRef } from "react";
import {
FwTabs,
FwTab,
FwTabPanel,
FwSpinner,
ToastController,
FwToast,
FwPagination,
FwModalTitle,
FwModalContent,
FwToggle,
FwButton,
FwIcon,
FwListOptions,
FwPopover,
FwModal,
} from "@freshworks/crayons/react";
// import SummaryContent from "./SummaryContent";
import {
getTicketCreationRules,
getTicketUpdationRules,
getHourlyRules,
getAgents,
pagination,
} from "../common";
// Utility: clean and normalize text
const cleanText = (text) =>
String(text || "")
.toLowerCase()
.replace(/<img[^>]>/gi, "") // remove tags
.replace(/ /gi, " ") // replace non-breaking space
.replace(/<[^>] >/g, "") // remove any other HTML tags
.replace(/[,.]/g, "") // remove commas and periods
.replace(/([a-zA-Z])(\d)/g, "1 1 1 2") // split letters & digits
.replace(/(\d)([a-zA-Z])/g, "1 1 1 2")
.replace(/\s+/g, " ") // collapse spaces
.trim()
.replace(/\bcomma\b\s*\bfull\s*stop\b/g, "comma fullstop");
// Normalize the condition parts similarly to original code logic
const normalizeConditionParts = (rawConditions) => {
let parts = [];
if (typeof rawConditions === "string") {
parts = rawConditions.split(",");
} else if (Array.isArray(rawConditions)) {
parts = rawConditions;
} else {
// if conditions is null, undefined, object etc.
parts = [];
}
const set1 = [];
const set2 = [];
let currentSet = null;
for (let part of parts) {
const cleaned = cleanText(part);
if (cleaned === "condition set 1") {
currentSet = set1;
continue;
}
if (cleaned === "condition set 2") {
currentSet = set2;
continue;
}
if (currentSet) currentSet.push(cleaned);
}
set1.sort();
set2.sort();
return { set1, set2 };
};
// Normalize actions (handle string or array)
const normalizeActions = (actions) => {
if (Array.isArray(actions)) {
return actions
.map((action) =>
Object.values(action)
.map((v) => cleanText(v))
.join(" ")
)
.sort()
.join(",");
} else if (typeof actions === "string") {
return actions
.split(",")
.map((a) => cleanText(a))
.sort()
.join(",");
}
return "";
};
Show full message · 1,625 lines Assistant2025-05-10 05:32 UTC Copy response
The root cause of the issue is that your search input (searchTerm) is cleared visually but the filtering state (searchQuery) is not reset immediately or consistently when the clear (x) button is clicked. That makes the filter remain active hiding all or some rules even though the input looks empty.
How to fix the issue in your existing code:
React doesn’t automatically recognize web component events like fwClear when used as JSX props (onFwClear).
You must use a ref and add a native event listener on the web component node for "fwClear" event.
Inside that event handler, reset both searchTerm AND searchQuery to empty strings and reset the current page .
Also make sure your filtering is based only on searchQuery , which you've done.
Minimal fix integration for your code:
Add this useEffect after your inputRef declaration:
jsx Copy code
const inputRef = useRef(null);
useEffect(() => {
const inputEl = inputRef.current;
if (!inputEl) return;
const onClearHandler = () => {
setSearchTerm("");
setSearchQuery(""); // critical: clear filter term on clear button click
setCurrentPage(prev => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
};
inputEl.addEventListener("fwClear", onClearHandler);
return () => {
inputEl.removeEventListener("fwClear", onClearHandler);
};
}, [activeTab]);
Change your <fw-input> element by:
Adding ref={inputRef}
Removing the onFwClear prop entirely
Example:
Assistant2025-05-10 05:33 UTC Copy response
Here's a complete focused integration snippet based on your full code with the proper fix for the search input clear button functionality.
Key changes:
Use a ref for <fw-input> (called inputRef).
Add native "fwClear" listener with addEventListener inside a useEffect.
Remove the JSX onFwClear prop on the <fw-input>.
In the "fwClear" handler, reset both searchTerm and searchQuery and pagination.
Code snippet to add/replace inside AutomationTabs component:
Assistant2025-05-10 05:34 UTC Copy response
Certainly! Here is the separate patch/fix part you can add to your existing AutomationTabs component to fix the clear button behavior on the <fw-input> search box:
1. Add this ref declaration near other refs:
js Copy code
const inputRef = useRef(null);
2. Add this useEffect inside your AutomationTabs component (after the ref declaration):
js Copy code
useEffect(() => {
const inputEl = inputRef.current;
if (!inputEl) return;
const onClearHandler = () => {
// Reset both searchTerm and searchQuery to clear the filter
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
};
inputEl.addEventListener("fwClear", onClearHandler);
return () => {
inputEl.removeEventListener("fwClear", onClearHandler);
};
}, [activeTab]);
3. Modify your <fw-input> element by:
Adding ref={inputRef}
Removing any onFwClear prop if you have it
Your input should look like this:
Assistant2025-05-10 05:36 UTC Copy response
If the native "fwClear" event listener approach did not work, let's carefully troubleshoot and apply an alternative robust fix that works reliably with Freshworks fw-input in React. Here's a proven approach:
Why it might still fail
Sometimes fw-input's internal clear button (clear-input attribute) does clear visible input but does not fire the "fwClear" event in some versions or environments.
React prop handler onFwClear won't work as it's a custom event.
The input's internal state and your React state searchTerm can get out-of-sync.
Robust Fix — Controlled Reset via onInput event detection
Instead of relying on "fwClear" event, detect the clearing by watching input value changes in the onInput event AND checking when value becomes an empty string. Then reset your filter states.
Here’s exactly what you should do:
Step 1 - Remove any onFwClear or "fwClear" listener code related to inputRef.
Step 2 - Modify your <fw-input> like this (fully controlled):
Copy first response
Not yet included in a published release.
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", boxShadow: "0 4px 8px rgba(0, 0, 0, 0.2)" }}>
{rulesToShow.map((rule, i) => (
<div
key={rule.id}
className="fw-card-1"
style={{
marginTop: i === 0 ? "10px" : "2px",
padding: "5px 8px",
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 {
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>
));
}
{showSearchHint && (
<p style={{ color: "red", marginTop: "4px", fontSize: "0.9em" }}>
Please enter a search term before searching.
</p>
)}
{loadingBannerVisible && !isRulesDBReady && (
<div
style={{
justifyContent: "center",
alignItems: "center",
height: "40px",
width: "50%",
margin: "0 auto",
}}
>
<FwSpinner size="medium" color="green" />
<span style={{ marginLeft: "8px" }}>Waiting for rules to be ready...</span>
</div>
)}
{tabsInitialized && (
<div style={{ width: "60%", marginRight: "auto" }}>
<div
style={{
display: "flex",
justifyContent: fetchFromApi ? "flex-start" : "flex-end",
marginBottom: 15,
}}
>
<FwButton color="secondary" onFwClick={fetchData} disabled={!isRulesDBReady}>
{fetchFromApi ? (
<>
<FwIcon
slot="before-label"
name="arrow-left"
size={16}
style={{ marginRight: "8px" }}
/>
Back
</>
) : (
<>
Get Recent Data
<FwIcon
slot="after-label"
name="refresh"
size={16}
style={{ marginLeft: "8px" }}
/>
</>
)}
</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>
</div>
)}
</>
)}
<FwToast />
all
nextMarker
js Copy code
let allRecords = [];
let nextMarker = null;
do {
// fetch page from entity DB
const response = await newRulePloadDB3.getAll(queryObj);
allRecords = allRecords.concat(response.records);
nextMarker = response.links?.next?.marker || null;
} while (nextMarker);
So in the data fetching, no hard limit is placed — it keeps fetching all pages until exhausted.
No Max Pagination Limit:
Since all data for a tab is loaded into state as a single array (ticketCreationRules, ticketUpdateRules, etc.), and pagination only slices the client-side array by page (pagination() utility function), there is effectively no max limit or upper limit on total pages that can exist.
Pagination Utility:
The pagination() function called slices arrays based on page number and rulesPerPage, so pages beyond the total page count will have no data.
Summary:
The component does paginate the shown rules using a page size (rulesPerPage) of 30 rules per page.
There is no explicit maximum number of pages coded; pagination depends on the total number of rules after filtering.
Data fetching functions fetch all pages from the backend by repeatedly querying with markers until no more data.
Pagination is pure client-side slicing of fetched data.
The user can (in theory) navigate through all pages as long as there is data.
Optional notes:
If you want to limit maximum pages shown or maximum total rules, you'd have to add logic to restrict total fetched data or cap the pagination UI accordingly.
This current design may cause performance issues if the total number of rules becomes very large, as all rules are loaded at once into memory and paginated client-side.
Conclusion: The code paginates with 30 items per page but has no explicit maximum pagination limit on the number of pages. The total number of pages depends dynamically on the total number of fetched and filtered rules.
searchQuery
currentPage not reset properly
You do reset the current page for activeTab to page 1 (good).
This is correct behavior when clearing search.
Maybe the input's value prop isn't tied properly
You set <fw-input value={searchTerm} ... />. Make sure that searchTerm updates on clear event and is passed down properly.
React state change should update input UI to empty as well.
How to debug and fix:
Verify if onFwClear is triggered
Add a console log inside:
jsx Copy code
onFwClear={() => {
console.log("Clear button clicked");
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
If nothing logs, the event might not be firing.
Alternative event listener attachment
Sometimes with web components you need:
jsx Copy code
const inputRef = useRef(null);
useEffect(() => {
const inputElement = inputRef.current;
if (!inputElement) return;
const onClear = () => {
console.log("Clear button clicked");
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
};
inputElement.addEventListener("fwClear", onClear);
return () => {
inputElement.removeEventListener("fwClear", onClear);
};
}, [activeTab]);
And keep the ref={inputRef} on your <fw-input>. This may be necessary if the React prop onFwClear is not working.
Ensure searchQuery and searchTerm reset triggers filtering
Your filtering function uses searchQuery, so when it becomes "", all rules should be shown. The pagination slicing is done accordingly.
Make sure the component rerenders
Use React dev tools or logs to confirm component re-renders on these state changes.
Summary:
Most likely the issue is the onFwClear event is not firing or not handled correctly by that React web component.
Try attaching listener with addEventListener("fwClear", fn) via ref and verify.
Confirm that clearing the states actually resets filters and pagination.
If input clears visually but filter doesn't reset, the issue is probably in event handling or state binding.
Additional Note on Web Components + React: fw-input is a web component — React doesn't automatically wrap custom events fwClear into React props onFwClear unless support is explicitly provided.
So binding onFwClear in JSX may not work directly. This is a common scenario with web components and React.
Conclusion Use a ref and addEventListener("fwClear") approach to handle the clear button click properly in your React component. This will allow resetting searchTerm and searchQuery, which then shows all rules again.
// Main normalized signature function combining conditions, actions, and operator
const getRuleSignatureNormalized = (rule) => {
const rawConditions = rule.summary?.conditions || rule.conditions || "";
const rawActions = rule.summary?.actions || rule.actions || "";
const operator = rule.operator || "";
const { set1, set2 } = normalizeConditionParts(rawConditions);
const normalizedActions = normalizeActions(rawActions);
const normalizedOperator = cleanText(operator);
// The signature should consider the fact conditions might be interchangeable
// between set1 and set2 (commutative)
const key1 = JSON.stringify({ set1, set2, actions: normalizedActions, operator: normalizedOperator });
const key2 = JSON.stringify({ set1: set2, set2: set1, actions: normalizedActions, operator: normalizedOperator });
// Return lexicographically smallest key for commutative sets
return key1 < key2 ? key1 : key2;
};
// Group duplicates by normalized signature
const groupDuplicates = (rules) => {
const groups = {};
rules
.filter((rule) => rule.active === "true" || rule.active === true) // handle boolean or string "true"
.forEach((rule) => {
const signature = getRuleSignatureNormalized(rule);
if (!groups[signature]) groups[signature] = [];
groups[signature].push(rule);
});
return Object.values(groups);
};
// export { groupDuplicates, getRuleSignatureNormalized };
// 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 [];
// }
// };
// ===== AutomationCard Component Inlined =====
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 };
code Copy code
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);
// Sort by `position` ascending before returning
allRecords.sort((a, b) => {
// If position undefined/missing, treat as larger - push to bottom
const posA = typeof a.position === "number" ? a.position : Number.MAX_SAFE_INTEGER;
const posB = typeof b.position === "number" ? b.position : Number.MAX_SAFE_INTEGER;
return posA - posB;
});
console.log(`✅ Filtered Records for Type ${automationTypeId}:`, allRecords);
return allRecords;
} catch (error) {
console.error("❌ Error fetching filtered records:", error);
return [];
}
};
const calculateLastModified = (updated_at) => {
const updatedDate = new Date(updated_at);
const currentDate = new Date();
const diffInMilliseconds = currentDate - updatedDate;
const seconds = Math.floor(diffInMilliseconds / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const months = Math.floor(days / 30);
const years = Math.floor(days / 365);
if (years > 0) return years === 1 ? "a year ago" : ${years} years ago;
if (months > 0) return months === 1 ? "a month ago" : ${months} months ago;
if (days > 0) return ${days} day${days > 1 ? "s" : ""} ago;
if (hours > 0) return ${hours} hour${hours > 1 ? "s" : ""} ago;
if (minutes > 0) return ${minutes} minute${minutes > 1 ? "s" : ""} ago;
return "Just now";
};
const AutomationCard = ({
rule = {},
index,
isFirstInGroup = false,
onDelete,
agent,
activeTab,
onSelect,
}) => {
const {
id,
name = "Default Rule Name",
summary = "",
description = "",
updated_at = "N/A",
last_updated_by = "Unknown",
affected_tickets_count = "--",
active = false,
position,
automation_type_id,
} = rule;
const [menuOpen, setMenuOpen] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const modalRef = useRef(null);
const menuContainerRef = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (
menuContainerRef.current &&
!menuContainerRef.current.contains(event.target)
) {
setMenuOpen(false);
}
};
code Copy code
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
// Imperatively open modal if showDeleteModal became true
useEffect(() => {
if (showDeleteModal && modalRef.current) {
modalRef.current.open();
}
}, [showDeleteModal]);
const openModal = () => setShowDeleteModal(true);
const closeModal = () => {
setShowDeleteModal(false);
if (modalRef.current) modalRef.current.close();
};
const handleConfirmDelete = () => {
closeModal();
if (onDelete) onDelete(rule);
};
const handleClick = () => {
if (onSelect) {
onSelect(rule);
}
};
const renderAgentName = () => {
if (rule.agentName) {
return rule.agentName;
}
if (!agent || !Array.isArray(agent)) {
return last_updated_by || "Unknown";
} else {
const foundAgent = agent.find((e) => e.value === last_updated_by);
return foundAgent ? foundAgent.text : last_updated_by || "Unknown";
}
};
function extractText(htmlString) {
if (!htmlString || typeof htmlString !== "string") return "";
let text = htmlString.replace(/<[^>]+>/g, "").trim();
if (text.toLowerCase().startsWith("if ")) {
text = text.substring(3).trim();
}
return text.toLowerCase();
}
function generateSummary(summary) {
if (!summary) return "";
if (typeof summary === "string") {
return summary;
}
let conditionTexts = [];
if (summary.conditions) {
for (const setKey in summary.conditions) {
if (Object.prototype.hasOwnProperty.call(summary.conditions, setKey)) {
const conditionsVal = summary.conditions[setKey];
const conditionsArray = Array.isArray(conditionsVal)
? conditionsVal
: [conditionsVal];
const cleanConditions = conditionsArray.map(extractText);
conditionTexts.push(cleanConditions.join(", "));
}
}
}
const conditionsStr = conditionTexts.join(", ");
let actionsStr = "";
if (summary.actions && Array.isArray(summary.actions)) {
const cleanActions = summary.actions.map(extractText);
actionsStr = cleanActions.join(", ");
}
if (conditionsStr && actionsStr) {
return if ${conditionsStr}, then ${actionsStr};
} else if (conditionsStr) {
return if ${conditionsStr};
} else if (actionsStr) {
return actionsStr;
}
return "";
}
function MenuList({ visible, onEdit, onClone, rule }) {
return (
<ul
style={{
position: "absolute",
backgroundColor: "white",
boxShadow: "0 8px 24px rgba(0, 0, 0, 0.15)",
borderRadius: 6,
padding: "8px 0",
minWidth: 160,
right: 0,
top: 28,
listStyle: "none",
zIndex: 9999,
margin: 0,
opacity: visible ? 1 : 0,
transform: visible
? "translateY(0px) scale(1)"
: "translateY(-10px) scale(0.98)",
transition: "opacity 300ms ease, transform 300ms ease",
pointerEvents: visible ? "auto" : "none",
willChange: "opacity, transform",
}}
>
{[
{ name: "edit", label: "Edit", onClick: onEdit },
{ name: "clone", label: "Clone", onClick: onClone },
{
name: "delete",
label: "Delete",
onClick: () => {
console.log("Delete icon clicked for rule id:", rule.id);
setMenuOpen(false);
openModal();
},
},
].map(({ name, label, onClick }) => (
<li
key={name}
style={{
display: "flex",
alignItems: "center",
gap: 8,
padding: "8px 16px",
cursor: "pointer",
color: "#333",
fontWeight: 500,
userSelect: "none",
backgroundColor: "transparent",
transition: "background-color 0.2s",
}}
onClick={(e) => {
e.stopPropagation();
onClick?.();
setMenuOpen(false);
}}
onMouseEnter={(e) =>
(e.currentTarget.style.backgroundColor = "#f5f7f9")
}
onMouseLeave={(e) =>
(e.currentTarget.style.backgroundColor = "transparent")
}
>
{label}
))}
);
}
return (
<>
<div
className="fw-card-1 fw-flex fw-flex-column"
style={{
overflow: "visible",
border: "0.5px solid #ddd",
backgroundColor: isFirstInGroup ? "#fff" : "#e5f2fd",
cursor: "pointer",
}}
onClick={handleClick}
>
<section
className="fw-flex-grow fw-px-16 fw-flex fw-flex-row"
style={{
justifyContent: "space-between",
alignItems: "center",
marginBottom: "40px",
}}
>
<div
style={{
paddingLeft: "16px",
maxWidth: "80%",
flexBasis: "80%",
flexShrink: 0,
whiteSpace: "normal",
}}
>
{position}. {name}
<p
className="fw-type-xs fw-mt-0 fw-mb-20"
style={{ marginBottom: "10px", fontSize: "14px" }}
>
{generateSummary(rule.summary)}
code Copy code
<div
style={{
display: "flex",
alignItems: "center",
gap: "8px",
padding: "8px 16px",
flexBasis: "20%",
flexShrink: 0,
marginTop: "-50px",
justifyContent: "flex-end",
position: "relative",
}}
>
<FwToggle size="medium" checked={active} />
<div ref={menuContainerRef} style={{ position: "relative" }}>
<div
role="button"
tabIndex={0}
onClick={(e) => {
e.stopPropagation();
setMenuOpen(!menuOpen);
}}
style={{
zIndex: 1,
background: "none",
border: "none",
cursor: "pointer",
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
className="app-icon dropdown-toggle"
>
<path
fillRule="evenodd"
d="M12 5c-1.38 0-2.5-1.12-2.5-2.5S10.62 0 12 0s2.5 1.12 2.5 2.5S13.38 5 12 5zM12 14c-1.38 0-2.5-1.12-2.5-2.5S10.62 9 12 9s2.5 1.12 2.5 2.5S13.38 14 12 14zM12 24c-1.38 0-2.5-1.12-2.5-2.5S10.62 19 12 19s2.5 1.12 2.5 2.5S13.38 24 12 24z"
/>
</svg>
</div>
<MenuList
visible={menuOpen}
onEdit={() => alert("Edit clicked")}
onClone={() => alert("Clone clicked")}
rule={rule}
/>
</div>
</div>
</section>
<section
className="fw-type-xs fw-flex fw-flex-row fw-items-center options"
style={{
background: "#f5f7f9",
padding: "10px 16px",
borderRadius: "5px",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-evenly",
width: "100%",
fontSize: "14px",
color: "#666",
textAlign: "center",
}}
>
<span>
Last Modified: <strong>{calculateLastModified(updated_at)}</strong>
</span>
<span>|</span>
<span>By: {renderAgentName()}</span>
<span>|</span>
<span>Impacted tickets (Last 7 days): {affected_tickets_count}</span>
</div>
</section>
</div>
{/* Delete Confirmation Modal */}
<FwModal
id={`delete-modal-${id}`}
ref={modalRef}
size="small"
submit-color="danger"
submit-text="Delete"
onFwSubmit={(e) => {
e.preventDefault?.();
handleConfirmDelete();
}}
onFwClose={() => {
setShowDeleteModal(false);
if (modalRef.current) modalRef.current.close();
}}
>
<FwModalTitle>
<span>Delete message</span>
</FwModalTitle>
<FwModalContent>
<span>Are you sure you want to delete this Message?</span>
</FwModalContent>
</FwModal>
</>
// ===== AutomationTabs Component =====
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 [errorMessage, setErrorMessage] = useState(null);
const [activeTab, setActiveTab] = useState("ticketcreate");
const [inputState, setInputState] = useState("normal"); // <-- added
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 [currentPage, setCurrentPage] = useState({
ticketcreate: 1,
ticketupdate: 1,
hourly: 1,
});
const toast = useRef(ToastController({ position: "top-center" }));
const newRulePloadDB5 = useRef(null);
const warningTimerRef = useRef(null); // <-- added
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(() => {
if (!loading) {
const timer = setTimeout(() => {
setShowPagination(true);
}, 200);
return () => clearTimeout(timer);
} else {
setShowPagination(false);
}
}, [loading, 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");
code Copy code
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();
// Whenever activeTab changes, reset its page to 1
useEffect(() => {
setCurrentPage((prev) => ({
...prev,
[activeTab]: 1,
}));
code Copy code
if (ruleViewFilter.value === "duplicate_rules") {
setRuleViewFilter(ruleViewOptions[0]); // Reset to 'All Rules' on tab switch
}
// ===== 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]);
useEffect(() => {
const fetchOnTabOrModeChange = async () => {
setLoading(true);
setErrorMessage(null); // clear previous errors
try {
let error = null;
if (fetchFromApi) {
if (activeTab === "ticketcreate") {
error = await getTicketCreationRules(client, setTicketCreationRules);
} else if (activeTab === "ticketupdate") {
error = await getTicketUpdationRules(client, setTicketUpdateRules);
} else if (activeTab === "hourly") {
error = await getHourlyRules(client, setHourlyTriggerRules);
}
await getAgents(client, setAgent); // this can also set errors if you want
} else {
if (!newRulePloadDB5.current) {
console.error("❌ Entity DB reference not initialized.");
setLoading(false);
return;
}
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);
}
}
code Copy code
if (error) {
setErrorMessage(error);
}
} catch (err) {
console.error("Error fetching data:", err);
setErrorMessage("An unexpected error occurred while fetching data.");
}
setLoading(false);
};
if (tabsInitialized && isRulesDBReady) {
fetchOnTabOrModeChange();
}
}, [activeTab, fetchFromApi, client, tabsInitialized, isRulesDBReady]);
const handlePageChange = (tab) => (event) => {
setCurrentPage((prev) => ({
...prev,
[tab]: event.detail.page,
}));
};
useEffect(() => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}, [activeTab]);
useEffect(() => {
const fwTabs = document.querySelector("fw-tabs");
code Copy code
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);
}
};
// const fetchData = async () => {
// if (!fetchFromApi) {
// setSearchTerm("");
// setSearchQuery("");
// setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
// }
// setFetchFromApi((prev) => !prev);
// toast.current.trigger({
// type: "info",
// content: ${fetchFromApi ? "Going Back" : "Fetching Recent Data"}...,
// });
// };
const fetchData = async () => {
code Copy code
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setFetchFromApi((prev) => !prev);
// Toast content depends on current mode before toggling
toast.current.trigger({
type: "info",
content: `${fetchFromApi ? "Going Back" : "Fetching Recent Data"}...`,
});
const checkAndSetButtonState = async () => {
try {
const storedvalue1 = await client.db.get("RulesDB");
const isButtonEnabled = !!storedvalue1.stored;
if (isButtonEnabled) {
setIsRulesDBReady(true);
setLoadingBannerVisible(false);
code Copy code
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;
code Copy code
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 inputRef = useRef(null);
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 }));
code Copy code
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="Type Keyword to Search"
placeholder="Enter a Keyword to Search..."
warning-text="Please Enter a Keyword to Search..."
state={inputState}
clear-input
style={{
width: "400px",
height: "60px",
fontSize: "18px",
}}
value={searchTerm}
onInput={(e) => {
const val = e.target.value;
if (val.length < searchTerm.length) {
setSearchQuery(""); // Clear filter to show all rules
}
setSearchTerm(val);
if (showSearchHint) setShowSearchHint(false);
if (inputState !== "normal") setInputState("normal");
code Copy code
// Clear warning timeout if user starts typing
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setShowSearchHint(false);
setInputState("warning");
// Show warning for 3 seconds
warningTimerRef.current = setTimeout(() => {
setInputState("normal");
warningTimerRef.current = null;
}, 3000);
} else {
setSearchQuery(trimmed);
setShowSearchHint(false);
setInputState("normal");
}
}
}}
onFwClear={() => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
code Copy code
<div style={{ flexShrink: 0 }}>
<FwButton color="primary" onFwClick={() => { /* Add your handler here */ }}>
<fw-icon name="plus" size="16" style={{ marginRight: "8px" }}></fw-icon>
Add New Rule
</FwButton>
</div>
</div>
const getTotalPages = () => {
if (ruleViewFilter.value === "duplicate_rules") {
const groups =
activeTab === "ticketcreate"
? ticketCreationRuleGroups
: activeTab === "ticketupdate"
? ticketUpdateRuleGroups
: hourlyRuleGroups;
code Copy code
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);
}
const renderRulesOrGroups = () => {
let groups = [];
let flatRules = [];
code Copy code
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", boxShadow: "0 4px 8px rgba(0, 0, 0, 0.2)" }}>
{rulesToShow.map((rule, i) => (
<div
key={rule.id}
className="fw-card-1"
style={{
marginTop: i === 0 ? "10px" : "2px",
padding: "5px 8px",
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 {
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>
));
}
const deleteRule = async (rule, allRulesList) => {
console.log("deleteRule called with rule:", rule);
code Copy code
const { id } = rule;
const matchedRecord = allRulesList.find((rec) => rec.id === id);
let automationTypeId;
let currentRules, setRulesFunc, groupSetterFunc, currentTabPage, tabKey;
switch (activeTab) {
case "ticketcreate":
automationTypeId = ticketCreate;
currentRules = ticketCreationRules;
setRulesFunc = setTicketCreationRules;
groupSetterFunc = setTicketCreationRuleGroups;
currentTabPage = currentPage.ticketcreate;
tabKey = "ticketcreate";
break;
case "ticketupdate":
automationTypeId = ticketUpdate;
currentRules = ticketUpdateRules;
setRulesFunc = setTicketUpdateRules;
groupSetterFunc = setTicketUpdateRuleGroups;
currentTabPage = currentPage.ticketupdate;
tabKey = "ticketupdate";
break;
case "hourly":
automationTypeId = hourlyTriggers;
currentRules = hourlyTriggerRules;
setRulesFunc = setHourlyTriggerRules;
groupSetterFunc = setHourlyRuleGroups;
currentTabPage = currentPage.hourly;
tabKey = "hourly";
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) {
// Update rules state after deletion
const updatedRules = currentRules.filter((r) => r.id !== id);
setRulesFunc(updatedRules);
// Clear duplicates group cache if any
groupSetterFunc([]);
// Pagination check: get filtered rules based on current searchQuery & ruleViewFilter
// Here using your getFilteredRules function to apply search filtering
let filteredRules = getFilteredRules(updatedRules);
// Calculate items on current page after deletion
const paginatedItems = pagination(
filteredRules,
currentTabPage
);
// If current page is now empty and not already on first page, go back one page
if (paginatedItems.length === 0 && currentTabPage > 1) {
setCurrentPage((prev) => ({
...prev,
[tabKey]: prev[tabKey] - 1,
}));
}
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);
code Copy code
const duplicateGroups = grouped
.filter((group) => group.length > 1)
.sort((a, b) => b.length - a.length);
console.log("Grouping duplicates for tab: ticketcreate");
console.log("All Ticket Creation Rules:", ticketCreationRules);
console.log("Grouped Rules:", grouped);
console.log("Duplicate Groups (length > 1):", duplicateGroups);
setTicketCreationRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketcreate: 1 }));
} 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("Grouping duplicates for tab: ticketupdate");
console.log("All Ticket Update Rules:", ticketUpdateRules);
console.log("Grouped Rules:", grouped);
console.log("Duplicate Groups (length > 1):", duplicateGroups);
setTicketUpdateRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketupdate: 1 }));
} 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("Grouping duplicates for tab: hourly");
console.log("All Hourly Trigger Rules:", hourlyTriggerRules);
console.log("Grouped Rules:", grouped);
console.log("Duplicate Groups (length > 1):", duplicateGroups);
setHourlyRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, hourly: 1 }));
}
const getPaginatedItemCount = () => {
let rules = [];
if (activeTab === "ticketcreate") rules = ticketCreationRules;
else if (activeTab === "ticketupdate") rules = ticketUpdateRules;
else if (activeTab === "hourly") rules = hourlyTriggerRules;
code Copy code
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 (
<>
{errorMessage ? (
code Copy code
{showSearchHint && (
<p style={{ color: "red", marginTop: "4px", fontSize: "0.9em" }}>
Please enter a search term before searching.
</p>
)}
{loadingBannerVisible && !isRulesDBReady && (
<div
style={{
justifyContent: "center",
alignItems: "center",
height: "40px",
width: "50%",
margin: "0 auto",
}}
>
<FwSpinner size="medium" color="green" />
<span style={{ marginLeft: "8px" }}>Waiting for rules to be ready...</span>
</div>
)}
{tabsInitialized && (
<div style={{ width: "60%", marginRight: "auto" }}>
<div
style={{
display: "flex",
justifyContent: fetchFromApi ? "flex-start" : "flex-end",
marginBottom: 15,
}}
>
<FwButton color="secondary" onFwClick={fetchData} disabled={!isRulesDBReady}>
{fetchFromApi ? (
<>
<FwIcon
slot="before-label"
name="arrow-left"
size={16}
style={{ marginRight: "8px" }}
/>
Back
</>
) : (
<>
Get Recent Data
<FwIcon
slot="after-label"
name="refresh"
size={16}
style={{ marginLeft: "8px" }}
/>
</>
)}
</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>
</div>
)}
</>
)}
<FwToast />
export default AutomationTabs;
<fw-input
ref={inputRef}
icon-left="search"
hint-text="Type Keyword to Search"
placeholder="Enter a Keyword to Search..."
warning-text="Please Enter a Keyword to Search..."
state={inputState}
clear-input
style={{
width: "400px",
height: "60px",
fontSize: "18px",
}}
value={searchTerm}
onInput={(e) => {
const val = e.target.value;
if (val.length < searchTerm.length) {
setSearchQuery(""); // Clear filter to show all rules
}
setSearchTerm(val);
if (showSearchHint) setShowSearchHint(false);
if (inputState !== "normal") setInputState("normal");
// Clear warning timeout if user starts typing
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setShowSearchHint(false);
setInputState("warning");
// Show warning for 3 seconds
warningTimerRef.current = setTimeout(() => {
setInputState("normal");
warningTimerRef.current = null;
}, 3000);
} else {
setSearchQuery(trimmed);
setShowSearchHint(false);
setInputState("normal");
}
}
}}
/>
Explanation:
React does not recognize onFwClear directly because it's a custom event from a web component.
Attaching a native event listenener with addEventListener on the actual DOM element works reliably.
Clearing the searchTerm and searchQuery and resetting the page number inside that handler makes your filtering logic show all rules again when the clear "x" is clicked.
We also clear any warning timers to keep the input state consistent.
Full snippet to add inside your component (just place near other hooks): jsx Copy code
// Attach fwClear event listener to listen for clear button clicks
useEffect(() => {
const inputEl = inputRef.current;
if (!inputEl) return;
const onFwClear = () => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
};
inputEl.addEventListener("fwClear", onFwClear);
return () => {
inputEl.removeEventListener("fwClear", onFwClear);
};
}, [activeTab]);
If you apply this change, clicking the clear ("x") button in the search input will correctly reset the search and show all rules again .
Let me know if you want me to create a fully integrated code post with this included!
onInput={(e) => {
const val = e.target.value;
setSearchTerm(val);
setSearchQuery(val); // <-- update searchQuery here too to filter as you type
if (showSearchHint) setShowSearchHint(false);
if (inputState !== "normal") setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
If you want to keep your current pattern where filtering triggers only on Enter key and clear, then after clearing you should also reset searchQuery and trigger a rerender (which you do).
Make sure your filtering uses searchQuery, and not searchTerm, and that filtering always runs on the latest searchQuery state.
Optional: Instant filtering on input If you want filtering as you type (which is more intuitive), update both states on input as above.
If you want filtering only on Enter key press but clear resets filters immediately, keep Enter key handler and do:
js Copy code
onInput={(e) => {
const val = e.target.value;
setSearchTerm(val);
if (val.length === 0) {
setSearchQuery(""); // reset filter when field cleared manually
}
...
}}
Complete fixed <fw-input> handlers snippet for common case (filter on Enter, clear resets): jsx Copy code
<fw-input
ref={inputRef}
icon-left="search"
hint-text="Type Keyword to Search"
placeholder="Enter a Keyword to Search..."
warning-text="Please Enter a Keyword to Search..."
state={inputState}
clear-input
style={{
width: "400px",
height: "60px",
fontSize: "18px",
}}
value={searchTerm}
onInput={(e) => {
const val = e.target.value;
setSearchTerm(val);
if (val.length === 0) {
setSearchQuery(""); // reset filter immediately on empty input
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}
if (showSearchHint) setShowSearchHint(false);
if (inputState !== "normal") setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setShowSearchHint(false);
setInputState("warning");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
// Show warning for 3 seconds
warningTimerRef.current = setTimeout(() => {
setInputState("normal");
warningTimerRef.current = null;
}, 3000);
} else {
setSearchQuery(trimmed);
setShowSearchHint(false);
setInputState("normal");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}
}
}}
/>
And in your fwClear listener:
js Copy code
const onFwClear = () => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
};
Why resetting page? You reset current page to 1 after clearing or changing search to ensure consistent UI.
Summary
Make sure both searchTerm and searchQuery are cleared on the clear event.
Update searchQuery immediately when the input value becomes empty on any input.
Reset page to 1 whenever you clear or perform a new search.
Filter based on searchQuery strictly.
This ensures the filtered list shows "all" rules once cleared.
If you want, I can also prepare a full minimal example of the fixed part for you to copy-paste — just ask!
// Main normalized signature function combining conditions, actions, and operator
const getRuleSignatureNormalized = (rule) => {
const rawConditions = rule.summary?.conditions || rule.conditions || "";
const rawActions = rule.summary?.actions || rule.actions || "";
const operator = rule.operator || "";
const { set1, set2 } = normalizeConditionParts(rawConditions);
const normalizedActions = normalizeActions(rawActions);
const normalizedOperator = cleanText(operator);
// The signature should consider the fact conditions might be interchangeable
// between set1 and set2 (commutative)
const key1 = JSON.stringify({ set1, set2, actions: normalizedActions, operator: normalizedOperator });
const key2 = JSON.stringify({ set1: set2, set2: set1, actions: normalizedActions, operator: normalizedOperator });
// Return lexicographically smallest key for commutative sets
return key1 < key2 ? key1 : key2;
};
// Group duplicates by normalized signature
const groupDuplicates = (rules) => {
const groups = {};
rules
.filter((rule) => rule.active === "true" || rule.active === true) // handle boolean or string "true"
.forEach((rule) => {
const signature = getRuleSignatureNormalized(rule);
if (!groups[signature]) groups[signature] = [];
groups[signature].push(rule);
});
return Object.values(groups);
};
// export { groupDuplicates, getRuleSignatureNormalized };
// 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 [];
// }
// };
// ===== AutomationCard Component Inlined =====
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 };
code Copy code
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);
// Sort by `position` ascending before returning
allRecords.sort((a, b) => {
// If position undefined/missing, treat as larger - push to bottom
const posA = typeof a.position === "number" ? a.position : Number.MAX_SAFE_INTEGER;
const posB = typeof b.position === "number" ? b.position : Number.MAX_SAFE_INTEGER;
return posA - posB;
});
console.log(`✅ Filtered Records for Type ${automationTypeId}:`, allRecords);
return allRecords;
} catch (error) {
console.error("❌ Error fetching filtered records:", error);
return [];
}
};
const calculateLastModified = (updated_at) => {
const updatedDate = new Date(updated_at);
const currentDate = new Date();
const diffInMilliseconds = currentDate - updatedDate;
const seconds = Math.floor(diffInMilliseconds / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const months = Math.floor(days / 30);
const years = Math.floor(days / 365);
if (years > 0) return years === 1 ? "a year ago" : ${years} years ago;
if (months > 0) return months === 1 ? "a month ago" : ${months} months ago;
if (days > 0) return ${days} day${days > 1 ? "s" : ""} ago;
if (hours > 0) return ${hours} hour${hours > 1 ? "s" : ""} ago;
if (minutes > 0) return ${minutes} minute${minutes > 1 ? "s" : ""} ago;
return "Just now";
};
const AutomationCard = ({
rule = {},
index,
isFirstInGroup = false,
onDelete,
agent,
activeTab,
onSelect,
}) => {
const {
id,
name = "Default Rule Name",
summary = "",
description = "",
updated_at = "N/A",
last_updated_by = "Unknown",
affected_tickets_count = "--",
active = false,
position,
automation_type_id,
} = rule;
const [menuOpen, setMenuOpen] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const modalRef = useRef(null);
const menuContainerRef = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (
menuContainerRef.current &&
!menuContainerRef.current.contains(event.target)
) {
setMenuOpen(false);
}
};
code Copy code
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
// Imperatively open modal if showDeleteModal became true
useEffect(() => {
if (showDeleteModal && modalRef.current) {
modalRef.current.open();
}
}, [showDeleteModal]);
const openModal = () => setShowDeleteModal(true);
const closeModal = () => {
setShowDeleteModal(false);
if (modalRef.current) modalRef.current.close();
};
const handleConfirmDelete = () => {
closeModal();
if (onDelete) onDelete(rule);
};
const handleClick = () => {
if (onSelect) {
onSelect(rule);
}
};
const renderAgentName = () => {
if (rule.agentName) {
return rule.agentName;
}
if (!agent || !Array.isArray(agent)) {
return last_updated_by || "Unknown";
} else {
const foundAgent = agent.find((e) => e.value === last_updated_by);
return foundAgent ? foundAgent.text : last_updated_by || "Unknown";
}
};
function extractText(htmlString) {
if (!htmlString || typeof htmlString !== "string") return "";
let text = htmlString.replace(/<[^>]+>/g, "").trim();
if (text.toLowerCase().startsWith("if ")) {
text = text.substring(3).trim();
}
return text.toLowerCase();
}
function generateSummary(summary) {
if (!summary) return "";
if (typeof summary === "string") {
return summary;
}
let conditionTexts = [];
if (summary.conditions) {
for (const setKey in summary.conditions) {
if (Object.prototype.hasOwnProperty.call(summary.conditions, setKey)) {
const conditionsVal = summary.conditions[setKey];
const conditionsArray = Array.isArray(conditionsVal)
? conditionsVal
: [conditionsVal];
const cleanConditions = conditionsArray.map(extractText);
conditionTexts.push(cleanConditions.join(", "));
}
}
}
const conditionsStr = conditionTexts.join(", ");
let actionsStr = "";
if (summary.actions && Array.isArray(summary.actions)) {
const cleanActions = summary.actions.map(extractText);
actionsStr = cleanActions.join(", ");
}
if (conditionsStr && actionsStr) {
return if ${conditionsStr}, then ${actionsStr};
} else if (conditionsStr) {
return if ${conditionsStr};
} else if (actionsStr) {
return actionsStr;
}
return "";
}
function MenuList({ visible, onEdit, onClone, rule }) {
return (
<ul
style={{
position: "absolute",
backgroundColor: "white",
boxShadow: "0 8px 24px rgba(0, 0, 0, 0.15)",
borderRadius: 6,
padding: "8px 0",
minWidth: 160,
right: 0,
top: 28,
listStyle: "none",
zIndex: 9999,
margin: 0,
opacity: visible ? 1 : 0,
transform: visible
? "translateY(0px) scale(1)"
: "translateY(-10px) scale(0.98)",
transition: "opacity 300ms ease, transform 300ms ease",
pointerEvents: visible ? "auto" : "none",
willChange: "opacity, transform",
}}
>
{[
{ name: "edit", label: "Edit", onClick: onEdit },
{ name: "clone", label: "Clone", onClick: onClone },
{
name: "delete",
label: "Delete",
onClick: () => {
console.log("Delete icon clicked for rule id:", rule.id);
setMenuOpen(false);
openModal();
},
},
].map(({ name, label, onClick }) => (
<li
key={name}
style={{
display: "flex",
alignItems: "center",
gap: 8,
padding: "8px 16px",
cursor: "pointer",
color: "#333",
fontWeight: 500,
userSelect: "none",
backgroundColor: "transparent",
transition: "background-color 0.2s",
}}
onClick={(e) => {
e.stopPropagation();
onClick?.();
setMenuOpen(false);
}}
onMouseEnter={(e) =>
(e.currentTarget.style.backgroundColor = "#f5f7f9")
}
onMouseLeave={(e) =>
(e.currentTarget.style.backgroundColor = "transparent")
}
>
{label}
))}
);
}
return (
<>
<div
className="fw-card-1 fw-flex fw-flex-column"
style={{
overflow: "visible",
border: "0.5px solid #ddd",
backgroundColor: isFirstInGroup ? "#fff" : "#e5f2fd",
cursor: "pointer",
}}
onClick={handleClick}
>
<section
className="fw-flex-grow fw-px-16 fw-flex fw-flex-row"
style={{
justifyContent: "space-between",
alignItems: "center",
marginBottom: "40px",
}}
>
<div
style={{
paddingLeft: "16px",
maxWidth: "80%",
flexBasis: "80%",
flexShrink: 0,
whiteSpace: "normal",
}}
>
{position}. {name}
<p
className="fw-type-xs fw-mt-0 fw-mb-20"
style={{ marginBottom: "10px", fontSize: "14px" }}
>
{generateSummary(rule.summary)}
code Copy code
<div
style={{
display: "flex",
alignItems: "center",
gap: "8px",
padding: "8px 16px",
flexBasis: "20%",
flexShrink: 0,
marginTop: "-50px",
justifyContent: "flex-end",
position: "relative",
}}
>
<FwToggle size="medium" checked={active} />
<div ref={menuContainerRef} style={{ position: "relative" }}>
<div
role="button"
tabIndex={0}
onClick={(e) => {
e.stopPropagation();
setMenuOpen(!menuOpen);
}}
style={{
zIndex: 1,
background: "none",
border: "none",
cursor: "pointer",
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
className="app-icon dropdown-toggle"
>
<path
fillRule="evenodd"
d="M12 5c-1.38 0-2.5-1.12-2.5-2.5S10.62 0 12 0s2.5 1.12 2.5 2.5S13.38 5 12 5zM12 14c-1.38 0-2.5-1.12-2.5-2.5S10.62 9 12 9s2.5 1.12 2.5 2.5S13.38 14 12 14zM12 24c-1.38 0-2.5-1.12-2.5-2.5S10.62 19 12 19s2.5 1.12 2.5 2.5S13.38 24 12 24z"
/>
</svg>
</div>
<MenuList
visible={menuOpen}
onEdit={() => alert("Edit clicked")}
onClone={() => alert("Clone clicked")}
rule={rule}
/>
</div>
</div>
</section>
<section
className="fw-type-xs fw-flex fw-flex-row fw-items-center options"
style={{
background: "#f5f7f9",
padding: "10px 16px",
borderRadius: "5px",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-evenly",
width: "100%",
fontSize: "14px",
color: "#666",
textAlign: "center",
}}
>
<span>
Last Modified: <strong>{calculateLastModified(updated_at)}</strong>
</span>
<span>|</span>
<span>By: {renderAgentName()}</span>
<span>|</span>
<span>Impacted tickets (Last 7 days): {affected_tickets_count}</span>
</div>
</section>
</div>
{/* Delete Confirmation Modal */}
<FwModal
id={`delete-modal-${id}`}
ref={modalRef}
size="small"
submit-color="danger"
submit-text="Delete"
onFwSubmit={(e) => {
e.preventDefault?.();
handleConfirmDelete();
}}
onFwClose={() => {
setShowDeleteModal(false);
if (modalRef.current) modalRef.current.close();
}}
>
<FwModalTitle>
<span>Delete message</span>
</FwModalTitle>
<FwModalContent>
<span>Are you sure you want to delete this Message?</span>
</FwModalContent>
</FwModal>
</>
// ===== AutomationTabs Component =====
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 [errorMessage, setErrorMessage] = useState(null);
const [activeTab, setActiveTab] = useState("ticketcreate");
const [inputState, setInputState] = useState("normal"); // <-- added
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 [currentPage, setCurrentPage] = useState({
ticketcreate: 1,
ticketupdate: 1,
hourly: 1,
});
const toast = useRef(ToastController({ position: "top-center" }));
const newRulePloadDB5 = useRef(null);
const warningTimerRef = useRef(null); // <-- added
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(() => {
if (!loading) {
const timer = setTimeout(() => {
setShowPagination(true);
}, 200);
return () => clearTimeout(timer);
} else {
setShowPagination(false);
}
}, [loading, 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");
code Copy code
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();
// Whenever activeTab changes, reset its page to 1
useEffect(() => {
setCurrentPage((prev) => ({
...prev,
[activeTab]: 1,
}));
code Copy code
if (ruleViewFilter.value === "duplicate_rules") {
setRuleViewFilter(ruleViewOptions[0]); // Reset to 'All Rules' on tab switch
}
// ===== 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]);
useEffect(() => {
const fetchOnTabOrModeChange = async () => {
setLoading(true);
setErrorMessage(null); // clear previous errors
try {
let error = null;
if (fetchFromApi) {
if (activeTab === "ticketcreate") {
error = await getTicketCreationRules(client, setTicketCreationRules);
} else if (activeTab === "ticketupdate") {
error = await getTicketUpdationRules(client, setTicketUpdateRules);
} else if (activeTab === "hourly") {
error = await getHourlyRules(client, setHourlyTriggerRules);
}
await getAgents(client, setAgent); // this can also set errors if you want
} else {
if (!newRulePloadDB5.current) {
console.error("❌ Entity DB reference not initialized.");
setLoading(false);
return;
}
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);
}
}
code Copy code
if (error) {
setErrorMessage(error);
}
} catch (err) {
console.error("Error fetching data:", err);
setErrorMessage("An unexpected error occurred while fetching data.");
}
setLoading(false);
};
if (tabsInitialized && isRulesDBReady) {
fetchOnTabOrModeChange();
}
}, [activeTab, fetchFromApi, client, tabsInitialized, isRulesDBReady]);
const handlePageChange = (tab) => (event) => {
setCurrentPage((prev) => ({
...prev,
[tab]: event.detail.page,
}));
};
useEffect(() => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}, [activeTab]);
useEffect(() => {
const fwTabs = document.querySelector("fw-tabs");
code Copy code
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);
}
};
// const fetchData = async () => {
// if (!fetchFromApi) {
// setSearchTerm("");
// setSearchQuery("");
// setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
// }
// setFetchFromApi((prev) => !prev);
// toast.current.trigger({
// type: "info",
// content: ${fetchFromApi ? "Going Back" : "Fetching Recent Data"}...,
// });
// };
const fetchData = async () => {
code Copy code
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setFetchFromApi((prev) => !prev);
// Toast content depends on current mode before toggling
toast.current.trigger({
type: "info",
content: `${fetchFromApi ? "Going Back" : "Fetching Recent Data"}...`,
});
const checkAndSetButtonState = async () => {
try {
const storedvalue1 = await client.db.get("RulesDB");
const isButtonEnabled = !!storedvalue1.stored;
if (isButtonEnabled) {
setIsRulesDBReady(true);
setLoadingBannerVisible(false);
code Copy code
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;
code Copy code
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 inputRef = useRef(null);
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 }));
code Copy code
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="Type Keyword to Search"
placeholder="Enter a Keyword to Search..."
warning-text="Please Enter a Keyword to Search..."
state={inputState}
clear-input
style={{
width: "400px",
height: "60px",
fontSize: "18px",
}}
value={searchTerm}
onInput={(e) => {
const val = e.target.value;
if (val.length < searchTerm.length) {
setSearchQuery(""); // Clear filter to show all rules
}
setSearchTerm(val);
if (showSearchHint) setShowSearchHint(false);
if (inputState !== "normal") setInputState("normal");
code Copy code
// Clear warning timeout if user starts typing
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setShowSearchHint(false);
setInputState("warning");
// Show warning for 3 seconds
warningTimerRef.current = setTimeout(() => {
setInputState("normal");
warningTimerRef.current = null;
}, 3000);
} else {
setSearchQuery(trimmed);
setShowSearchHint(false);
setInputState("normal");
}
}
}}
onFwClear={() => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
code Copy code
<div style={{ flexShrink: 0 }}>
<FwButton color="primary" onFwClick={() => { /* Add your handler here */ }}>
<fw-icon name="plus" size="16" style={{ marginRight: "8px" }}></fw-icon>
Add New Rule
</FwButton>
</div>
</div>
const getTotalPages = () => {
if (ruleViewFilter.value === "duplicate_rules") {
const groups =
activeTab === "ticketcreate"
? ticketCreationRuleGroups
: activeTab === "ticketupdate"
? ticketUpdateRuleGroups
: hourlyRuleGroups;
code Copy code
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);
}
const renderRulesOrGroups = () => {
let groups = [];
let flatRules = [];
code Copy code
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", boxShadow: "0 4px 8px rgba(0, 0, 0, 0.2)" }}>
{rulesToShow.map((rule, i) => (
<div
key={rule.id}
className="fw-card-1"
style={{
marginTop: i === 0 ? "10px" : "2px",
padding: "5px 8px",
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 {
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>
));
}
const deleteRule = async (rule, allRulesList) => {
console.log("deleteRule called with rule:", rule);
code Copy code
const { id } = rule;
const matchedRecord = allRulesList.find((rec) => rec.id === id);
let automationTypeId;
let currentRules, setRulesFunc, groupSetterFunc, currentTabPage, tabKey;
switch (activeTab) {
case "ticketcreate":
automationTypeId = ticketCreate;
currentRules = ticketCreationRules;
setRulesFunc = setTicketCreationRules;
groupSetterFunc = setTicketCreationRuleGroups;
currentTabPage = currentPage.ticketcreate;
tabKey = "ticketcreate";
break;
case "ticketupdate":
automationTypeId = ticketUpdate;
currentRules = ticketUpdateRules;
setRulesFunc = setTicketUpdateRules;
groupSetterFunc = setTicketUpdateRuleGroups;
currentTabPage = currentPage.ticketupdate;
tabKey = "ticketupdate";
break;
case "hourly":
automationTypeId = hourlyTriggers;
currentRules = hourlyTriggerRules;
setRulesFunc = setHourlyTriggerRules;
groupSetterFunc = setHourlyRuleGroups;
currentTabPage = currentPage.hourly;
tabKey = "hourly";
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) {
// Update rules state after deletion
const updatedRules = currentRules.filter((r) => r.id !== id);
setRulesFunc(updatedRules);
// Clear duplicates group cache if any
groupSetterFunc([]);
// Pagination check: get filtered rules based on current searchQuery & ruleViewFilter
// Here using your getFilteredRules function to apply search filtering
let filteredRules = getFilteredRules(updatedRules);
// Calculate items on current page after deletion
const paginatedItems = pagination(
filteredRules,
currentTabPage
);
// If current page is now empty and not already on first page, go back one page
if (paginatedItems.length === 0 && currentTabPage > 1) {
setCurrentPage((prev) => ({
...prev,
[tabKey]: prev[tabKey] - 1,
}));
}
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);
code Copy code
const duplicateGroups = grouped
.filter((group) => group.length > 1)
.sort((a, b) => b.length - a.length);
console.log("Grouping duplicates for tab: ticketcreate");
console.log("All Ticket Creation Rules:", ticketCreationRules);
console.log("Grouped Rules:", grouped);
console.log("Duplicate Groups (length > 1):", duplicateGroups);
setTicketCreationRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketcreate: 1 }));
} 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("Grouping duplicates for tab: ticketupdate");
console.log("All Ticket Update Rules:", ticketUpdateRules);
console.log("Grouped Rules:", grouped);
console.log("Duplicate Groups (length > 1):", duplicateGroups);
setTicketUpdateRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketupdate: 1 }));
} 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("Grouping duplicates for tab: hourly");
console.log("All Hourly Trigger Rules:", hourlyTriggerRules);
console.log("Grouped Rules:", grouped);
console.log("Duplicate Groups (length > 1):", duplicateGroups);
setHourlyRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, hourly: 1 }));
}
const getPaginatedItemCount = () => {
let rules = [];
if (activeTab === "ticketcreate") rules = ticketCreationRules;
else if (activeTab === "ticketupdate") rules = ticketUpdateRules;
else if (activeTab === "hourly") rules = hourlyTriggerRules;
code Copy code
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 (
<>
{errorMessage ? (
code Copy code
{showSearchHint && (
<p style={{ color: "red", marginTop: "4px", fontSize: "0.9em" }}>
Please enter a search term before searching.
</p>
)}
{loadingBannerVisible && !isRulesDBReady && (
<div
style={{
justifyContent: "center",
alignItems: "center",
height: "40px",
width: "50%",
margin: "0 auto",
}}
>
<FwSpinner size="medium" color="green" />
<span style={{ marginLeft: "8px" }}>Waiting for rules to be ready...</span>
</div>
)}
{tabsInitialized && (
<div style={{ width: "60%", marginRight: "auto" }}>
<div
style={{
display: "flex",
justifyContent: fetchFromApi ? "flex-start" : "flex-end",
marginBottom: 15,
}}
>
<FwButton color="secondary" onFwClick={fetchData} disabled={!isRulesDBReady}>
{fetchFromApi ? (
<>
<FwIcon
slot="before-label"
name="arrow-left"
size={16}
style={{ marginRight: "8px" }}
/>
Back
</>
) : (
<>
Get Recent Data
<FwIcon
slot="after-label"
name="refresh"
size={16}
style={{ marginLeft: "8px" }}
/>
</>
)}
</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>
</div>
)}
</>
)}
<FwToast />
export default AutomationTabs;
<fw-input
ref={inputRef}
icon-left="search"
hint-text="Type Keyword to Search"
placeholder="Enter a Keyword to Search..."
warning-text="Please Enter a Keyword to Search..."
state={inputState}
clear-input
style={{
width: "400px",
height: "60px",
fontSize: "18px",
}}
value={searchTerm}
onInput={(e) => {
const val = e.target.value;
if (val.length < searchTerm.length) {
setSearchQuery(""); // Clear filter to show all rules
}
setSearchTerm(val);
if (showSearchHint) setShowSearchHint(false);
if (inputState !== "normal") setInputState("normal");
// Clear warning timeout if user starts typing
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setShowSearchHint(false);
setInputState("warning");
// Show warning for 3 seconds
warningTimerRef.current = setTimeout(() => {
setInputState("normal");
warningTimerRef.current = null;
}, 3000);
} else {
setSearchQuery(trimmed);
setShowSearchHint(false);
setInputState("normal");
}
}
}}
/>
Why does this fix your issue?
Web components like <fw-input> dispatch custom DOM events (like fwClear) that React doesn't automatically map to prop handlers.
Using a React prop such as onFwClear doesn't properly catch that event.
Manually attaching event listeners on the native DOM node with addEventListener("fwClear", handler) reliably catches clear events.
This lets you update your React state properly on clear, so filtering resets and the UI immediately updates.
Summary
Remove your current onFwClear prop on <fw-input>.
Add the native event listener in useEffect.
Keep your other state update logic as is.
If you want me, I can provide you a complete minimal code snippet with this fix incorporated from start to finish. Just ask!
Explanation:
The key fix is in the useEffect hooks which attach a native "fwClear" event listener to the actual DOM element referenced by inputRef.
When the clear button is clicked, onClear runs and clears both searchTerm and searchQuery and resets the pagination page state.
This ensures the filter resets and all rules are shown.
The onInput handler updates searchTerm live and also clears searchQuery when deleting characters, triggering showing all rules again.
onKeyDown handles Enter key for search execution.
This minimal snippet should be straightforward to integrate in your AutomationTabs component for reliable search clearing.
If you want, I can also help you merge this into your full component code!
// Main normalized signature function combining conditions, actions, and operator
const getRuleSignatureNormalized = (rule) => {
const rawConditions = rule.summary?.conditions || rule.conditions || "";
const rawActions = rule.summary?.actions || rule.actions || "";
const operator = rule.operator || "";
const { set1, set2 } = normalizeConditionParts(rawConditions);
const normalizedActions = normalizeActions(rawActions);
const normalizedOperator = cleanText(operator);
// The signature should consider the fact conditions might be interchangeable
// between set1 and set2 (commutative)
const key1 = JSON.stringify({ set1, set2, actions: normalizedActions, operator: normalizedOperator });
const key2 = JSON.stringify({ set1: set2, set2: set1, actions: normalizedActions, operator: normalizedOperator });
// Return lexicographically smallest key for commutative sets
return key1 < key2 ? key1 : key2;
};
// Group duplicates by normalized signature
const groupDuplicates = (rules) => {
const groups = {};
rules
.filter((rule) => rule.active === "true" || rule.active === true) // handle boolean or string "true"
.forEach((rule) => {
const signature = getRuleSignatureNormalized(rule);
if (!groups[signature]) groups[signature] = [];
groups[signature].push(rule);
});
return Object.values(groups);
};
// export { groupDuplicates, getRuleSignatureNormalized };
// 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 [];
// }
// };
// ===== AutomationCard Component Inlined =====
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 };
code Copy code
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);
// Sort by `position` ascending before returning
allRecords.sort((a, b) => {
// If position undefined/missing, treat as larger - push to bottom
const posA = typeof a.position === "number" ? a.position : Number.MAX_SAFE_INTEGER;
const posB = typeof b.position === "number" ? b.position : Number.MAX_SAFE_INTEGER;
return posA - posB;
});
console.log(`✅ Filtered Records for Type ${automationTypeId}:`, allRecords);
return allRecords;
} catch (error) {
console.error("❌ Error fetching filtered records:", error);
return [];
}
};
const calculateLastModified = (updated_at) => {
const updatedDate = new Date(updated_at);
const currentDate = new Date();
const diffInMilliseconds = currentDate - updatedDate;
const seconds = Math.floor(diffInMilliseconds / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
const months = Math.floor(days / 30);
const years = Math.floor(days / 365);
if (years > 0) return years === 1 ? "a year ago" : ${years} years ago;
if (months > 0) return months === 1 ? "a month ago" : ${months} months ago;
if (days > 0) return ${days} day${days > 1 ? "s" : ""} ago;
if (hours > 0) return ${hours} hour${hours > 1 ? "s" : ""} ago;
if (minutes > 0) return ${minutes} minute${minutes > 1 ? "s" : ""} ago;
return "Just now";
};
const AutomationCard = ({
rule = {},
index,
isFirstInGroup = false,
onDelete,
agent,
activeTab,
onSelect,
}) => {
const {
id,
name = "Default Rule Name",
summary = "",
description = "",
updated_at = "N/A",
last_updated_by = "Unknown",
affected_tickets_count = "--",
active = false,
position,
automation_type_id,
} = rule;
const [menuOpen, setMenuOpen] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const modalRef = useRef(null);
const menuContainerRef = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (
menuContainerRef.current &&
!menuContainerRef.current.contains(event.target)
) {
setMenuOpen(false);
}
};
code Copy code
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
// Imperatively open modal if showDeleteModal became true
useEffect(() => {
if (showDeleteModal && modalRef.current) {
modalRef.current.open();
}
}, [showDeleteModal]);
const openModal = () => setShowDeleteModal(true);
const closeModal = () => {
setShowDeleteModal(false);
if (modalRef.current) modalRef.current.close();
};
const handleConfirmDelete = () => {
closeModal();
if (onDelete) onDelete(rule);
};
const handleClick = () => {
if (onSelect) {
onSelect(rule);
}
};
const renderAgentName = () => {
if (rule.agentName) {
return rule.agentName;
}
if (!agent || !Array.isArray(agent)) {
return last_updated_by || "Unknown";
} else {
const foundAgent = agent.find((e) => e.value === last_updated_by);
return foundAgent ? foundAgent.text : last_updated_by || "Unknown";
}
};
function extractText(htmlString) {
if (!htmlString || typeof htmlString !== "string") return "";
let text = htmlString.replace(/<[^>]+>/g, "").trim();
if (text.toLowerCase().startsWith("if ")) {
text = text.substring(3).trim();
}
return text.toLowerCase();
}
function generateSummary(summary) {
if (!summary) return "";
if (typeof summary === "string") {
return summary;
}
let conditionTexts = [];
if (summary.conditions) {
for (const setKey in summary.conditions) {
if (Object.prototype.hasOwnProperty.call(summary.conditions, setKey)) {
const conditionsVal = summary.conditions[setKey];
const conditionsArray = Array.isArray(conditionsVal)
? conditionsVal
: [conditionsVal];
const cleanConditions = conditionsArray.map(extractText);
conditionTexts.push(cleanConditions.join(", "));
}
}
}
const conditionsStr = conditionTexts.join(", ");
let actionsStr = "";
if (summary.actions && Array.isArray(summary.actions)) {
const cleanActions = summary.actions.map(extractText);
actionsStr = cleanActions.join(", ");
}
if (conditionsStr && actionsStr) {
return if ${conditionsStr}, then ${actionsStr};
} else if (conditionsStr) {
return if ${conditionsStr};
} else if (actionsStr) {
return actionsStr;
}
return "";
}
function MenuList({ visible, onEdit, onClone, rule }) {
return (
<ul
style={{
position: "absolute",
backgroundColor: "white",
boxShadow: "0 8px 24px rgba(0, 0, 0, 0.15)",
borderRadius: 6,
padding: "8px 0",
minWidth: 160,
right: 0,
top: 28,
listStyle: "none",
zIndex: 9999,
margin: 0,
opacity: visible ? 1 : 0,
transform: visible
? "translateY(0px) scale(1)"
: "translateY(-10px) scale(0.98)",
transition: "opacity 300ms ease, transform 300ms ease",
pointerEvents: visible ? "auto" : "none",
willChange: "opacity, transform",
}}
>
{[
{ name: "edit", label: "Edit", onClick: onEdit },
{ name: "clone", label: "Clone", onClick: onClone },
{
name: "delete",
label: "Delete",
onClick: () => {
console.log("Delete icon clicked for rule id:", rule.id);
setMenuOpen(false);
openModal();
},
},
].map(({ name, label, onClick }) => (
<li
key={name}
style={{
display: "flex",
alignItems: "center",
gap: 8,
padding: "8px 16px",
cursor: "pointer",
color: "#333",
fontWeight: 500,
userSelect: "none",
backgroundColor: "transparent",
transition: "background-color 0.2s",
}}
onClick={(e) => {
e.stopPropagation();
onClick?.();
setMenuOpen(false);
}}
onMouseEnter={(e) =>
(e.currentTarget.style.backgroundColor = "#f5f7f9")
}
onMouseLeave={(e) =>
(e.currentTarget.style.backgroundColor = "transparent")
}
>
{label}
))}
);
}
return (
<>
<div
className="fw-card-1 fw-flex fw-flex-column"
style={{
overflow: "visible",
border: "0.5px solid #ddd",
backgroundColor: isFirstInGroup ? "#fff" : "#e5f2fd",
cursor: "pointer",
}}
onClick={handleClick}
>
<section
className="fw-flex-grow fw-px-16 fw-flex fw-flex-row"
style={{
justifyContent: "space-between",
alignItems: "center",
marginBottom: "40px",
}}
>
<div
style={{
paddingLeft: "16px",
maxWidth: "80%",
flexBasis: "80%",
flexShrink: 0,
whiteSpace: "normal",
}}
>
{position}. {name}
<p
className="fw-type-xs fw-mt-0 fw-mb-20"
style={{ marginBottom: "10px", fontSize: "14px" }}
>
{generateSummary(rule.summary)}
code Copy code
<div
style={{
display: "flex",
alignItems: "center",
gap: "8px",
padding: "8px 16px",
flexBasis: "20%",
flexShrink: 0,
marginTop: "-50px",
justifyContent: "flex-end",
position: "relative",
}}
>
<FwToggle size="medium" checked={active} />
<div ref={menuContainerRef} style={{ position: "relative" }}>
<div
role="button"
tabIndex={0}
onClick={(e) => {
e.stopPropagation();
setMenuOpen(!menuOpen);
}}
style={{
zIndex: 1,
background: "none",
border: "none",
cursor: "pointer",
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
className="app-icon dropdown-toggle"
>
<path
fillRule="evenodd"
d="M12 5c-1.38 0-2.5-1.12-2.5-2.5S10.62 0 12 0s2.5 1.12 2.5 2.5S13.38 5 12 5zM12 14c-1.38 0-2.5-1.12-2.5-2.5S10.62 9 12 9s2.5 1.12 2.5 2.5S13.38 14 12 14zM12 24c-1.38 0-2.5-1.12-2.5-2.5S10.62 19 12 19s2.5 1.12 2.5 2.5S13.38 24 12 24z"
/>
</svg>
</div>
<MenuList
visible={menuOpen}
onEdit={() => alert("Edit clicked")}
onClone={() => alert("Clone clicked")}
rule={rule}
/>
</div>
</div>
</section>
<section
className="fw-type-xs fw-flex fw-flex-row fw-items-center options"
style={{
background: "#f5f7f9",
padding: "10px 16px",
borderRadius: "5px",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-evenly",
width: "100%",
fontSize: "14px",
color: "#666",
textAlign: "center",
}}
>
<span>
Last Modified: <strong>{calculateLastModified(updated_at)}</strong>
</span>
<span>|</span>
<span>By: {renderAgentName()}</span>
<span>|</span>
<span>Impacted tickets (Last 7 days): {affected_tickets_count}</span>
</div>
</section>
</div>
{/* Delete Confirmation Modal */}
<FwModal
id={`delete-modal-${id}`}
ref={modalRef}
size="small"
submit-color="danger"
submit-text="Delete"
onFwSubmit={(e) => {
e.preventDefault?.();
handleConfirmDelete();
}}
onFwClose={() => {
setShowDeleteModal(false);
if (modalRef.current) modalRef.current.close();
}}
>
<FwModalTitle>
<span>Delete message</span>
</FwModalTitle>
<FwModalContent>
<span>Are you sure you want to delete this Message?</span>
</FwModalContent>
</FwModal>
</>
// ===== AutomationTabs Component =====
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 inputRef = useRef(null);
const [errorMessage, setErrorMessage] = useState(null);
const [activeTab, setActiveTab] = useState("ticketcreate");
const [inputState, setInputState] = useState("normal"); // <-- added
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 [currentPage, setCurrentPage] = useState({
ticketcreate: 1,
ticketupdate: 1,
hourly: 1,
});
const toast = useRef(ToastController({ position: "top-center" }));
const newRulePloadDB5 = useRef(null);
const warningTimerRef = useRef(null); // <-- added
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(() => {
if (!loading) {
const timer = setTimeout(() => {
setShowPagination(true);
}, 200);
return () => clearTimeout(timer);
} else {
setShowPagination(false);
}
}, [loading, 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");
code Copy code
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();
// Whenever activeTab changes, reset its page to 1
useEffect(() => {
setCurrentPage((prev) => ({
...prev,
[activeTab]: 1,
}));
code Copy code
if (ruleViewFilter.value === "duplicate_rules") {
setRuleViewFilter(ruleViewOptions[0]); // Reset to 'All Rules' on tab switch
}
// ===== 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]);
useEffect(() => {
if (inputRef.current) {
const onClear = () => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
code Copy code
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
};
inputRef.current.addEventListener("fwClear", onClear);
return () => {
if (inputRef.current) {
inputRef.current.removeEventListener("fwClear", onClear);
}
};
}
useEffect(() => {
const fetchOnTabOrModeChange = async () => {
setLoading(true);
setErrorMessage(null); // clear previous errors
try {
let error = null;
if (fetchFromApi) {
if (activeTab === "ticketcreate") {
error = await getTicketCreationRules(client, setTicketCreationRules);
} else if (activeTab === "ticketupdate") {
error = await getTicketUpdationRules(client, setTicketUpdateRules);
} else if (activeTab === "hourly") {
error = await getHourlyRules(client, setHourlyTriggerRules);
}
await getAgents(client, setAgent); // this can also set errors if you want
} else {
if (!newRulePloadDB5.current) {
console.error("❌ Entity DB reference not initialized.");
setLoading(false);
return;
}
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);
}
}
code Copy code
if (error) {
setErrorMessage(error);
}
} catch (err) {
console.error("Error fetching data:", err);
setErrorMessage("An unexpected error occurred while fetching data.");
}
setLoading(false);
};
if (tabsInitialized && isRulesDBReady) {
fetchOnTabOrModeChange();
}
}, [activeTab, fetchFromApi, client, tabsInitialized, isRulesDBReady]);
const handlePageChange = (tab) => (event) => {
setCurrentPage((prev) => ({
...prev,
[tab]: event.detail.page,
}));
};
useEffect(() => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}, [activeTab]);
useEffect(() => {
const fwTabs = document.querySelector("fw-tabs");
code Copy code
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);
}
};
// const fetchData = async () => {
// if (!fetchFromApi) {
// setSearchTerm("");
// setSearchQuery("");
// setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
// }
// setFetchFromApi((prev) => !prev);
// toast.current.trigger({
// type: "info",
// content: ${fetchFromApi ? "Going Back" : "Fetching Recent Data"}...,
// });
// };
const fetchData = async () => {
code Copy code
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setFetchFromApi((prev) => !prev);
// Toast content depends on current mode before toggling
toast.current.trigger({
type: "info",
content: `${fetchFromApi ? "Going Back" : "Fetching Recent Data"}...`,
});
const checkAndSetButtonState = async () => {
try {
const storedvalue1 = await client.db.get("RulesDB");
const isButtonEnabled = !!storedvalue1.stored;
if (isButtonEnabled) {
setIsRulesDBReady(true);
setLoadingBannerVisible(false);
code Copy code
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;
code Copy code
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 inputRef = useRef(null);
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 }));
code Copy code
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="Type Keyword to Search"
placeholder="Enter a Keyword to Search..."
warning-text="Please Enter a Keyword to Search..."
state={inputState}
clear-input
style={{ width: "400px", height: "60px", fontSize: "18px" }}
value={searchTerm}
onInput={(e) => {
const val = e.target.value;
if (val.length < searchTerm.length) {
setSearchQuery(""); // Clear filter to show all rules when deleting chars
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}
setSearchTerm(val);
if (inputState !== "normal") setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setInputState("warning");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
warningTimerRef.current = setTimeout(() => {
setInputState("normal");
warningTimerRef.current = null;
}, 3000);
} else {
setSearchQuery(trimmed);
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
}
}
}}
/>
code Copy code
<div style={{ flexShrink: 0 }}>
<FwButton color="primary" onFwClick={() => { /* Add your handler here */ }}>
<fw-icon name="plus" size="16" style={{ marginRight: "8px" }}></fw-icon>
Add New Rule
</FwButton>
</div>
</div>
const getTotalPages = () => {
if (ruleViewFilter.value === "duplicate_rules") {
const groups =
activeTab === "ticketcreate"
? ticketCreationRuleGroups
: activeTab === "ticketupdate"
? ticketUpdateRuleGroups
: hourlyRuleGroups;
code Copy code
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);
}
const renderRulesOrGroups = () => {
let groups = [];
let flatRules = [];
code Copy code
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", boxShadow: "0 4px 8px rgba(0, 0, 0, 0.2)" }}>
{rulesToShow.map((rule, i) => (
<div
key={rule.id}
className="fw-card-1"
style={{
marginTop: i === 0 ? "10px" : "2px",
padding: "5px 8px",
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 {
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>
));
}
const deleteRule = async (rule, allRulesList) => {
console.log("deleteRule called with rule:", rule);
code Copy code
const { id } = rule;
const matchedRecord = allRulesList.find((rec) => rec.id === id);
let automationTypeId;
let currentRules, setRulesFunc, groupSetterFunc, currentTabPage, tabKey;
switch (activeTab) {
case "ticketcreate":
automationTypeId = ticketCreate;
currentRules = ticketCreationRules;
setRulesFunc = setTicketCreationRules;
groupSetterFunc = setTicketCreationRuleGroups;
currentTabPage = currentPage.ticketcreate;
tabKey = "ticketcreate";
break;
case "ticketupdate":
automationTypeId = ticketUpdate;
currentRules = ticketUpdateRules;
setRulesFunc = setTicketUpdateRules;
groupSetterFunc = setTicketUpdateRuleGroups;
currentTabPage = currentPage.ticketupdate;
tabKey = "ticketupdate";
break;
case "hourly":
automationTypeId = hourlyTriggers;
currentRules = hourlyTriggerRules;
setRulesFunc = setHourlyTriggerRules;
groupSetterFunc = setHourlyRuleGroups;
currentTabPage = currentPage.hourly;
tabKey = "hourly";
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) {
// Update rules state after deletion
const updatedRules = currentRules.filter((r) => r.id !== id);
setRulesFunc(updatedRules);
// Clear duplicates group cache if any
groupSetterFunc([]);
// Pagination check: get filtered rules based on current searchQuery & ruleViewFilter
// Here using your getFilteredRules function to apply search filtering
let filteredRules = getFilteredRules(updatedRules);
// Calculate items on current page after deletion
const paginatedItems = pagination(
filteredRules,
currentTabPage
);
// If current page is now empty and not already on first page, go back one page
if (paginatedItems.length === 0 && currentTabPage > 1) {
setCurrentPage((prev) => ({
...prev,
[tabKey]: prev[tabKey] - 1,
}));
}
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);
code Copy code
const duplicateGroups = grouped
.filter((group) => group.length > 1)
.sort((a, b) => b.length - a.length);
console.log("Grouping duplicates for tab: ticketcreate");
console.log("All Ticket Creation Rules:", ticketCreationRules);
console.log("Grouped Rules:", grouped);
console.log("Duplicate Groups (length > 1):", duplicateGroups);
setTicketCreationRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketcreate: 1 }));
} 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("Grouping duplicates for tab: ticketupdate");
console.log("All Ticket Update Rules:", ticketUpdateRules);
console.log("Grouped Rules:", grouped);
console.log("Duplicate Groups (length > 1):", duplicateGroups);
setTicketUpdateRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, ticketupdate: 1 }));
} 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("Grouping duplicates for tab: hourly");
console.log("All Hourly Trigger Rules:", hourlyTriggerRules);
console.log("Grouped Rules:", grouped);
console.log("Duplicate Groups (length > 1):", duplicateGroups);
setHourlyRuleGroups(duplicateGroups);
setCurrentPage((prev) => ({ ...prev, hourly: 1 }));
}
const getPaginatedItemCount = () => {
let rules = [];
if (activeTab === "ticketcreate") rules = ticketCreationRules;
else if (activeTab === "ticketupdate") rules = ticketUpdateRules;
else if (activeTab === "hourly") rules = hourlyTriggerRules;
code Copy code
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 (
<>
{errorMessage ? (
code Copy code
{showSearchHint && (
<p style={{ color: "red", marginTop: "4px", fontSize: "0.9em" }}>
Please enter a search term before searching.
</p>
)}
{loadingBannerVisible && !isRulesDBReady && (
<div
style={{
justifyContent: "center",
alignItems: "center",
height: "40px",
width: "50%",
margin: "0 auto",
}}
>
<FwSpinner size="medium" color="green" />
<span style={{ marginLeft: "8px" }}>Waiting for rules to be ready...</span>
</div>
)}
{tabsInitialized && (
<div style={{ width: "60%", marginRight: "auto" }}>
<div
style={{
display: "flex",
justifyContent: fetchFromApi ? "flex-start" : "flex-end",
marginBottom: 15,
}}
>
<FwButton color="secondary" onFwClick={fetchData} disabled={!isRulesDBReady}>
{fetchFromApi ? (
<>
<FwIcon
slot="before-label"
name="arrow-left"
size={16}
style={{ marginRight: "8px" }}
/>
Back
</>
) : (
<>
Get Recent Data
<FwIcon
slot="after-label"
name="refresh"
size={16}
style={{ marginLeft: "8px" }}
/>
</>
)}
</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>
</div>
)}
</>
)}
<FwToast />
export default AutomationTabs;
<fw-input
ref={inputRef}
icon-left="search"
hint-text="Type Keyword to Search"
placeholder="Enter a Keyword to Search..."
warning-text="Please Enter a Keyword to Search..."
state={inputState}
clear-input
style={{ width: "400px", height: "60px", fontSize: "18px" }}
value={searchTerm}
onInput={(e) => {
const val = e.target.value;
if (val.length < searchTerm.length) {
setSearchQuery(""); // clear filter as user deletes characters
setCurrentPage(prev => ({ ...prev, [activeTab]: 1 }));
}
setSearchTerm(val);
if (inputState !== "normal") setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setInputState("warning");
setCurrentPage(prev => ({ ...prev, [activeTab]: 1 }));
warningTimerRef.current = setTimeout(() => {
setInputState("normal");
warningTimerRef.current = null;
}, 3000);
} else {
setSearchQuery(trimmed);
setCurrentPage(prev => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
}
}
}}
/>
Why this works:
The native "fwClear" event fires when the clear button is clicked.
The event listener updates searchQuery to empty string, which actually controls filtering , thus resetting the filter.
Resetting currentPage back to 1 ensures your pagination stays consistent.
This guarantees the rules data is re-filtered with an empty query (i.e., no filter) after clear is clicked.
Summary Replace your existing onFwClear handler on the input with the above useEffect based approach attaching native event listeners. Always reset both searchTerm and searchQuery inside the event handler.
If you want, I can help you create a complete snippet or diff with your full code integrated with this fix. Let me know!
import React, { useState, useEffect, useRef } from "react";
// ... other imports ...
const AutomationTabs = ({ client }) => {
// ... your existing state and refs like searchTerm, searchQuery, currentPage, etc. ...
const inputRef = useRef(null);
// Attach native fwClear event listener on fw-input web component
useEffect(() => {
const inputEl = inputRef.current;
if (!inputEl) return;
const onClear = () => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
};
inputEl.addEventListener("fwClear", onClear);
return () => {
inputEl.removeEventListener("fwClear", onClear);
};
}, [activeTab]);
// ... your existing code ...
const searchInputs = (
<div
style={{
display: "flex",
alignItems: "center",
marginBottom: 10,
marginLeft: 20,
marginTop: 15,
maxWidth: "100%",
gap: "20px",
}}
>
{/* "All Rules" button and other UI components */}
<div style={{ flex: 1, display: "flex", justifyContent: "center", marginTop: 20 }}>
<fw-input
ref={inputRef} // <-- Add this ref here
icon-left="search"
hint-text="Type Keyword to Search"
placeholder="Enter a Keyword to Search..."
warning-text="Please Enter a Keyword to Search..."
state={inputState}
clear-input
style={{ width: "400px", height: "60px", fontSize: "18px" }}
value={searchTerm}
onInput={(e) => {
const val = e.target.value;
if (val.length < searchTerm.length) {
// Reset filter if user deletes characters
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}
setSearchTerm(val);
if (inputState !== "normal") setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setInputState("warning");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
warningTimerRef.current = setTimeout(() => {
setInputState("normal");
warningTimerRef.current = null;
}, 3000);
} else {
setSearchQuery(trimmed);
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
}
}
}}
/>
</div>
{/* Add New Rule button etc. */}
</div>
);
// ...rest of your component code
};
export default AutomationTabs;
What was changed/added?
Introduced inputRef assignment on <fw-input>.
Attached native DOM listener fwClear to call cleanup function resetting:
searchTerm to empty string,
searchQuery to empty string,
pagination page for current tab to 1,
input state to "normal".
Removed the erroneous or non-working onFwClear JSX prop (so it's not in the <fw-input> tag).
You keep filtering based on searchQuery state in your getFilteredRules function as you already do.
This will ensure:
When user clicks the clear x button in the input:
The input visibly clears.
Your filter state searchQuery clears synchronously.
Pagination resets to first page.
The UI re-renders, showing all rules again (no filter).
If you want me to generate a full diff or full integrated file just let me know!
<fw-input
ref={inputRef}
icon-left="search"
hint-text="Type Keyword to Search"
placeholder="Enter a Keyword to Search..."
warning-text="Please Enter a Keyword to Search..."
state={inputState}
clear-input
style={{
width: "400px",
height: "60px",
fontSize: "18px",
}}
value={searchTerm}
onInput={(e) => {
const val = e.target.value;
if (val.length < searchTerm.length) {
setSearchQuery(""); // Clear filter to show all rules when deleting chars
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}
setSearchTerm(val);
if (inputState !== "normal") setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setInputState("warning");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
warningTimerRef.current = setTimeout(() => {
setInputState("normal");
warningTimerRef.current = null;
}, 3000);
} else {
setSearchQuery(trimmed);
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
}
}
}}
/>
What this fix does:
Uses a native DOM event listener to listen for the fwClear event fired by the web component when the clear button is clicked.
Clears both searchTerm state and searchQuery state to reset the filter properly.
Resets the pagination page to 1.
Corrects the input state to "normal".
Add these 3 parts to your existing AutomationTabs component and it will fix your problem where clicking the clear button (x) clears the input text but doesn't reset the filtering.
If you want, I can explain how to integrate this step-by-step or generate a diff for you.
<fw-input
icon-left="search"
hint-text="Type Keyword to Search"
placeholder="Enter a Keyword to Search..."
warning-text="Please Enter a Keyword to Search..."
state={inputState}
clear-input
style={{ width: "400px", height: "60px", fontSize: "18px" }}
value={searchTerm}
onInput={(e) => {
const val = e.target.value;
// Detect if input cleared (empty string)
if (val === "") {
setSearchQuery(""); // Reset filter state
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
}
// If user deletes characters (shorter input), reset searchQuery immediately
else if (val.length < searchTerm.length) {
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}
setSearchTerm(val);
if (inputState !== "normal") setInputState("normal");
if (warningTimerRef.current) {
clearTimeout(warningTimerRef.current);
warningTimerRef.current = null;
}
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setInputState("warning");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
warningTimerRef.current = setTimeout(() => {
setInputState("normal");
warningTimerRef.current = null;
}, 3000);
} else {
setSearchQuery(trimmed);
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
setInputState("normal");
}
}
}}
/>
Step 3 - Remove any separate event listeners for fwClear or onFwClear.
Why this works reliably:
The clear-input button clears the visible input but the internal value change triggers onInput.
By detecting val === "" inside the onInput handler, you reliably see when the user cleared input either manually or via clear button.
Then you reset the React filtering state properly.
React stays “in control” of the input.
Summary:
Use the onInput event to detect clearing instead of relying on fwClear custom event.
When input is cleared (val === ""), clear the filter state and pagination.
This avoids dependency on custom event support and ensures React state and UI stay in sync.
If you want, I can provide you a full minimal sample component with just this part integrated for your local testing. Would you like that?