import React, { useState, useEffect, useRef } from… · The Chat Archive
Explore / Programming import React, { useState, useEffect, useRef } from "react"; import { FwSpinner } from… Save Share Download ▾ Reportimport React, { useState, useEffect, useRef } from "react";
import { FwSpinner } from "@freshworks/crayons/react";
import Highcharts from "highcharts";
import HighchartsReact from "highcharts-react-official";
const variablePie = require("highcharts/modules/variable-pie");
const variablePieInit =
typeof variablePie === "function"
? variablePie
: variablePie?.default || (() => {});
variablePieInit(Highcharts);
const funnelModule = require("highcharts/modules/funnel");
const funnelInit =
typeof funnelModule === "function"
? funnelModule
: funnelModule?.default || (() => {});
funnelInit(Highcharts);
// Initialize the variable pie module
// variablePie(Highcharts);
import {
Chart as ChartJS,
ArcElement,
Tooltip,
Legend,
RadialLinearScale,
LinearScale,
CategoryScale,
RadarController,
LineElement,
PointElement,
} from "chart.js";
import { Radar } from "react-chartjs-2";
import { PolarArea, Doughnut } from "react-chartjs-2";
import ChartDataLabels from "chartjs-plugin-datalabels";
import { FunnelController, TrapezoidElement } from "chartjs-chart-funnel";
ChartJS.register(
ArcElement,
Tooltip,
Legend,
RadialLinearScale,
LinearScale,
CategoryScale,
ChartDataLabels,
FunnelController,
TrapezoidElement,
RadarController,
LineElement,
PointElement
);
const NoImpactFunnelChart = ({ noImpactRules }) => {
console.log("New No Impact at 6.48pm");
if (!noImpactRules || noImpactRules.length === 0)
return (
<div
style={{
padding: 20,
fontStyle: "italic",
color: "#666",
textAlign: "center",
backgroundColor: "#fafafa",
borderRadius: 8,
border: "1px solid #ddd",
maxWidth: 600,
margin: "auto",
boxShadow: "0 2px 5px rgba(0,0,0,0.05)",
}}
>
No No Impact rules to display
);
const rowHeightPx = 40;
// Limit rules to first 10 only
const displayRules = noImpactRules.slice(0, 10);
// Count commas and add 1 to get days in impactDiffWithDate
const getInactiveDays = (impactDiffWithDate) => {
if (!impactDiffWithDate) return 0;
return (impactDiffWithDate.match(/,/g) || []).length + 1;
};
return (
<>
{ /* Remove scroll-container max-height and overflow */ .scroll-container { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; border-radius: 12px; background-color: #fff; } }
Show full message · 705 lines Assistant2025-07-05 01:54 UTC Copy response
give me within that function itself
Assistant2025-07-05 01:54 UTC Copy response
Sure! Here's your updated parseImpact function rewritten so it calculates total impact only for the most recent 7 comma-separated entries (days) , all within the same function:
js Copy code
const parseImpact = (impactString) => {
console.log("🔍 Raw impact string:", impactString);
if (!impactString) return 0;
// Split into individual day-impact entries by comma
const dayEntries = impactString.split(',');
// Take only the last 7 entries (or less if fewer than 7)
const last7Entries = dayEntries.slice(-7);
// Extract the impact value from each entry, format assumed "date:value"
const values = last7Entries.map(entry => {
const parts = entry.split(':');
const val = parts[1] ? parseInt(parts[1], 10) : 0;
return isNaN(val) ? 0 : val;
});
const total = values.reduce((sum, val) => sum + val, 0);
console.log(`Summed impact of last 7 days: ${total}`);
return total;
};
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 2 (4 messages)
Language en
Conversation date Jul 5, 2025
Added to archive Nov 16, 2026
ID 01m7h42x6jf6mrv4cv4x3wdmvjSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 8b513a2d47dc5127d1935814a47318db
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
<div
style={{
maxWidth: 700,
overflow: "hidden",
fontFamily: "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
}}
>
<div className="scroll-container">
<table
style={{
width: "100%",
borderCollapse: "separate",
borderSpacing: 0,
minWidth: 500,
// allow table to expand naturally (no fixed height or max height)
}}
>
<thead>
<tr>
<th
style={{
backgroundColor: "#f5f9ff",
color: "#2a3f66",
padding: "12px 15px",
textAlign: "left",
fontWeight: "700",
borderBottom: "2px solid #c4d1f5",
position: "sticky",
top: 0,
zIndex: 2,
maxWidth: 100,
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
}}
>
Rule Name
</th>
<th
style={{
backgroundColor: "#f5f9ff",
color: "#2a3f66",
padding: "12px 40px",
textAlign: "center",
fontWeight: "700",
borderBottom: "2px solid #c4d1f5",
position: "sticky",
top: 0,
zIndex: 2,
width: 120,
}}
>
Days Inactive
</th>
</tr>
</thead>
<tbody>
{displayRules.map((rule, idx) => {
const inactiveDays = getInactiveDays(rule.impactDiffWithDate);
const tooltipContent = ${rule.name || "N/A"}\nInactive for ${inactiveDays} day${ inactiveDays > 1 ? "s" : "" };
code Copy code
return (
<tr
key={rule.id || idx}
style={{
height: 28,
backgroundColor: idx % 2 === 0 ? "#fff" : "#f9fbff",
transition: "background-color 0.3s ease",
cursor: "default",
}}
onMouseEnter={(e) => {
e.currentTarget.style.backgroundColor = "#d6e4ff";
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = idx % 2 === 0 ? "#fff" : "#f9fbff";
}}
>
<td
style={{
borderBottom: "1px solid #e5e9f2",
padding: "6px 10px", // reduced padding
color: "#2d3a5a",
fontSize: 15,
fontWeight: "500",
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
maxWidth: 300,
}}
title={tooltipContent}
>
{rule.name || "N/A"}
</td>
<td
style={{
borderBottom: "1px solid #e5e9f2",
padding: "6px 10px", // reduced padding
textAlign: "center",
color: "#4a6dff",
fontWeight: "600",
fontSize: 13,
userSelect: "none",
}}
title={tooltipContent}
>
{inactiveDays}
</td>
</tr>
);
const HighImpactColumnChart = ({ rules }) => {
if (!rules || !Array.isArray(rules) || rules.length === 0)
return No High Impact rules to display;
const filteredRules = rules.filter(rule => rule.impact > 0);
if (filteredRules.length === 0)
return No High Impact rules to display;
const data = filteredRules.map(rule => ({
name: rule.name || rule.id || Rule ${rule.rule_id},
y: rule.impact
}));
const totalImpact = filteredRules.reduce((sum, rule) => sum + rule.impact, 0);
const options = {
chart: {
type: 'column',
height: 300,
},
title: { text: '' },
subtitle: { text: '' },
xAxis: {
type: 'category',
labels: {
autoRotation: [-45, -90],
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif',
},
},
},
yAxis: {
min: 0,
title: {
text: 'Impact (tickets affected)',
},
labels: {
formatter: function () {
return this.value; // Show the actual number without abbreviation
},
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif',
},
},
},
legend: { enabled: false },
tooltip: {
formatter: function () {
const percentage = ((this.y / totalImpact) * 100).toFixed(2);
return <b>${this.point.name}</b><br/>Impact: <b>${this.y}</b><br/>Percentage: <b>${percentage}%</b>;
}
},
series: [
{
name: 'Impact',
colorByPoint: true,
groupPadding: 0,
data,
dataLabels: {
enabled: true,
color: '#000000',
verticalAlign: 'bottom',
inside: false,
format: '{y}',
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif',
},
},
}
],
colors: [
'#9b20d9', '#9215ac', '#861ec9', '#7a17e6', '#7010f9', '#691af3',
'#6225ed', '#5b30e7', '#533be1', '#4c46db', '#4551d5', '#3e5ccf',
'#3667c9', '#2f72c3', '#277dbd', '#1f88b7', '#1693b1', '#0a9eaa',
'#03c69b', '#00f194'
],
credits: { enabled: false },
};
const LowImpactVariablePieChart = ({ rules }) => {
if (!rules || rules.length === 0)
return (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "100%", // or a fixed height like 200px if you want
fontSize: 18,
color: "#666",
minHeight: 150 // or whatever fits your layout
}}
>
No Low Impact rules to display
);
const data = rules.map((rule) => ({
name: rule.name || rule.id || Rule ${rule.rule_id},
y: rule.impact,
z: rule.impact, // same value used for radius - modify if you have other metric
}));
const colors = [
'#4caefe',
'#3dc3e8',
'#2dd9db',
'#1feeaf',
'#0ff3a0',
'#00e887',
'#23e274',
'#a3cb38',
'#f7b731',
'#fc5c65'
];
const options = {
chart: {
type: 'variablepie',
height: 400,
},
title: {
text: '',
},
tooltip: {
headerFormat: '',
pointFormatter: function () {
return ${this.name}<br/>Impact: <b>${this.y}</b><br/>Percentage: <b>${this.percentage.toFixed(2)}%</b>;
}
},
code Copy code
plotOptions: {
variablepie: {
dataLabels: {
enabled: true,
formatter: function() {
return `${this.point.percentage.toFixed(1)}%`;
},
color: '#000',
style: {
fontWeight: 'bold',
textOutline: 'none'
}
}
}
},
series: [{
minPointSize: 10,
innerSize: '20%',
zMin: 0,
colors,
name: 'Rules',
data,
borderRadius: 5,
}],
credits: { enabled: false },
const LoadingWrapper = ({ loading, children }) => {
if (loading) {
return (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: 340,
marginLeft:-50
}}
>
);
}
return children;
};
const Workflow_dashboard = ({ client }) => {
const [timerSeconds, setTimerSeconds] = useState(null);
const [processingDone, setProcessingDone] = useState(false);
const [storedvalue1, setStoredvalue1] = useState(null);
const intervalRef = useRef(null);
const newRulePloadDB6 = useRef(null);
const [impactStats, setImpactStats] = useState({});
const ticketCreate = 1;
const ticketUpdate = 4;
const hourlyTriggers = 3;
const parseImpact = (impactString) => {
console.log("🔍 Raw impact string:", impactString);
code Copy code
let totalCommaChar_ = (impactString.match(/,/g) || []).length;
// console.log("🧮 Total comma-separated entries:", totalCommaChar_);
if (totalCommaChar_ > 35) {
let d = new Date();
d.setMonth(d.getMonth() - 1);
let lastDate = d.toLocaleDateString();
// console.log("📆 Too many entries, splitting from date:", lastDate);
let splitParts = impactString.split(`${lastDate}`);
// console.log("🧩 After split:", splitParts);
impactString = splitParts[1] || splitParts[0];
// console.log("✅ Trimmed impact string:", impactString);
}
const arrStr = impactString.split(/[:,]/).filter((el, i) => i % 2);
// console.log("🔢 Extracted numeric values:", arrStr);
const total = arrStr.reduce((sum, val) => sum + (parseInt(val) || 0), 0);
// console.log("🧾 Total impact:", total);
return total;
const analyzeRules = (records, typeLabel) => {
const activeRules = records.filter((r) => r.active === "true");
code Copy code
const rulesWithImpact = activeRules.map((r) => {
const impact = parseImpact(r.impactDiffWithDate || "0:0");
return { ...r, impact };
});
const noImpactRules = rulesWithImpact.filter((r) => r.impact === 0);
const sortedByImpact = [...rulesWithImpact].sort((a, b) => b.impact - a.impact);
const top10High = sortedByImpact.slice(0, 10);
const top10Low = sortedByImpact.filter((r) => r.impact > 0).slice(-10);
console.log(`🔹 ${typeLabel} ➤ Top 10 Highest Impact Rules (${top10High.length}):`);
console.log(top10High.map((r) => `${r.name} (${r.impact})`));
console.log(`🔹 ${typeLabel} ➤ Top 10 Lowest Impact Rules (${top10Low.length}):`);
console.log(top10Low.map((r) => `${r.name} (${r.impact})`));
console.log(`🔹 ${typeLabel} ➤ No Impact Rules (${noImpactRules.length})`);
console.log(noImpactRules);
return {
noImpactRules, //
topHigh: top10High,
topLow: top10Low,
};
const Filterrecords = async (automationTypeId, dbInstance, typeLabel) => {
let allRecords = [];
let nextMarker = null;
code Copy code
try {
do {
const queryObj = { query: { automation_type_id: automationTypeId } };
if (nextMarker) queryObj.next = { marker: nextMarker };
const response = await dbInstance.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,
}));
allRecords = allRecords.concat(filtered);
nextMarker = response.links?.next?.marker || null;
} while (nextMarker);
allRecords.sort((a, b) => {
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);
console.log(`✅ Filtered Records for Type ${automationTypeId}:`, JSON.stringify(allRecords[0], null, 2));
return analyzeRules(allRecords, typeLabel);
} catch (error) {
console.error("❌ Error fetching filtered records:", error);
return { noImpactCount: 0, topHigh: [], topLow: [], topDuplicates: [] };
}
const handleFilterRecords = async () => {
const dbInstance = newRulePloadDB6.current;
if (!dbInstance) return;
code Copy code
const creationStats = await Filterrecords(ticketCreate, dbInstance, "Create");
const updateStats = await Filterrecords(ticketUpdate, dbInstance, "Update");
const hourlyStats = await Filterrecords(hourlyTriggers, dbInstance, "Hourly");
setImpactStats({ create: creationStats, update: updateStats, hourly: hourlyStats });
useEffect(() => {
const initDB = async () => {
try {
const entity = await client.db.entity({ version: "v1" });
newRulePloadDB6.current = entity.get("newRulePloadDB6");
} catch (error) {
console.error("Failed to init DB:", error);
}
};
initDB();
}, [client]);
useEffect(() => {
const fetchStored = async () => {
try {
const val = await client.db.get("RulesDB");
setStoredvalue1(val);
} catch (err) {
console.error("Error fetching RulesDB:", err);
setStoredvalue1(null);
}
};
fetchStored();
const interval = setInterval(fetchStored, 60000);
return () => clearInterval(interval);
}, [client]);
useEffect(() => {
if (!storedvalue1) return;
const itemsPerPage = 100;
const secondsPerPage = 60;
const fixedOverhead = 60;
code Copy code
const getTime = (count) =>
count > 0 ? Math.ceil(count / itemsPerPage) * secondsPerPage + fixedOverhead : 0;
const creationTime = getTime(storedvalue1.creationTotal || 0);
const hourlyTime = getTime(storedvalue1.hourlyTotal || 0);
const updateTime = getTime(storedvalue1.updateTotal || 0);
const totalTime = creationTime + hourlyTime + updateTime;
if (totalTime <= 0) {
setTimerSeconds(null);
setProcessingDone(true);
return;
}
setTimerSeconds(totalTime);
setProcessingDone(false);
let remaining = totalTime;
if (intervalRef.current) clearInterval(intervalRef.current);
intervalRef.current = setInterval(() => {
remaining -= 1;
setTimerSeconds(remaining);
if (remaining <= 0) {
clearInterval(intervalRef.current);
intervalRef.current = null;
setTimerSeconds(0);
setProcessingDone(true);
}
}, 1000);
return () => clearInterval(intervalRef.current);
useEffect(() => {
if (processingDone && newRulePloadDB6.current) {
handleFilterRecords();
}
}, [processingDone, newRulePloadDB6.current]);
code Copy code
{/* Render each rule individually so you can add separate styling */}
{["create", "update", "hourly"].map((key) => {
const stats = impactStats[key];
const isLoading = !stats; // if stats object is null/undefined – treat as loading
return (
<div key={key} style={{ /* your existing styles */ }}>
<h2 style={{ marginBottom: 20 }}>{key.toUpperCase()} Rules
code Copy code
<div style={{
display: "flex",
justifyContent: "space-between",
backgroundColor: "#f4f4f48c", // brown card
padding: 20,
gap: 20,
flexWrap: "wrap",
}}>
<div style={{ flex: "1", maxWidth: 500, backgroundColor: "#fff", padding: 10, color: "#000" }}>
<h4>🎯 Top 10 High Impact</h4>
<LoadingWrapper loading={isLoading}>
<HighImpactColumnChart rules={stats?.topHigh || []} />
</LoadingWrapper>
</div>
<div style={{ flex: "1", maxWidth: 500, backgroundColor: "#fff", padding: 10, color: "#000" }}>
<h4>📡 Top 10 Low Impact</h4>
<LoadingWrapper loading={isLoading}>
<LowImpactVariablePieChart rules={stats?.topLow || []} />
</LoadingWrapper>
</div>
<div style={{
flex: "1",
maxWidth: 500,
backgroundColor: "#fff",
padding: 10,
display: "flex",
flexDirection: "column",
justifyContent: "space-between",
color: "#000",
}}>
<h4>🚫 No Impact</h4>
<div style={{ height: 400, maxWidth: 500, backgroundColor: "#fff", borderRadius: 10, padding: 10 }}>
<LoadingWrapper loading={isLoading}>
<NoImpactFunnelChart noImpactRules={stats?.noImpactRules || []} />
</LoadingWrapper>
</div>
</div>
</div>
</div>
export default Workflow_dashboard;
in this, on calculating date based on comma, calculate recent 7 days comma count (like last from )
To adjust your parseImpact function or related logic so that it only calculates the impact from the most recent 7 days based on commas in the impactDiffWithDate string , you need to:
Identify the last 7 comma-separated entries corresponding to recent 7 days.
Sum only those entries.
Your current parseImpact is:
js Copy code
const parseImpact = (impactString) => {
console.log("🔍 Raw impact string:", impactString);
let totalCommaChar_ = (impactString.match(/,/g) || []).length;
if (totalCommaChar_ > 35) {
let d = new Date();
d.setMonth(d.getMonth() - 1);
let lastDate = d.toLocaleDateString();
let splitParts = impactString.split(`${lastDate}`);
impactString = splitParts[1] || splitParts[0];
}
const arrStr = impactString.split(/[:,]/).filter((el, i) => i % 2);
const total = arrStr.reduce((sum, val) => sum + (parseInt(val) || 0), 0);
return total;
};
Modify to sum only last 7 days (last 7 numeric entries after splitting):
Assuming your string is in the format something like this:
code Copy code
"date1:value1,date2:value2,..."
Split by commas to get entries per day.
Extract last 7 entries (if less, take all).
Extract impact number from each entry.
Sum these.
Modified parseImpactLast7Days function:
js Copy code
const parseImpactLast7Days = (impactString) => {
console.log("🔍 Raw impact string:", impactString);
if (!impactString) return 0;
// Split by comma to get each day: e.g. ["date1:value1", "date2:value2", ...]
const dayEntries = impactString.split(',');
// Take last 7 entries (or less if not enough)
const last7DaysEntries = dayEntries.slice(-7);
// Extract impact values (assuming format "date:value")
const values = last7DaysEntries.map(entry => {
// Split by colon to get impact value
const parts = entry.split(':');
const val = parts[1] ? parseInt(parts[1], 10) : 0;
return isNaN(val) ? 0 : val;
});
const total = values.reduce((sum, val) => sum + val, 0);
console.log(`Summed impact of last 7 days: ${total}`);
return total;
};
Where to replace in your code?
Replace inside your analyzeRules where you call parseImpact:
From:
js Copy code
const impact = parseImpact(r.impactDiffWithDate || "0:0");
To:
js Copy code
const impact = parseImpactLast7Days(r.impactDiffWithDate || "");
Notes:
This approach strictly sums up impact values from the last 7 entries (latest 7 days), works under the assumption that the impactDiffWithDate string is ordered chronologically.
If the date formatting is irregular, or you want robust date parsing, you might want to parse dates properly and filter by date ranges, but your request referred to counting commas to get last 7 days, so this approach matches that.
If you want me to help you integrate this cleanly in your existing code or adapt to existing logic, just ask!
Just replace your existing parseImpact function with this. It will:
Split the input string by commas,
Grab the last 7 entries,
Parse out the number after :,
Sum those numbers,
Return the total.
Let me know if you want me to integrate it into your full code!
Copy first response
Not yet included in a published release.