Explore / Programming in this code, consider this scenario : if im in entity and search a word, then when i… Save Share Download ▾ ReportJump to turn (20) 1 in this code, consider this scenario : if im in entity and search a word, then w 2 const AutomationCard = ({ rule = {}, index, isFirstInGroup = false, onDelete, ag 3 give me the complete 4 give what to add 5 yesssss 6 im gonna use this in automationtab.js so no export 7 no modal is showing 8 full replacement automationcard code. also to ensure delete icon is clicked add 9 export async function getTicketCreationRules(client, setState) { try { let creat 10 return ( <> Automations - Rules {showSearchHint && ( Please enter a search term 11 it should be under 12 const fetchData = async () => { if (!fetchFromApi) { setSearchTerm(""); setSearc 13 same it should perfor searchquer to empty when switching from api to back (entit 14 const findDuplicateRulestype1and3 = (records) => { const seenRules = new Map(); 15 // Utility: clean and normalize text const cleanText = (text) => String(text || 16 const findDuplicateRulestype1and3 = (records) => { const seenRules = new Map(); 17 // Group duplicates by normalized signature const groupDuplicates = (rules) => { 18 give me full snippet 19 [ { "name": "simple", "position": 1, "active": true, "outdated": false, "lastupd 20 yes Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 20 (40 messages)
Language en
Conversation date May 9, 2025
Added to archive Nov 16, 2026
ID 01m7h42sayr5sggd53s3b87byrSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 80e56ecee62a16997ff400f2f2b7b192
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
in this code, consider this scenario : if im in entity and search a word, then when i click Recent Data the search should rest
also. when i type in search in that i have x when user clicks that also should remove the search keyword
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);
// Create a ref for the dropdown container
const menuContainerRef = useRef(null);
// Listen for clicks outside the menu container to close the menu
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);
}, []);
const handleConfirmDelete = () => {
setShowDeleteModal(false);
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 "";
}
// Dropdown Menu Component (inline styling with animation)
function MenuList({ visible, onEdit, onClone, onDelete, 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: () => {
setMenuOpen(false);
if (onDelete) onDelete(rule);
},
},
].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"
></path>
</svg>
</div>
<MenuList
visible={menuOpen}
onEdit={() => alert("Edit clicked")}
onClone={() => alert("Clone clicked")}
onDelete={handleConfirmDelete}
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>
<div>
<FwModal id="composition" size="small" submit-color="danger" submit-text="Delete">
<FwModalTitle>
<span>Delete message</span>
</FwModalTitle>
<FwModalContent>
<span>Are you sure you want to delete this Message?</span>
</FwModalContent>
</FwModal>
</div>
</>
);
};
// ===== 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 [activeTab, setActiveTab] = useState("ticketcreate");
const [tabsInitialized, setTabsInitialized] = useState(false);
const modalRef = useRef(null);
const [ticketCreationRules, setTicketCreationRules] = useState([]);
const [ticketUpdateRules, setTicketUpdateRules] = useState([]);
const [hourlyTriggerRules, setHourlyTriggerRules] = useState([]);
const [loading, setLoading] = useState(false);
const [agent, setAgent] = useState([]);
// const [ruleViewFilter, setRuleViewFilter] = useState(ruleViewOptions[0]);
const rulesPerPage = 30;
const [currentPage, setCurrentPage] = useState({
ticketcreate: 1,
ticketupdate: 1,
hourly: 1,
});
const toast = useRef(ToastController({ position: "top-center" }));
const newRulePloadDB5 = useRef(null);
const ticketCreate = 1;
const ticketUpdate = 4;
const hourlyTriggers = 3;
// ===== CHANGE: initial fetchFromApi to false to fetch entity data initially =====
const [fetchFromApi, setFetchFromApi] = useState(false);
const [showPagination, setShowPagination] = useState(false);
// ======= Grouped state arrays to hold duplicate groups =======
const [ticketCreationRuleGroups, setTicketCreationRuleGroups] = useState([]);
const [ticketUpdateRuleGroups, setTicketUpdateRuleGroups] = useState([]);
const [hourlyRuleGroups, setHourlyRuleGroups] = useState([]);
// =============================================================
// ----- NEW: rule view filter for 'All Rules' or 'Duplicate Rules' -----
const ruleViewOptions = [
{
value: "all_rules",
text: "All Rules",
graphicsProps: { name: "list" },
},
{
value: "duplicate_rules",
text: "Duplicate Rules",
graphicsProps: { name: "warning" },
},
];
const [ruleViewFilter, setRuleViewFilter] = useState(ruleViewOptions[0]);
// ---------------------------------------------------------------------
useEffect(() => {
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);
};
code Copy code
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 () => {
setFetchFromApi((prev) => !prev);
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"
warning-text="Please use numbers for user ID"
placeholder="Enter a Keyword to Search..."
error-text="Invalid user ID"
clear-input
style={{
width: "400px",
height: "60px",
fontSize: "18px",
}}
value={searchTerm} // controlled value bound here
onInput={(e) => {
const val = e.target.value;
// If user cleared or removed characters, reset searchQuery to show all rules:
if (val.length < searchTerm.length) {
setSearchQuery(""); // Clear filter to show all rules
}
setSearchTerm(val);
if (showSearchHint) setShowSearchHint(false);
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setShowSearchHint(false);
} else {
setSearchQuery(trimmed); // Apply search on Enter
setShowSearchHint(false);
}
}
}}
/>
</div>
{/* "Add New Rule" button aligned right */}
<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
);
};
export default AutomationTabs;
Show full message · 1,445 lines Assistant2025-05-09 04:50 UTC Copy response
To implement the behavior you described:
When "Recent Data" button is clicked, if you're on the entity data mode (fetchFromApi false), reset the search input and clear any search query.
When the user clicks the clear (x) button on the search input, clear the searchTerm and searchQuery to show all results.
Changes needed:
Reset search on "Recent Data" button click:
In your fetchData function, add logic to clear the search state when switching from entity to API mode or when clicking "Get Recent Data" from entity mode :
js Copy code
const fetchData = async () => {
// If we are currently fetching entity data (fetchFromApi is false), clicking "Get Recent Data" will set fetchFromApi to true
// So, reset search here
if (!fetchFromApi) {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}
setFetchFromApi((prev) => !prev);
toast.current.trigger({
type: "info",
content: `${fetchFromApi ? "Going Back" : "Fetching Recent Data"}...`,
});
};
Reset search when clicking the clear (x) on the input:
Your search input is <fw-input> with clear-input attribute, but no handler is attached for the clear event.
You can add an event handler for the input's clear event. The Freshworks Crayons <fw-input> fires a fwClear event when the clear (x) icon is clicked.
Modify your search input as:
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);
// Create a ref for the dropdown container
const menuContainerRef = useRef(null);
// Listen for clicks outside the menu container to close the menu
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);
}, []);
const handleConfirmDelete = () => {
setShowDeleteModal(false);
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 "";
}
// Dropdown Menu Component (inline styling with animation)
function MenuList({ visible, onEdit, onClone, onDelete, 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: () => {
setMenuOpen(false);
if (onDelete) onDelete(rule);
},
},
].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}
))}
);
}
Show full message · 323 lines Assistant2025-05-09 04:56 UTC Copy response
To implement showing the <FwModal> confirmation dialog on clicking Delete in your AutomationCard, and then trigger the real deletion after user confirms (modal's fwSubmit event), here’s what you can do:
Key goals:
When user clicks Delete from dropdown menu, open the modal instead of immediately deleting.
When modal confirmation (Delete button in the modal) fires fwSubmit, call the onDelete callback to perform actual deletion.
Close the modal on submit.
Pass the rule to delete properly.
Step-by-step implementation:
1. Modify AutomationCard for modal control
You already have showDeleteModal state — use that to control modal opening.
2. Change delete menu item click to open modal instead of immediately deleting
Replace the existing onClick delete handler in MenuList so it sets showDeleteModal(true) instead of calling onDelete.
3. Render <FwModal> in AutomationCard, controlled by showDeleteModal with handlers:
onFwOpen and onFwClose event handlers to toggle showDeleteModal state properly (mostly onFwClose).
onFwSubmit handler calls onDelete(rule) and closes modal.
4. Important: You need to listen for modal events: React uses onFwSubmit, onFwOpen, and onFwClose as props on <FwModal>
Here is your updated relevant code snippets:
Assistant2025-05-09 05:36 UTC Copy response
Certainly! Below is the complete revised AutomationCard component with the fully integrated delete confirmation modal as you requested:
Show full message · 357 lines Assistant2025-05-09 05:40 UTC Copy response
To add modal-based confirmation on delete in your existing AutomationCard component, you only need to:
1. Add state to control modal visibility:
js Copy code
const [showDeleteModal, setShowDeleteModal] = useState(false);
2. Change your Delete menu item click handler inside MenuList to:
js Copy code
onClick: () => {
setMenuOpen(false);
setShowDeleteModal(true); // open confirmation modal instead of deleting immediately
},
3. Add the modal JSX at the bottom of your component’s return JSX :
jsx Copy code
<FwModal
id={`delete-modal-${id}`}
size="small"
submit-color="danger"
submit-text="Delete"
open={showDeleteModal}
onFwSubmit={(e) => {
e.preventDefault?.();
handleConfirmDelete();
}}
onFwClose={() => {
setShowDeleteModal(false);
}}
>
<FwModalTitle>
<span>Delete message</span>
</FwModalTitle>
<FwModalContent>
<span>Are you sure you want to delete this Message?</span>
</FwModalContent>
</FwModal>
4. Add the handler function to confirm delete and close modal:
js Copy code
const handleConfirmDelete = () => {
setShowDeleteModal(false);
if (onDelete) onDelete(rule); // call your delete function
};
Summary of what to add/change:
diff Copy code
+ const [showDeleteModal, setShowDeleteModal] = useState(false);
...
// Inside MenuList:
- onClick: () => { setMenuOpen(false); if(onDelete) onDelete(rule); },
+ onClick: () => { setMenuOpen(false); setShowDeleteModal(true); },
...
+ <FwModal
+ id={`delete-modal-${id}`}
+ size="small"
+ submit-color="danger"
+ submit-text="Delete"
+ open={showDeleteModal}
+ onFwSubmit={(e) => {
+ e.preventDefault?.();
+ handleConfirmDelete();
+ }}
+ onFwClose={() => setShowDeleteModal(false)}
+ >
+ <FwModalTitle>
+ <span>Delete message</span>
+ </FwModalTitle>
+ <FwModalContent>
+ <span>Are you sure you want to delete this Message?</span>
+ </FwModalContent>
+ </FwModal>
...
+ const handleConfirmDelete = () => {
+ setShowDeleteModal(false);
+ if (onDelete) onDelete(rule);
+ };
This minimal patch will make the delete action show a modal first, and only delete when confirmed.
Let me know if you want me to provide the full modified AutomationCard.js or help with wiring the onDelete!
Assistant2025-05-09 05:47 UTC Copy response
Great! Here's the full modified AutomationCard component including the modal confirmation on delete, ready for you to replace your current AutomationCard with:
Show full message · 362 lines im gonna use this in automationtab.js so no export
Assistant2025-05-09 05:48 UTC Copy response
Got it! Here’s the complete AutomationCard component without export , ready to be used inline inside your AutomationTabs.js or wherever you want to.
Just paste this component code inside AutomationTabs.js file (above or below your main component) and use it directly.
Show full message · 348 lines Assistant2025-05-09 05:51 UTC Copy response
If the modal doesn't show, it usually has to do with how the <FwModal> component controls visibility with its open prop and event handlers. The Crayons React modal needs open to be controlled properly and sometimes requires a ref or calling .open() method on the modal element.
Possible issues and fixes:
Ensure your Crayons React version supports controlled open prop
If FwModal does not respond to the open prop (because it expects to be opened imperatively), you can do this:
Use a ref on the modal
On showDeleteModal change, call modalRef.current.open() or modalRef.current.close()
Revised approach (imperative open/close):
Replace the modal control in AutomationCard with this:
jsx Copy code
import React, { useState, useEffect, useRef } from "react";
import {
FwIcon,
FwToggle,
FwModal,
FwModalTitle,
FwModalContent,
} from "@freshworks/crayons/react";
const AutomationCard = (props) => {
// ... other code unchanged
const modalRef = useRef(null);
const [showDeleteModal, setShowDeleteModal] = useState(false);
// Open modal imperatively when showDeleteModal becomes 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 (props.onDelete) props.onDelete(props.rule);
};
// Inside MenuList replace delete onClick with openModal:
// onClick: () => {
// setMenuOpen(false);
// openModal();
// },
// JSX for modal:
return (
<>
{/* ... rest of card ... */}
<FwModal
id={`delete-modal-${props.rule.id}`}
ref={modalRef}
size="small"
submit-color="danger"
submit-text="Delete"
onFwSubmit={(e) => {
e.preventDefault?.();
handleConfirmDelete();
}}
onFwClose={() => {
closeModal();
}}
>
<FwModalTitle>
<span>Delete message</span>
</FwModalTitle>
<FwModalContent>
<span>Are you sure you want to delete this Message?</span>
</FwModalContent>
</FwModal>
</>
);
};
full replacement automationcard code. also to ensure delete icon is clicked add alog to verify
Assistant2025-05-09 05:51 UTC Copy response
Certainly! Here's the full replacement AutomationCard component incorporating:
Imperative modal open/close using a React ref
Logging output on Delete icon click to verify it triggers
Proper modal confirmation flow for deletion
Show full message · 387 lines export async function getTicketCreationRules(client, setState) {
try {
let creation_rules = await getAllRules("getCreationRules", 1, []);
setState(creation_rules); // No filtering applied
} catch (err) {
console.error("Error in getting Ticket Creation rules:", err);
}
}
export async function getTicketUpdationRules(client, setState) {
try {
let updation_rules = await getAllRules("getUpdationRules", 1, []);
console.log("updation_rules", updation_rules);
setState(updation_rules); // No filtering applied
} catch (err) {
console.log("Error in getting Ticket updation rules", err);
}
}
export async function getHourlyRules(client, setState) {
try {
let hourly_rules = await getAllRules("getHourlyTriggerRules", 1, []);
console.log("hourly_rules", hourly_rules);
setState(hourly_rules); // No filtering applied
} catch (err) {
console.log("Error in getting Hourly Trigger rules", err);
}
}
export async function getAgents(client, setState) {
code Copy code
try{
let agentsList = await getAllRules("getAgentsList", 1, []);
console.log("agentsList", agentsList);
const agentNameList = agentsList.map(agent => ({
value: agent.id,
text: agent.contact.name
}))
setState(agentNameList);
}catch(err){
console.log("Error in getting list of agents", err);
}
}
in this, if it comes
{
"status": 401,
"headers": {
"date": "Fri, 09 May 2025 07:08:07 GMT",
"content-type": "application/json; charset=utf-8",
"transfer-encoding": "chunked",
"connection": "close",
"status": "401 Unauthorized",
"x-request-id": "8b574d83-6563-4716-bd72-9188a85a091a",
"x-freshdesk-api-version": "latest=v2; requested=v2",
"content-security-policy": "default-src 'self'; connect-src 'self' *.freshconnect.io/ *.freshsales.io/ *.freshworks.com/ *.freshdesk.com/ *.freshworksapi.com/ *.freshdeskusercontent.com/ *.freshdeskusercontent-euc.com/ *.freshdeskusercontent-in.com/ .freshdeskusercontent-aus.com/ .fconstage.io/ analytics.inlinemanual.com/__profile analytics.inlinemanual.com/__ptm backend.getbeamer.com/ heapanalytics.com/ d3h0owdjgzys62.cloudfront.net/ d2uy6ubiilaqku.cloudfront.net/assets/ dcdu85ocrj5q6.cloudfront.net/ dtdafz6i4gvv1.cloudfront.net/ d3r4aewxkdubw4.cloudfront.net/ d2lz1e868xzctj.cloudfront.net/ rum.haystack.es/freshdesk/analytics fonts.googleapis.com/ fonts.gstatic.com/ sentry.io/api/ wss:// .freshworksapi.com/ wss:// .freshdesk.com/ fg8vvsvnieiv3ej16jby.litix.io/ distillery.wistia.com/ pipedream.wistia.com/ freshworks.asknice.ly/ embedwistia-a.akamaihd.net/ embed-fastly.wistia.com/ maps.googleapis.com/ graph.microsoft.com/v1.0/ freshcaller-attachments.s3.amazonaws.com/production/ euc-freshcaller-attachments.s3.eu-central-1.amazonaws.com/production/ mec-freshcaller-attachments.s3.me-central-1.amazonaws.com/production/ au-freshcaller-attachments.s3-ap-southeast-2.amazonaws.com/production/ in-freshcaller-attachments.s3.ap-south-1.amazonaws.com/production/ pubsub.rtschannel.com/ api.fdcollab.com/ wss://pubsub.rtschannel.com/ cloudflareinsights.com/ data: blob: api.appcues.net/ wss://api.appcues.net/ fast.appcues.com/ cdn.jsdelivr.net/npm/@freshworks/crayons-icon@next/dist/ translate.googleapis.com/translate_a/t translate.googleapis.com/element/log fast.wistia.net/ fast.wistia.com/ embed-cloudfront.wistia.com/deliveries/ app.inlinemanual.com/ client-api.auryc.com/ *.surveyserv.com *.freshsurvey.com *.freddybot.com; font-src 'self' *.freshdesk.com/ fonts.gstatic.com/ fonts.googleapis.com/ cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/fonts/ fast.wistia.net/ fast.wistia.com/ *.freddybot.com cdn.inlinemanual.com/inm/author/ data:; frame-src 'self' https:; img-src 'self' https: data: blob:; media-src 'self' https: blob:; object-src 'none'; script-src 'self' *.freshworksapi.com/ *.freshworks.com/ *.myfreshworks.com/ *.freshdesk.com/ *.freshchat.com/ *.freshcaller.com/ *.freshconnect.io/ *.freshcloud.io/ *.fconstage.io/ accounts.freshworks.com/ wchat.freshchat.com/js/ wchat.freshchat.com/widget/js/ assets.calendly.com/assets/external/widget.js d3h0owdjgzys62.cloudfront.net/ d2uy6ubiilaqku.cloudfront.net/ dtdafz6i4gvv1.cloudfront.net/ dcdu85ocrj5q6.cloudfront.net/ d3r4aewxkdubw4.cloudfront.net/ app.getbeamer.com/js/beamer-embed.js analytics.inlinemanual.com/ cdn.inlinemanual.com/embed/ cdn.heapanalytics.com/ s3.amazonaws.com/assets.freshdesk.com/ cdnjs.cloudflare.com/ ajax.cloudflare.com/ static.cloudflareinsights.com/ js.chargebee.com/v1/chargebee.js js.braintreegateway.com/v1/braintree.js static.freshdev.io/ fast.wistia.net/ fast.wistia.com/ static.getbeamer.com/ calendly.com/ unpkg.com/@webcomponents/webcomponentsjs@2.4.3/custom-elements-es5-adapter.js unpkg.com/@webcomponents/webcomponentsjs@2.4.3/webcomponents-loader.js js-agent.newrelic.com/ static.asknice.ly/dist/standalone/asknicely-in-app-conversation.js js.live.net/v7.2/OneDrive.js apis.google.com/ asknice.ly bam.nr-data.net/ maps.googleapis.com/ unpkg.com/@freshworks/crayons@v3/dist/crayons/crayons.esm.js unpkg.com/@freshworks/crayons@v3/dist/crayons/crayons.js s3.amazonaws.com/freshcaller-widget-loader/ in-freshcaller-widget-loader.s3.ap-south-1.amazonaws.com/ s3.eu-central-1.amazonaws.com/euc-freshcaller-widget-loader/ mec-freshcaller-widget-loader.s3.me-central-1.amazonaws.com/ au-freshcaller-widget-loader.s3-ap-southeast-2.amazonaws.com/ fast.appcues.com/ translate.google.com/translate_a/element.js translate.googleapis.com/ /js/ translate-pa.googleapis.com/v1/supportedLanguages cdn.surveyserv.com/widget.min.js cdn.freshdev.io/assets/marketplace-heap.js cdn.freshcloud.io/assets/marketplace-heap.js cdn.inlinemanual.com/inm/author/ app.inlinemanual.com/ *.surveyserv.com *.freshsurvey.com *.freddybot.com d3el5jsqgryo0a.cloudfront.net accounts.google.com/ 'unsafe-inline' 'unsafe-eval'; style-src 'self' *.freshworks.com *.myfreshworks.com/ *.freshchat.com/ d3h0owdjgzys62.cloudfront.net/ dcdu85ocrj5q6.cloudfront.net/ dtdafz6i4gvv1.cloudfront.net/ d3r4aewxkdubw4.cloudfront.net/ d2uy6ubiilaqku.cloudfront.net/ fonts.googleapis.com/ app.getbeamer.com/styles/beamer-embed.css s3.amazonaws.com/assets.freshdesk.com/ *.freshdesk.com/ wchat.freshchat.com/ calendly.com/ unpkg.com/@webcomponents/webcomponentsjs@2.4.3/custom-elements-es5-adapter.js unpkg.com/@webcomponents/webcomponentsjs@2.4.3/webcomponents-loader.js static.asknice.ly/dist/standalone/asknicely-in-app-conversation.css fast.appcues.com/ asknice.ly *.surveyserv.com *.freshsurvey.com *.freddybot.com cdn.inlinemanual.com/inm/author/ 'unsafe-inline'; worker-src 'self' blob:",
"x-xss-protection": "1; mode=block",
"x-content-type-options": "nosniff",
"set-cookie": [
"_x_w=2; path=/; HttpOnly; secure",
"_x_m=x_c; path=/; HttpOnly; secure",
"__cf_bm=BlnnO_Y8qEO49qQdkr1Yi0Guj9HTcH2BITmMLV.Pu30-1746774487-1.0.1.1-zof9Ud4yEqun.xsMmWeJsHdM3CpWdQF9z.KmRntaxg_Zp2kFxpnXSy4XMuoS1iGA9VodMfh7z5EXGT0NScEtwwjdLOkBw5.06WHCXIIZqZ8; path=/; expires=Fri, 09-May-25 07:38:07 GMT; domain=.freshdesk.com; HttpOnly; Secure"
],
"x-envoy-upstream-service-time": "54",
"x-trace-id": "00-230fb0abece80aa2025c9f8b80e14b86-e4813fcc8db07e9b-00",
"nel": "{ "report_to": "nel-endpoint-freshdesk", "max_age": 2592000, "include_subdomains": true}",
"report-to": "{ "group": "nel-endpoint-freshdesk", "max_age": 2592000, "include_subdomains": true, "endpoints": [{"url": " "}]}",
"x-fw-ratelimiting-managed": "true",
"x-ratelimit-total": "400",
"x-ratelimit-remaining": "396",
"x-ratelimit-used-currentrequest": "1",
"cf-cache-status": "DYNAMIC",
"strict-transport-security": "max-age=31536000; includeSubDomains; preload",
"server": "cloudflare",
"cf-ray": "93cf5d231d04213a-MAA",
"alt-svc": "h3=":443"; ma=86400"
},
"response": "{"code":"invalid_credentials","message":"You have to be logged in to perform this action."}",
"attempts": 1,
"errorSource": "APP"
}
Show full message · 1,570 lines Assistant2025-05-09 07:09 UTC Copy response
You want to display an error message when any of your API fetch functions get a 401 Unauthorized error and propagate that error message into your AutomationTabs UI for the user, right?
Approach:
Modify your API functions (getTicketCreationRules, getTicketUpdationRules, etc.) to throw or return error info when 401 is received .
In AutomationTabs, where you call these functions, catch errors and set an error state .
Render an error message/banner in the UI if that error state is set.
Detailed example:
1. Modify your fetch functions to return error info or throw on 401:
js Copy code
export async function getTicketCreationRules(client, setState) {
try {
let creation_rules = await getAllRules("getCreationRules", 1, []);
setState(creation_rules);
return null; // no error
} catch (err) {
console.error("Error in getting Ticket Creation rules:", err);
if (err?.status === 401) {
return "Unauthorized: You need to be logged in to perform this action.";
}
return "Error fetching Ticket Creation rules.";
}
}
export async function getTicketUpdationRules(client, setState) {
try {
let updation_rules = await getAllRules("getUpdationRules", 1, []);
setState(updation_rules);
return null;
} catch (err) {
console.log("Error in getting Ticket updation rules", err);
if (err?.status === 401) {
return "Unauthorized: You need to be logged in to perform this action.";
}
return "Error fetching Ticket Updation rules.";
}
}
export async function getHourlyRules(client, setState) {
try {
let hourly_rules = await getAllRules("getHourlyTriggerRules", 1, []);
setState(hourly_rules);
return null;
} catch (err) {
console.log("Error in getting Hourly Trigger rules", err);
if (err?.status === 401) {
return "Unauthorized: You need to be logged in to perform this action.";
}
return "Error fetching Hourly Trigger rules.";
}
}
export async function getAgents(client, setState) {
try{
let agentsList = await getAllRules("getAgentsList", 1, []);
const agentNameList = agentsList.map(agent => ({
value: agent.id,
text: agent.contact.name
}));
setState(agentNameList);
return null;
}catch(err){
console.log("Error in getting list of agents", err);
if (err?.status === 401) {
return "Unauthorized: You need to be logged in to perform this action.";
}
return "Error fetching Agents list.";
}
}
return (
<>
Automations - Rules
Show full message · 138 lines Assistant2025-05-09 07:16 UTC Copy response
To make the error message container have the same width as the tab panel container (60% and aligned similarly), simply move the {errorMessage && ...} block inside the container <div style={{ width: "60%", marginRight: "auto" }}> and apply consistent styling.
Example:
jsx Copy code
{tabsInitialized && (
<div style={{ width: "60%", marginRight: "auto" }}>
{/* Error message at top inside container */}
{errorMessage && (
<div
style={{
color: "red",
marginBottom: "10px",
textAlign: "center",
fontWeight: "bold",
}}
>
{errorMessage}
</div>
)}
<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}>
{/* Tabs and TabPanels as before */}
</FwTabs>
</div>
)}
Summary
Place the error message inside the exact container div that defines the width (width: 60% and marginRight: auto).
Remove the fixed width from the error message div itself.
Add some margin bottom for spacing above the rest of content.
This will make the error text align nicely and have uniform width with your rest of UI.
If you want me to update your full return JSX snippet with the error block properly placed, just say!
Assistant2025-05-09 07:17 UTC Copy response
Got it! You want the error message to appear below the tabs container , but still be exactly the same width and aligned with the tab container (which is 60% width and aligned to left via marginRight: "auto").
How to do this:
Place your error block after the tabs container div (so it visually appears under it), but wrap it in a div with the same width and margin styles .
Example:
jsx Copy code
{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}>
{/* ... your tabs and panels here */}
</FwTabs>
</div>
{/* Error message below the tabs container */}
{errorMessage && (
<div
style={{
width: "60%",
marginRight: "auto",
color: "red",
marginTop: "8px",
marginBottom: "10px",
textAlign: "center",
fontWeight: "bold",
}}
>
{errorMessage}
</div>
)}
</>
)}
Explanation:
The tabs container remains in its <div style={{ width: "60%", marginRight: "auto" }}>...</div>
The error container is separate, below it, but styled exactly the same way (same width and margin), so it aligns perfectly below.
Added some top margin (marginTop: 8px) on error message for spacing.
If you want me to adjust your full return statement with this placement, just ask!
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"}...,
});
};
how this actually works
Assistant2025-05-09 07:22 UTC Copy response
Let's break down what your fetchData function does step-by-step:
js Copy code
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"}...`,
});
};
Context
fetchFromApi is a boolean state indicating which data source/view mode you're currently in:
false = fetching entity data (like cached or local data)
true = fetching recent data (e.g., from an API)
searchTerm and searchQuery are state values managing search input and applied search filter.
currentPage holds current pagination page numbers for each tab.
activeTab identifies the currently selected tab (ticketcreate, ticketupdate, or hourly).
Step-by-step:
Check if we're currently NOT fetching from API (i.e., fetchFromApi is false):
js Copy code
if (!fetchFromApi) {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}
If this is true, reset :
Search input (searchTerm) to empty string, so the search box clears
Applied search filter (searchQuery) to empty string, so results aren’t filtered
Pagination page for the current tab (currentPage[activeTab]) to 1, showing first page of results
This ensures the UI clears any search filter and resets pagination when switching from entity data to recent API data (or whenever this function is called while is false).
same it should perfor searchquer to empty when switching from api to back (entity)
Assistant2025-05-09 07:23 UTC Copy response
Got it! You want the search state (searchTerm and searchQuery) and current page to be reset on both switches :
From entity (local) ➡ API (recent data)
From API (recent data) ➡ entity (local)
Adjusted fetchData implementation:
js Copy code
const fetchData = async () => {
// Always clear search and reset page no matter which way you toggle
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
// Toggle fetch mode
setFetchFromApi((prev) => !prev);
// Toast content depends on current mode before toggling
toast.current.trigger({
type: "info",
content: `${fetchFromApi ? "Going Back" : "Fetching Recent Data"}...`,
});
};
Explanation:
Move the cleanup logic (clearing search terms and resetting page) outside the if-condition so it runs every toggle.
That way, whether you switch from entity → API or API → entity, search box clears and page resets to 1.
Toast still uses old mode to pick correct message text.
Why?
Your original code only cleaned search terms when switching from entity to API, not the other way around. This new code always resets search and page on each mode toggle.
Let me know if you want me to update the full code snippet in your component!
const findDuplicateRulestype1and3 = (records) => {
const seenRules = new Map();
const duplicateRecords = [];
const stripImageTags = (html) => html?.replace(/<img[^>]*>/gi, "") || "";
const cleanText = (text) =>
stripImageTags(String(text))
.toLowerCase()
.replace(/ /gi, " ") // replace non-breaking space
.replace(/<[^>]>/g, "") // remove remaining HTML tags
.replace(/[,.]/g, "") // remove commas and periods
.replace(/([a-zA-Z])(\d)/g, "1 1 1 2") // split letters and digits
.replace(/(\d)([a-zA-Z])/g, "1 1 1 2") // split digits and letters
.replace(/\s+/g, " ") // normalize whitespace
.trim()
.replace(/\bcomma\b\s \bfull\s*stop\b/g, "comma fullstop"); // ensure correct spacing
const normalizeConditionParts = (rawConditions) => {
const parts = rawConditions?.split(",") || [];
const set1 = [];
const set2 = [];
let currentSet = null;
code Copy code
for (let i = 0; i < parts.length; i++) {
let part = cleanText(parts[i]);
if (part === "condition set 1") {
currentSet = set1;
continue;
}
if (part === "condition set 2") {
currentSet = set2;
continue;
}
if (currentSet) currentSet.push(part);
}
set1.sort();
set2.sort();
return { set1: set1.join(","), set2: set2.join(",") };
};
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 "";
};
records.forEach((record) => {
const { conditions, actions, operator } = record.data;
code Copy code
const { set1, set2 } = normalizeConditionParts(conditions);
const normalizedActions = normalizeActions(actions);
const normalizedOperator = operator ? cleanText(operator) : "";
const key1 = `${set1}|${set2}|${normalizedActions}|${normalizedOperator}`;
const key2 = `${set2}|${set1}|${normalizedActions}|${normalizedOperator}`;
// Check if key1 or key2 already exists in the seen rules
if (seenRules.has(key1) || seenRules.has(key2)) {
const existing = seenRules.get(key1) || seenRules.get(key2);
if (!duplicateRecords.includes(existing)) {
duplicateRecords.push(existing);
}
duplicateRecords.push(record);
} else {
seenRules.set(key1, record);
}
});
return duplicateRecords;
};
how it actually filters
Show full message · 88 lines Assistant2025-05-09 07:28 UTC Copy response
Your findDuplicateRulestype1and3 function is designed to identify duplicate rule records based on normalized “conditions”, “actions” and “operator” fields — applying normalization and a commutative check on the condition sets.
What it does, step-by-step:
1. Prepares helper functions:
stripImageTags(html): removes <img> tags from HTML strings.
cleanText(text): normalizes text by lowercasing, removing HTML tags, commas/periods, splitting letters/digits, reducing spaces, and fixing some phrases.
normalizeConditionParts(rawConditions): splits raw condition strings by commas, groups condition parts into two sets (set1, set2) when it encounters "condition set 1" and "condition set 2" markers, normalizes & sorts them, then joins each set back to a string.
normalizeActions(actions): normalizes the actions field similarly; handles strings or arrays of objects, normalizes the text content, sorts, and joins with commas.
2. Iterate over each record in records:
js Copy code
records.forEach((record) => {
const { conditions, actions, operator } = record.data;
// Normalize conditions and actions and operator
const { set1, set2 } = normalizeConditionParts(conditions);
const normalizedActions = normalizeActions(actions);
const normalizedOperator = operator ? cleanText(operator) : "";
// Create two keys: one with set1|set2 and one with set2|set1
// to account for commutativity between condition sets (order doesn't matter)
const key1 = `${set1}|${set2}|${normalizedActions}|${normalizedOperator}`;
const key2 = `${set2}|${set1}|${normalizedActions}|${normalizedOperator}`;
// Check if we've already seen either key
if (seenRules.has(key1) || seenRules.has(key2)) {
const existing = seenRules.get(key1) || seenRules.get(key2);
// Add existing record first (if not already added)
if (!duplicateRecords.includes(existing)) {
duplicateRecords.push(existing);
}
// Then add current record as duplicate
duplicateRecords.push(record);
} else {
// First time seeing this normalized combination, store it
seenRules.set(key1, record);
}
});
// 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);
Show full message · 107 lines Assistant2025-05-09 07:30 UTC Copy response
Yes! This logic you posted is essentially a more robust and structured approach to normalizing and grouping duplicate rules based on their conditions, actions, and operator—very much in the same spirit as the earlier findDuplicateRulestype1and3 function, but with some improvements and refinements.
How is it similar?
Text normalization: Both normalize conditions and actions by making text lowercase, removing HTML tags, commas, periods, normalizing whitespace, and splitting letter-digit combinations.
Condition sets treated commutatively: Both handle the fact that conditions come in 2 sets that could be interchangeable (set1 and set2), and generate two potential keys with swapped sets to identify duplicates regardless of condition set order.
Grouping duplicates: Both group records by a normalized "signature" or "key" that's constructed from normalized condition sets, normalized actions, and normalized operator.
Filtering active rules: The grouping function filters only rules where active === true (or "true" string).
How does it differ/improve?
More flexible input: This logic supports conditions that may be a string or an array, handling either cleanly.
Better encoding of signature: It uses JSON.stringify to create a structured object key for grouping, which is easier to maintain and less error-prone than manually concatenating strings.
Sorting within sets: By sorting the condition parts arrays before joining, it ensures equivalence is detected even if order differs.
Returns groups of duplicates: Instead of returning a flat list of duplicates (findDuplicateRulestype1and3 returns duplicate records directly), this groups duplicates as arrays, which makes it easier to work with groups after.
Summary
Yes, this is based on the same principle as your earlier findDuplicateRulestype1and3 function but structured into reusable utility functions with clearer separation.
This approach is cleaner and more maintainable, and preferred especially when you want to work with duplicate groups rather than just flat duplicate elements.
If you want, I can help you integrate this grouping logic into your app for displaying duplicate groups or deduplicating rules!
const findDuplicateRulestype1and3 = (records) => {
const seenRules = new Map();
const duplicateRecords = [];
const stripImageTags = (html) => html?.replace(/<img[^>]*>/gi, "") || "";
const cleanText = (text) =>
stripImageTags(String(text))
.toLowerCase()
.replace(/ /gi, " ") // replace non-breaking space
.replace(/<[^>]>/g, "") // remove remaining HTML tags
.replace(/[,.]/g, "") // remove commas and periods
.replace(/([a-zA-Z])(\d)/g, "1 1 1 2") // split letters and digits
.replace(/(\d)([a-zA-Z])/g, "1 1 1 2") // split digits and letters
.replace(/\s+/g, " ") // normalize whitespace
.trim()
.replace(/\bcomma\b\s \bfull\s*stop\b/g, "comma fullstop"); // ensure correct spacing
const normalizeConditionParts = (rawConditions) => {
const parts = rawConditions?.split(",") || [];
const set1 = [];
const set2 = [];
let currentSet = null;
code Copy code
for (let i = 0; i < parts.length; i++) {
let part = cleanText(parts[i]);
if (part === "condition set 1") {
currentSet = set1;
continue;
}
if (part === "condition set 2") {
currentSet = set2;
continue;
}
if (currentSet) currentSet.push(part);
}
set1.sort();
set2.sort();
return { set1: set1.join(","), set2: set2.join(",") };
};
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 "";
};
records.forEach((record) => {
const { conditions, actions, operator } = record.data;
Show full message · 199 lines Assistant2025-05-09 07:32 UTC Copy response
Certainly! Below is a React-friendly version of your duplicate filtering logic — structured as a pure utility function that accepts an array of rules (passed as a parameter) and returns an array of duplicate groups.
This code integrates your normalization logic, and returns an array of groups , each group being an array of duplicate rules sharing the same normalized signature.
Key points:
React doesn’t require special treatment here because this is pure JS filtering — just ensure your component calls this function with the rules array when needed (e.g., inside a useMemo, useEffect, or event handler).
No direct state management inside the function; state is managed in the component that calls it.
The function returns grouped duplicates (each group having 2+ items).
The normalization handles condition sets commutatively.
Full utility function rewritten with comments:
// 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);
};
it should work from this
Assistant2025-05-09 07:34 UTC Copy response
Yes! Your groupDuplicates function is correctly structured to group rules by their normalized signature.
Here’s a bit more context and how you can use it properly in React:
What groupDuplicates does:
Takes an array of rules.
Filters to only active rules (active === "true" or boolean true).
For each rule, computes a normalized signature (using getRuleSignatureNormalized, which you already have).
Groups all rules with the same signature together in the groups object.
Returns only the arrays of grouped rules as an array of groups (Object.values(groups)).
Each group contains rules that are duplicates of each other.
How to use it:
Assuming you have your utility groupDuplicates and getRuleSignatureNormalized, just call:
js Copy code
const duplicateGroups = groupDuplicates(allRules);
duplicateGroups is an array of arrays.
Each inner array is a group of rules that are identical per your normalization criteria.
Groups with just one rule are also included (if you want only groups with duplicates, filter those out).
If you want only groups with duplicates (more than 1 rule), do:
js Copy code
const duplicateGroups = groupDuplicates(allRules).filter(group => group.length > 1);
Using in React:
jsx Copy code
const MyComponent = ({ rules }) => {
// Memoize duplicate groups for performance
const duplicateGroups = React.useMemo(() => {
return groupDuplicates(rules).filter(group => group.length > 1);
}, [rules]);
return (
<div>
{duplicateGroups.length === 0 ? (
<p>No duplicate rules found.</p>
) : (
duplicateGroups.map((group, idx) => (
<div key={idx}>
<h3>Duplicate Group {idx + 1} ({group.length} rules)</h3>
<ul>
{group.map(rule => (
<li key={rule.id}>{rule.name || rule.id}</li>
))}
</ul>
</div>
))
)}
</div>
);
};
Summary:
Your groupDuplicates function is perfectly fine as-is.
Just call it and optionally filter groups by length > 1 to show actual duplicates.
Use it in React components with useMemo or wherever appropriate.
If you want me to verify or enhance your getRuleSignatureNormalized or provide a sample integration, just say!
Assistant2025-05-09 07:34 UTC Copy response
Certainly! Below is a full React-compatible snippet combining the duplicate grouping utilities with a sample React component that:
Accepts a list of rules.
Groups duplicates by normalized signature.
Displays only the groups with duplicates (size > 1).
Uses memoization (useMemo) for performance.
[
{
"name": "simple",
"position": 1,
"active": true,
"outdated": false,
"last_updated_by": 82175529665,
"id": 82000720816,
"summary": {
"conditions": {
"condition_set_1": [
"If Subject is we are great "
]
},
"actions": [
"Delete ticket"
]
},
"created_at": "2025-05-06T06:22:41Z",
"updated_at": "2025-05-09T07:19:31Z",
"affected_tickets_count": 0,
"conditions": [
{
"name": "condition_set_1",
"match_type": "any",
"properties": [
{
"field_name": "subject",
"resource_type": "ticket",
"operator": "is",
"value": "we are great ",
"case_sensitive": false
}
]
}
],
"actions": [
{
"field_name": "delete_ticket"
}
],
"description": null
},
{
"name": "Copy of simple",
"position": 2,
"active": true,
"outdated": false,
"last_updated_by": 82175529665,
"id": 82000720817,
"summary": {
"conditions": {
"condition_set_1": [
"If Subject is We Are Great "
]
},
"actions": [
"Delete ticket"
]
},
"created_at": "2025-05-06T06:22:54Z",
"updated_at": "2025-05-09T07:19:31Z",
"affected_tickets_count": 0,
"conditions": [
{
"name": "condition_set_1",
"match_type": "any",
"properties": [
{
"field_name": "subject",
"resource_type": "ticket",
"operator": "is",
"value": "We Are Great ",
"case_sensitive": false
}
]
}
],
"actions": [
{
"field_name": "delete_ticket"
}
],
"description": null
},
{
"name": "lol",
"position": 24,
"active": true,
"outdated": false,
"last_updated_by": 82175846817,
"id": 82000720951,
"summary": {
"conditions": {
"condition_set_1": [
"If Subject or description is we are"
]
},
"actions": [
"Delete ticket"
]
},
"created_at": "2025-05-07T12:05:26Z",
"updated_at": "2025-05-09T07:19:31Z",
"affected_tickets_count": 0,
"conditions": [
{
"name": "condition_set_1",
"match_type": "any",
"properties": [
{
"field_name": "subject_or_description",
"resource_type": "ticket",
"operator": "is",
"value": "we are",
"case_sensitive": false
}
]
}
],
"actions": [
{
"field_name": "delete_ticket"
}
],
"description": null
},
{
"name": "Copy of lol",
"position": 25,
"active": true,
"outdated": false,
"last_updated_by": 82175846817,
"id": 82000720957,
"summary": {
"conditions": {
"condition_set_1": [
"If Subject or description is we are"
]
},
"actions": [
"Delete ticket"
]
},
"created_at": "2025-05-07T12:12:56Z",
"updated_at": "2025-05-09T07:19:31Z",
"affected_tickets_count": 0,
"conditions": [
{
"name": "condition_set_1",
"match_type": "any",
"properties": [
{
"field_name": "subject_or_description",
"resource_type": "ticket",
"operator": "is",
"value": "we are",
"case_sensitive": false
}
]
}
],
"actions": [
{
"field_name": "delete_ticket"
}
],
"description": null
},
{
"name": "Copy of Copy of lol",
"position": 26,
"active": true,
"outdated": false,
"last_updated_by": 82175846817,
"id": 82000720958,
"summary": {
"conditions": {
"condition_set_1": [
"If Subject or description is we are"
]
},
"actions": [
"Delete ticket"
]
},
"created_at": "2025-05-07T12:13:07Z",
"updated_at": "2025-05-09T07:19:31Z",
"affected_tickets_count": 0,
"conditions": [
{
"name": "condition_set_1",
"match_type": "any",
"properties": [
{
"field_name": "subject_or_description",
"resource_type": "ticket",
"operator": "is",
"value": "we are",
"case_sensitive": false
}
]
}
],
"actions": [
{
"field_name": "delete_ticket"
}
],
"description": null
}
]
Show full message · 214 lines Assistant2025-05-09 07:36 UTC Copy response
Yes, the grouping functions you have (like getRuleSignatureNormalized and groupDuplicates or findDuplicateRulestype1and3) are designed exactly for data like this to detect duplicates despite minor differences like:
Case differences ("we are great" vs "We Are Great")
HTML tags inside summary conditions/actions
Different ordering or whitespace variations
Other textual noise normalized by cleanText
What your functions do with this data:
Your rules have summaries where conditions and actions are provided as HTML strings, e.g.,
js Copy code
"If <div class = SummaryKey>Subject</div> <div class = SummaryOperator>is</div> <div class = SummaryValue>we are great </div>"
cleanText removes HTML tags, normalizes case, removes punctuation, normalizes spaces.
Conditions are split into sets (e.g., condition_set_1), extracted by normalizeConditionParts.
Actions are normalized too.
The operator normalized (mostly empty or "is" in many cases).
Two normalized keys are created with swapped sets to handle commutativity.
Finally, rules with matching normalized keys are grouped together.
In your provided data:
"simple" and "Copy of simple":
Conditions and actions are basically the same except for casing differences that your cleanText handles.
They should be grouped as duplicates.
Similarly "lol", "Copy of lol", and "Copy of Copy of lol" have same normalized conditions and actions and should be grouped together.
So yes, your functions will:
Normalize all these rule conditions and actions,
Detect and group "simple" with "Copy of simple",
Detect and group "lol", "Copy of lol", and "Copy of Copy of lol".
Note:
The rules are mostly duplicated by name and summary fields, but your code groups duplicates based on the (not on names or positions).
Assistant2025-05-09 07:36 UTC Copy response
Sure! Here's a complete demo React snippet that:
Takes your sample rules as input (the JSON you provided)
Uses your normalization and grouping utilities (cleanText, normalizeConditionParts, normalizeActions, getRuleSignatureNormalized, and groupDuplicates)
Displays groups of duplicate rules in the UI
Show full message · 214 lines Copy first response
Not yet included in a published release.
Turns (20) 1 in this code, consider this scenario : if im in entity and search a word, then w 2 const AutomationCard = ({ rule = {}, index, isFirstInGroup = false, onDelete, ag 3 give me the complete 4 give what to add 5 yesssss 6 im gonna use this in automationtab.js so no export 7 no modal is showing 8 full replacement automationcard code. also to ensure delete icon is clicked add 9 export async function getTicketCreationRules(client, setState) { try { let creat 10 return ( <> Automations - Rules {showSearchHint && ( Please enter a search term 11 it should be under 12 const fetchData = async () => { if (!fetchFromApi) { setSearchTerm(""); setSearc 13 same it should perfor searchquer to empty when switching from api to back (entit 14 const findDuplicateRulestype1and3 = (records) => { const seenRules = new Map(); 15 // Utility: clean and normalize text const cleanText = (text) => String(text || 16 const findDuplicateRulestype1and3 = (records) => { const seenRules = new Map(); 17 // Group duplicates by normalized signature const groupDuplicates = (rules) => { 18 give me full snippet 19 [ { "name": "simple", "position": 1, "active": true, "outdated": false, "lastupd 20 yes 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 />
</>
<fw-input
ref={inputRef}
icon-left="search"
hint-text="Type Keyword to Search"
placeholder="Enter a Keyword to Search..."
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);
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setShowSearchHint(false);
} else {
setSearchQuery(trimmed);
setShowSearchHint(false);
}
}
}}
onFwClear={() => {
// When user clicks on the 'x' clear button, reset search and pagination
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}}
/>
Summary:
Reset search states (searchTerm, searchQuery, and page number) when switching data source via the "Get Recent Data" / "Back" button.
Reset search states when user clears the search input via 'x'.
Why this works:
Clearing searchTerm and searchQuery will remove the search filter and show full rules.
Resetting the pagination to 1 on the active tab ensures the user starts from the first page.
Adding the onFwClear handler ensures clicking the clear button behaves consistently.
If you want, I can help integrate these adjustments into your full component code. Let me know!
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"
></path>
</svg>
</div>
<MenuList
visible={menuOpen}
onEdit={() => alert("Edit clicked")}
onClone={() => alert("Clone clicked")}
onDelete={handleConfirmDelete}
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>
</>
in this on clicking delete
code Copy code
<FwButton modal-trigger-id='composition'> Open confirmation Modal </FwButton>
<FwModal id='composition' size="small" submit-color="danger" submit-text="Delete">
<FwModalTitle>
<span>Delete message</span>
</FwModalTitle>
<FwModalContent>
<span>Are you sure you want to delete this Message?</span>
</FwModalContent>
</FwModal>
trigger this modal to open modal.
Events
Event Description Type
fwClose Triggered when modal is closed. CustomEvent
fwOpen Triggered when modal is opened. CustomEvent
fwSubmit Triggered when the default action button is clicked. CustomEvent
refer this when fwsubmit is clicked. then perform deleterule
import { useState, useRef, useEffect } from "react";
import { FwIcon, FwToggle, FwModal, FwModalTitle, FwModalContent } from "@freshworks/crayons/react";
const AutomationCard = ({
rule = {},
index,
isFirstInGroup = false,
onDelete,
agent,
activeTab,
onSelect,
}) => {
// ...other code
const [menuOpen, setMenuOpen] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const menuContainerRef = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (menuContainerRef.current && !menuContainerRef.current.contains(event.target)) {
setMenuOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
// When user confirms delete in modal
const handleConfirmDelete = () => {
setShowDeleteModal(false);
if (onDelete) onDelete(rule);
};
// Dropdown menu delete item click - open modal instead of immediate deletion
function MenuList({ visible, onEdit, onClone, onDelete, rule }) {
return (
<ul
// styles omitted for brevity, keep your existing styles here
>
{[
{ name: "edit", label: "Edit", onClick: onEdit },
{ name: "clone", label: "Clone", onClick: onClone },
{
name: "delete",
label: "Delete",
onClick: () => {
setMenuOpen(false);
setShowDeleteModal(true); // open modal instead of direct delete
},
},
].map(({ name, label, onClick }) => (
<li
key={name}
// other handlers
onClick={(e) => {
e.stopPropagation();
onClick?.();
setMenuOpen(false);
}}
// onMouseEnter and onMouseLeave handlers
>
<FwIcon name={name} size={18} color="#333" />
<div>{label}</div>
</li>
))}
</ul>
);
}
return (
<>
<div
className="fw-card-1 fw-flex fw-flex-column"
// your existing styles and click handlers
>
{/* existing card content */}
</div>
{/* Delete confirmation modal */}
<FwModal
id={`delete-modal-${rule.id}`} // unique id for modal
size="small"
submit-color="danger"
submit-text="Delete"
open={showDeleteModal}
onFwSubmit={(e) => {
e.preventDefault?.();
handleConfirmDelete();
}}
onFwClose={() => {
setShowDeleteModal(false);
}}
>
<FwModalTitle>
<span>Delete message</span>
</FwModalTitle>
<FwModalContent>
<span>Are you sure you want to delete this Message?</span>
</FwModalContent>
</FwModal>
</>
);
};
Explanation:
Integration notes:
Make sure onDelete passed to AutomationCard is the function that triggers deleting the rule, as you already do.
The modal ID is made unique by appending rule id, just in case multiple cards are rendered.
The modal's open state (open={showDeleteModal}) directly controls showing/hiding it.
Prevent default event handling in onFwSubmit to avoid any strange behaviour.
This change lets the modal manage the confirmation flow, replacing instant delete on the menu option.
If you'd like, I can help you integrate this with the main component or with your deletion logic. Let me know!
import React, { useState, useEffect, useRef } from "react";
import {
FwIcon,
FwToggle,
FwModal,
FwModalTitle,
FwModalContent,
} from "@freshworks/crayons/react";
// Assuming calculateLastModified is imported or defined elsewhere in your file
// If not, make sure to include it
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 menuContainerRef = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (
menuContainerRef.current &&
!menuContainerRef.current.contains(event.target)
) {
setMenuOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
const handleConfirmDelete = () => {
setShowDeleteModal(false);
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 "";
}
// Dropdown Menu Component
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: () => {
setMenuOpen(false);
setShowDeleteModal(true); // <-- open confirmation modal here
},
},
].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")
}
>
<FwIcon name={name} size={18} color="#333" />
<div>{label}</div>
</li>
))}
</ul>
);
}
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",
}}
>
<h5 className="fw-type-h1 fw-mt-0 fw-mb-8">
{position}. {name}
</h5>
<p
className="fw-type-xs fw-mt-0 fw-mb-20"
style={{ marginBottom: "10px", fontSize: "14px" }}
>
{generateSummary(rule.summary)}
</p>
</div>
<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"
></path>
</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}`}
size="small"
submit-color="danger"
submit-text="Delete"
open={showDeleteModal}
onFwSubmit={(e) => {
e.preventDefault?.();
handleConfirmDelete();
}}
onFwClose={() => {
setShowDeleteModal(false);
}}
>
<FwModalTitle>
<span>Delete message</span>
</FwModalTitle>
<FwModalContent>
<span>Are you sure you want to delete this Message?</span>
</FwModalContent>
</FwModal>
</>
);
};
export default AutomationCard;
How to use this:
In your parent component, pass an onDelete function that handles actual deletion logic.
When user clicks Delete from dropdown, the modal will open.
Confirming the modal calls onDelete with the rule.
Modal closes on cancel or submit.
If you want me to also help with the deletion logic in the parent/component that renders AutomationCard, just let me know!
import React, { useState, useEffect, useRef } from "react";
import {
FwIcon,
FwToggle,
FwModal,
FwModalTitle,
FwModalContent,
} from "@freshworks/crayons/react";
// Make sure calculateLastModified is imported or defined in your file
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 menuContainerRef = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (
menuContainerRef.current &&
!menuContainerRef.current.contains(event.target)
) {
setMenuOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
const handleConfirmDelete = () => {
setShowDeleteModal(false);
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 "";
}
// Dropdown Menu Component
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: () => {
setMenuOpen(false);
setShowDeleteModal(true); // Show confirmation modal on delete click
},
},
].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")
}
>
<FwIcon name={name} size={18} color="#333" />
<div>{label}</div>
</li>
))}
</ul>
);
}
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",
}}
>
<h5 className="fw-type-h1 fw-mt-0 fw-mb-8">
{position}. {name}
</h5>
<p
className="fw-type-xs fw-mt-0 fw-mb-20"
style={{ marginBottom: "10px", fontSize: "14px" }}
>
{generateSummary(rule.summary)}
</p>
</div>
<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}`}
size="small"
submit-color="danger"
submit-text="Delete"
open={showDeleteModal}
onFwSubmit={(e) => {
e.preventDefault?.();
handleConfirmDelete();
}}
onFwClose={() => {
setShowDeleteModal(false);
}}
>
<FwModalTitle>
<span>Delete message</span>
</FwModalTitle>
<FwModalContent>
<span>Are you sure you want to delete this Message?</span>
</FwModalContent>
</FwModal>
</>
);
};
export default AutomationCard;
What happens now?
When the user clicks Delete in the dropdown menu, the confirmation modal appears.
If the user confirms by clicking Delete in the modal, your onDelete(rule) function is called.
The modal closes on cancel or after confirming delete.
The rest of the card/UI stays the same.
Next step: Make sure you pass the onDelete prop from your parent component, which should handle the actual delete request and update state accordingly.
If you want me to help with the parent component or how to wire up the delete callback and state update, just ask!
import React, { useState, useEffect, useRef } from "react";
import {
FwIcon,
FwToggle,
FwModal,
FwModalTitle,
FwModalContent,
} from "@freshworks/crayons/react";
// Make sure calculateLastModified is defined or imported in the same file
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 menuContainerRef = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (
menuContainerRef.current &&
!menuContainerRef.current.contains(event.target)
) {
setMenuOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
const handleConfirmDelete = () => {
setShowDeleteModal(false);
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: () => {
setMenuOpen(false);
setShowDeleteModal(true); // open modal on Delete click
},
},
].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")
}
>
<FwIcon name={name} size={18} color="#333" />
<div>{label}</div>
</li>
))}
</ul>
);
}
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",
}}
>
<h5 className="fw-type-h1 fw-mt-0 fw-mb-8">
{position}. {name}
</h5>
<p
className="fw-type-xs fw-mt-0 fw-mb-20"
style={{ marginBottom: "10px", fontSize: "14px" }}
>
{generateSummary(rule.summary)}
</p>
</div>
<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}`}
size="small"
submit-color="danger"
submit-text="Delete"
open={showDeleteModal}
onFwSubmit={(e) => {
e.preventDefault?.();
handleConfirmDelete();
}}
onFwClose={() => setShowDeleteModal(false)}
>
<FwModalTitle>
<span>Delete message</span>
</FwModalTitle>
<FwModalContent>
<span>Are you sure you want to delete this Message?</span>
</FwModalContent>
</FwModal>
</>
);
};
Then just use <AutomationCard /> as before inside your AutomationTabs or wherever you want.
If you want me to help with the parent AutomationTabs part for handling the onDelete prop, just tell me!
Summary of changes:
Use a React ref (modalRef) on <FwModal>.
Use modalRef.current.open() and .close() to control modal instead of open={} prop.
When showDeleteModal is true, call modalRef.current.open() imperatively.
Call modalRef.current.close() when closing modal.
Toggle showDeleteModal state to track whether modal should currently be open or not.
On delete menu click, call openModal() instead of setting showDeleteModal directly to open modal imperatively.
On modal onFwClose event, close modal.
This pattern matches typical usage of Freshworks Crayons modal in React (imperative control). Your problem is likely the modal not opening because open prop is not supported or doesn’t auto-open modal on prop change.
Let me know if you want me to provide the full replacement AutomationCard code with this fix applied! import React, { useState, useEffect, useRef } from "react";
import {
FwIcon,
FwToggle,
FwModal,
FwModalTitle,
FwModalContent,
} from "@freshworks/crayons/react";
// Make sure calculateLastModified is defined or imported in your file
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);
}
};
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")
}
>
<FwIcon name={name} size={18} color="#333" />
<div>{label}</div>
</li>
))}
</ul>
);
}
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",
}}
>
<h5 className="fw-type-h1 fw-mt-0 fw-mb-8">
{position}. {name}
</h5>
<p
className="fw-type-xs fw-mt-0 fw-mb-20"
style={{ marginBottom: "10px", fontSize: "14px" }}
>
{generateSummary(rule.summary)}
</p>
</div>
<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>
</>
);
};
export default AutomationCard;
What to check:
When you click Delete menu item , you should see a console log:
code Copy code
Delete icon clicked for rule id: <the rule’s id here>
The confirmation modal should pop up.
Clicking Delete in the modal triggers onDelete(rule) passed from parent.
Canceling or closing modal cancels the deletion.
If modal still does not open:
Confirm your diapers version supports imperative .open() and .close() on FwModal refs.
Confirm modalRef is attached correctly (Freshworks Crayons React supports ref).
Make sure no CSS or z-index is preventing modal from showing.
Feel free to ask if you want me to help troubleshoot or integrate this with your AutomationTabs component!
/translate_http/
error you have to show a line in automationtab because this is common js it is imported to automationtab.js
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 [activeTab, setActiveTab] = useState("ticketcreate");
const [tabsInitialized, setTabsInitialized] = useState(false);
const modalRef = useRef(null);
const [ticketCreationRules, setTicketCreationRules] = useState([]);
const [ticketUpdateRules, setTicketUpdateRules] = useState([]);
const [hourlyTriggerRules, setHourlyTriggerRules] = useState([]);
const [loading, setLoading] = useState(false);
const [agent, setAgent] = useState([]);
// const [ruleViewFilter, setRuleViewFilter] = useState(ruleViewOptions[0]);
const [currentPage, setCurrentPage] = useState({
ticketcreate: 1,
ticketupdate: 1,
hourly: 1,
});
const toast = useRef(ToastController({ position: "top-center" }));
const newRulePloadDB5 = useRef(null);
const ticketCreate = 1;
const ticketUpdate = 4;
const hourlyTriggers = 3;
// ===== CHANGE: initial fetchFromApi to false to fetch entity data initially =====
const [fetchFromApi, setFetchFromApi] = useState(false);
const [showPagination, setShowPagination] = useState(false);
// ======= Grouped state arrays to hold duplicate groups =======
const [ticketCreationRuleGroups, setTicketCreationRuleGroups] = useState([]);
const [ticketUpdateRuleGroups, setTicketUpdateRuleGroups] = useState([]);
const [hourlyRuleGroups, setHourlyRuleGroups] = useState([]);
// =============================================================
// ----- NEW: rule view filter for 'All Rules' or 'Duplicate Rules' -----
const ruleViewOptions = [
{
value: "all_rules",
text: "All Rules",
graphicsProps: { name: "list" },
},
{
value: "duplicate_rules",
text: "Duplicate Rules",
graphicsProps: { name: "warning" },
},
];
const [ruleViewFilter, setRuleViewFilter] = useState(ruleViewOptions[0]);
// ---------------------------------------------------------------------
useEffect(() => {
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);
};
code Copy code
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 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..."
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);
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
const trimmed = e.target.value.trim();
if (!trimmed) {
setSearchQuery("");
setShowSearchHint(false);
} else {
setSearchQuery(trimmed);
setShowSearchHint(false);
}
}
}}
onFwClear={() => {
setSearchTerm("");
setSearchQuery("");
setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
}}
/>
<div style={{ flexShrink: 0 }}>
<FwButton color="primary" onFwClick={() => { /* Add your handler here */ }}>
<fw-icon name="plus" size="16" style={{ marginRight: "8px" }}>
Add New Rule
);
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 (
<>
Automations - Rules
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;
2. Inside your AutomationTabs component, add an error state: jsx Copy code
const [errorMessage, setErrorMessage] = useState(null);
3. Modify your data fetching effect to catch error text returned: jsx Copy code
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);
}
}
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]);
4. Render the error message in your JSX somewhere near the top or above your tab panels: jsx Copy code
{errorMessage && (
<div style={{ color: "red", margin: "10px auto", width: "60%", textAlign: "center", fontWeight: "bold" }}>
{errorMessage}
</div>
)}
Result:
When API returns 401 Unauthorized, the appropriate message is set in state errorMessage.
The message is displayed prominently in the UI so users can see it.
If no errors, no message shows.
Other errors (non-401) will show generic error messages but you can customize.
If you want me to help adjust your full AutomationTabs.js with these changes included, just ask!
{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 />
{errorMessage && (
the errormessage should be same as tab width
fetchFromApi
Toggle fetchFromApi boolean state:
js Copy code
setFetchFromApi((prev) => !prev);
Flips the value of fetchFromApi to its opposite.
So if currently false (entity data mode), it becomes true (recent data mode), and vice versa.
This toggle triggers the useEffect that listens to fetchFromApi to fetch fresh data from the new source.
Trigger Toast Notification:
js Copy code
toast.current.trigger({
type: "info",
content: `${fetchFromApi ? "Going Back" : "Fetching Recent Data"}...`,
});
Shows a notification (a "toast") to user.
Text depends on current fetch mode before toggling (because JS closures remember the old value of fetchFromApi):
If fetchFromApi is currently true, it says "Going Back" (probably back to entity/local data).
If fetchFromApi is currently false, it says "Fetching Recent Data" (loading fresh API data).
When you click the button calling fetchData: Then your component reacts to the change in fetchFromApi and fetches the corresponding data accordingly.
Summary fetchData serves as a toggle between two datasets (entity data vs API recent data), cleaning search state when switching to API data, and notifying the user about the state change.
If you want, I can help you trace how fetchFromApi drives data fetching useEffect in your code too!
Detailed explanation:
Normalization ensures different syntactic variations are treated the same , e.g., extra spaces, letter/digit run-ons, HTML markup, and punctuation—so duplicates will match.
normalizeConditionParts extracts two sets (set1, set2) of conditions, sorts them, and joins them. This treats the two sets independently but normalized.
The two constructed keys key1 and key2 are swapped versions — this handles the case where swapping the two condition sets should identify the same rule (commutative sets).
The function uses a Map called seenRules to store the normalized keys and the first record encountered with that key.
When a new record's normalized key or its swapped variant matches one in seenRules, it is considered a duplicate.
The function collects duplicates in duplicateRecords, including the first record seen only once , then all subsequent duplicates.
In summary:
It finds duplicates based on normalized conditions (two sets, commutative), normalized actions, and the operator.
Duplicates share the same sets of conditions & actions, ignoring differences in order, punctuation, or HTML markup.
Returns a flat array of all duplicate records found (including the original first one for each duplicate group).
Use cases:
Prevent duplicate automation rules from being created.
Show a grouped list of duplicate rules for cleanup.
Help maintain clean, unique rule sets by catching similar rules expressed differently.
If you want, I can help convert this logic to return groups of duplicates or optimize further. Let me know!
// 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);
};
was this logic also based on like that or not?
const { set1, set2 } = normalizeConditionParts(conditions);
const normalizedActions = normalizeActions(actions);
const normalizedOperator = operator ? cleanText(operator) : "";
const key1 = `${set1}|${set2}|${normalizedActions}|${normalizedOperator}`;
const key2 = `${set2}|${set1}|${normalizedActions}|${normalizedOperator}`;
// Check if key1 or key2 already exists in the seen rules
if (seenRules.has(key1) || seenRules.has(key2)) {
const existing = seenRules.get(key1) || seenRules.get(key2);
if (!duplicateRecords.includes(existing)) {
duplicateRecords.push(existing);
}
duplicateRecords.push(record);
} else {
seenRules.set(key1, record);
}
return duplicateRecords;
};
change this to react js filter by passing rules as parameter
// 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);
};
give me correct logic of vanila js code into react correctly manage filter ideas
// Utility to normalize and group duplicate rules
export const findDuplicateRuleGroups = (rules) => {
// Helper: clean and normalize text consistently
const cleanText = (text) =>
String(text || "")
.toLowerCase()
.replace(/<img[^>]*>/gi, "")
.replace(/ /gi, " ")
.replace(/<[^>]*>/g, "")
.replace(/[,\.]/g, "")
.replace(/([a-zA-Z])(\d)/g, "$1 $2")
.replace(/(\d)([a-zA-Z])/g, "$1 $2")
.replace(/\s+/g, " ")
.trim()
.replace(/\bcomma\b\s*\bfull\s*stop\b/g, "comma fullstop");
// Normalize condition parts with sets and sorting
const normalizeConditionParts = (rawConditions) => {
let parts = [];
if (typeof rawConditions === "string") parts = rawConditions.split(",");
else if (Array.isArray(rawConditions)) parts = rawConditions;
else 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 array or string similarly
const normalizeActions = (actions) => {
if (Array.isArray(actions)) {
return actions
.map((action) =>
Object.values(action)
.map(cleanText)
.join(" ")
)
.sort()
.join(",");
} else if (typeof actions === "string") {
return actions
.split(",")
.map(cleanText)
.sort()
.join(",");
}
return "";
};
// Generate a normalized signature string for a rule (commutative set)
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);
const key1 = JSON.stringify({
set1,
set2,
actions: normalizedActions,
operator: normalizedOperator,
});
const key2 = JSON.stringify({
set1: set2,
set2: set1,
actions: normalizedActions,
operator: normalizedOperator,
});
return key1 < key2 ? key1 : key2; // lex smallest for commutative sets
};
const groupsMap = new Map();
// Iterate active rules and group by normalized signature
rules
.filter((r) => r.active === true || r.active === "true")
.forEach((rule) => {
const signature = getRuleSignatureNormalized(rule);
if (!groupsMap.has(signature)) groupsMap.set(signature, []);
groupsMap.get(signature).push(rule);
});
// Filter groups to only those with duplicates (more than 1 item)
const duplicateGroups = [];
for (const group of groupsMap.values()) {
if (group.length > 1) duplicateGroups.push(group);
}
return duplicateGroups; // array of duplicate groups (arrays)
};
Usage in React jsx Copy code
const MyComponent = ({ allRules }) => {
const duplicateGroups = React.useMemo(() => findDuplicateRuleGroups(allRules), [allRules]);
return (
<div>
{duplicateGroups.length === 0 ? (
<p>No duplicate rules found.</p>
) : (
duplicateGroups.map((group, idx) => (
<div key={idx}>
<h3>Duplicate Group {idx + 1}</h3>
<ul>
{group.map((rule) => (
<li key={rule.id}>{rule.name || rule.id}</li>
))}
</ul>
</div>
))
)}
</div>
);
};
Summary
The utility returns groups of duplicate rules.
You call it with your rules list and get back an array of groups.
Each group has 2+ rules that are considered duplicates.
Can be used in useMemo, or called on demand before rendering.
If you want your previous findDuplicateRulestype1and3 logic converted exactly or want further help integrating this into your state management or components, just ask!
import React from "react";
// Utility: clean and normalize text
const cleanText = (text) =>
String(text || "")
.toLowerCase()
.replace(/<img[^>]*>/gi, "") // remove <img> 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 $2") // split letters & digits
.replace(/(\d)([a-zA-Z])/g, "$1 $2")
.replace(/\s+/g, " ") // collapse spaces
.trim()
.replace(/\bcomma\b\s*\bfull\s*stop\b/g, "comma fullstop");
// Normalize condition parts considering condition set 1 and 2
const normalizeConditionParts = (rawConditions) => {
let parts = [];
if (typeof rawConditions === "string") {
parts = rawConditions.split(",");
} else if (Array.isArray(rawConditions)) {
parts = rawConditions;
} else {
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 - either string or array of objects
const normalizeActions = (actions) => {
if (Array.isArray(actions)) {
return actions
.map((action) =>
Object.values(action)
.map(cleanText)
.join(" ")
)
.sort()
.join(",");
} else if (typeof actions === "string") {
return actions
.split(",")
.map(cleanText)
.sort()
.join(",");
}
return "";
};
// Create normalized signature string for a rule
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);
// Create two keys swapping condition sets for commutativity
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 to handle sets considered equal when swapped
return key1 < key2 ? key1 : key2;
};
// Group rules by normalized signature
const groupDuplicates = (rules) => {
const groups = {};
rules
.filter((rule) => rule.active === "true" || rule.active === true) // Only active rules
.forEach((rule) => {
const signature = getRuleSignatureNormalized(rule);
if (!groups[signature]) groups[signature] = [];
groups[signature].push(rule);
});
return Object.values(groups);
};
// React component example
const DuplicateRulesList = ({ rules }) => {
// Memoize groups so calculation occurs only on rules change
const duplicateGroups = React.useMemo(() => {
return groupDuplicates(rules).filter(group => group.length > 1);
}, [rules]);
if (!rules || rules.length === 0) {
return <p>No rules to display.</p>;
}
if (duplicateGroups.length === 0) {
return <p>No duplicate rules found.</p>;
}
return (
<div>
{duplicateGroups.map((group, idx) => (
<div key={idx} style={{ marginBottom: '1rem', border: '1px solid #ddd', padding: '0.5rem' }}>
<h4>Duplicate Group {idx + 1} ({group.length} rules)</h4>
<ul>
{group.map(rule => (
<li key={rule.id || rule.rule_id || idx}>
<strong>{rule.name || "(Unnamed Rule)"}</strong> - ID: {rule.id || rule.rule_id || "N/A"}
</li>
))}
</ul>
</div>
))}
</div>
);
};
export default DuplicateRulesList;
How to use: Pass your rules array (each rule with conditions, actions, operator, active, etc.) as the rules prop:
jsx Copy code
<DuplicateRulesList rules={allLoadedRules} />
What happens:
Rules are normalized into signatures with commutative handling of condition sets.
Rules are grouped by signatures, only groups with duplicates (2+) are kept.
Displays groups with rule names and ids.
If you want me to help adapt this to your existing code or integrate it in your UI, please let me know!
this is the grouped does it match with these functions
normalized conditions + actions + operator
Grouping is robust vs differences in capitalization, HTML markup, white space, punctuation.
If you want to confirm, you can run groupDuplicates(yourRules) (with yourRules loaded from this JSON) and check the output groups.
Caveat:
Your functions assume a certain data shape:
conditions can be a string, array, or from .summary.conditions.
actions same.
Your sample data has conditions and actions both on the root and inside .summary.
Make sure you pick the consistent source (your getRuleSignatureNormalized prefers rule.summary?.conditions over rule.conditions).
If you want, I can help with a demo snippet that loads this data and shows how they get grouped!
import React from "react";
// Utility functions you provided (slightly reformatted for clarity):
const cleanText = (text) =>
String(text || "")
.toLowerCase()
.replace(/<img[^>]*>/gi, "")
.replace(/ /gi, " ")
.replace(/<[^>]*>/g, "")
.replace(/[,\.]/g, "")
.replace(/([a-zA-Z])(\d)/g, "$1 $2")
.replace(/(\d)([a-zA-Z])/g, "$1 $2")
.replace(/\s+/g, " ")
.trim()
.replace(/\bcomma\b\s*\bfull\s*stop\b/g, "comma fullstop");
const normalizeConditionParts = (rawConditions) => {
let parts = [];
if (typeof rawConditions === "string") {
parts = rawConditions.split(",");
} else if (Array.isArray(rawConditions)) {
parts = rawConditions;
} else {
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 };
};
const normalizeActions = (actions) => {
if (Array.isArray(actions)) {
return actions
.map((action) =>
Object.values(action)
.map(cleanText)
.join(" ")
)
.sort()
.join(",");
} else if (typeof actions === "string") {
return actions
.split(",")
.map(cleanText)
.sort()
.join(",");
}
return "";
};
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);
const key1 = JSON.stringify({ set1, set2, actions: normalizedActions, operator: normalizedOperator });
const key2 = JSON.stringify({ set1: set2, set2: set1, actions: normalizedActions, operator: normalizedOperator });
return key1 < key2 ? key1 : key2; // enforce canonical ordering
};
const groupDuplicates = (rules) => {
const groups = {};
rules
.filter((rule) => rule.active === "true" || rule.active === true)
.forEach((rule) => {
const sig = getRuleSignatureNormalized(rule);
if (!groups[sig]) groups[sig] = [];
groups[sig].push(rule);
});
// Only return groups with duplicates (more than one rule)
return Object.values(groups).filter(group => group.length > 1);
};
// Your sample rules array (shortened here for brevity, replace with your full data)
const sampleRules = [
{
name: "simple",
active: true,
id: 1,
summary: {
conditions: {
condition_set_1: [
"If <div class = SummaryKey>Subject</div> <div class = SummaryOperator>is</div> <div class = SummaryValue>we are great </div>"
]
},
actions: [
"<div class = SummaryKey>Delete ticket</div>"
]
},
},
{
name: "Copy of simple",
active: true,
id: 2,
summary: {
conditions: {
condition_set_1: [
"If <div class = SummaryKey>Subject</div> <div class = SummaryOperator>is</div> <div class = SummaryValue>We Are Great </div>"
]
},
actions: [
"<div class = SummaryKey>Delete ticket</div>"
]
},
},
{
name: "lol",
active: true,
id: 3,
summary: {
conditions: {
condition_set_1: [
"If <div class = SummaryKey>Subject or description</div> <div class = SummaryOperator>is</div> <div class = SummaryValue>we are</div>"
]
},
actions: [
"<div class = SummaryKey>Delete ticket</div>"
]
},
},
{
name: "Copy of lol",
active: true,
id: 4,
summary: {
conditions: {
condition_set_1: [
"If <div class = SummaryKey>Subject or description</div> <div class = SummaryOperator>is</div> <div class = SummaryValue>we are</div>"
]
},
actions: [
"<div class = SummaryKey>Delete ticket</div>"
]
},
},
];
const DuplicateGroupsDemo = () => {
const duplicateGroups = React.useMemo(() => groupDuplicates(sampleRules), []);
return (
<div>
<h2>Duplicate Groups Demo</h2>
{duplicateGroups.length === 0 ? (
<p>No duplicate rules found.</p>
) : (
duplicateGroups.map((group, i) => (
<div key={i} style={{ border: "1px solid gray", margin: "1rem 0", padding: "0.5rem" }}>
<h3>Duplicate Group {i + 1} ({group.length})</h3>
<ul>
{group.map(rule => (
<li key={rule.id}>
<b>{rule.name}</b> (ID: {rule.id})
</li>
))}
</ul>
</div>
))
)}
</div>
);
};
export default DuplicateGroupsDemo;
How to try:
Put this component into a React environment.
Replace the sampleRules with your full rules data.
You should see groups of duplicates with rule names and ids, grouped as expected even if minor differences like casing or HTML markup exist.
If you want me to help integrate this into your fuller app code or tweak the normalization, just ask!