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

if (containerid === "Ticketcreation" && storedvalue1.creationTotal === 0) {…

  1. User

    if (containerid === "Ticketcreation" && storedvalue1.creationTotal === 0) { handleDuplicateRulestype(1); } else if (containerid === "HourlyTriggers" && storedvalue1.hourlyTotal === 0) { handleDuplicateRulestype(3); } else if (containerid === "TicketUpdates" && storedvalue1.updateTotal === 0) { handleDuplicateRulestype(4); }

    like this add functionality in this part

    /* Start timers when storedvalue1 (RulesDB data) changes */ useEffect(() => {

    if (!storedvalue1) return;

    // Ticket Creation if (storedvalue1.creationTotal > 0) { const duration = getDurationForTotal(storedvalue1.creationTotal); startTimer("ticketcreate", duration); } else { setTimers((prev) => ({ ...prev, ticketcreate: null })); }

    // Ticket Updates if (storedvalue1.updateTotal > 0) { const duration = getDurationForTotal(storedvalue1.creationTotal) + getDurationForTotal(storedvalue1.hourlyTotal) + getDurationForTotal(storedvalue1.updateTotal); startTimer("ticketupdate", duration); } else { setTimers((prev) => ({ ...prev, ticketupdate: null })); }

    // Hourly Triggers if (storedvalue1.hourlyTotal > 0) { const duration = getDurationForTotal(storedvalue1.creationTotal) + getDurationForTotal(storedvalue1.hourlyTotal); startTimer("hourly", duration); } else { setTimers((prev) => ({ ...prev, hourly: null })); }

    return () => { Object.values(timerIntervals.current).forEach((t) => clearInterval(t)); }; }, [storedvalue1]);

    with this

    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); }

    show if tmer is 0 fetch separate when timer comes to zero

  2. Assistant

    Got it! You want to enhance your existing useEffect where the timers are started or cleared based on storedvalue1, and when the timer reaches zero (or initially if the count is 0), to fetch corresponding data (by calling Filterrecords for each tab) asynchronously.

    Here's a detailed approach to achieve this:


    Plan:

    1. When storedvalue1 changes:

      • If the relevant totals are > 0, start timers as you already do.
      • If totals are 0, fetch the rules immediately for that tab.
    2. When a timer reaches 0 (I assume the timer callback will be somewhere else):

      • Fetch the data again for that tab.

    Step 1: Modify your useEffect to initiate fetching immediately if totals are 0.

    Assuming you have functions:

    • Filterrecords
    • Data containers: ticketCreate, ticketUpdate, hourlyTriggers
    • State setters: setTicketCreationRules, setTicketUpdateRules, setHourlyTriggerRules

    You can make useEffect async and fetch data when totals are 0.


    Step 2: You need a separate effect or callback that runs when each timer becomes 0.

    If you have control over the timer's decrement logic (e.g., with setInterval), then when the timer hits zero, call the fetch function for the appropriate tab.


    IMPLEMENTATION

    useEffect(() => {
      if (!storedvalue1) return;
    
      // Helper function to fetch rules for a given tab name
      const fetchRulesForTab = async (activeTab) => {
        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);
        }
      };
    
      // Ticket Creation
      if (storedvalue1.creationTotal > 0) {
        const duration = getDurationForTotal(storedvalue1.creationTotal);
        startTimer("ticketcreate", duration);
      } else {
        setTimers((prev) => ({ ...prev, ticketcreate: null }));
        // Fetch immediately if timer is effectively zero
        fetchRulesForTab("ticketcreate");
      }
    
      // Ticket Updates
      if (storedvalue1.updateTotal > 0) {
        const duration =
          getDurationForTotal(storedvalue1.creationTotal) +
          getDurationForTotal(storedvalue1.hourlyTotal) +
          getDurationForTotal(storedvalue1.updateTotal);
        startTimer("ticketupdate", duration);
      } else {
        setTimers((prev) => ({ ...prev, ticketupdate: null }));
        fetchRulesForTab("ticketupdate");
      }
    
      // Hourly Triggers
      if (storedvalue1.hourlyTotal > 0) {
        const duration =
          getDurationForTotal(storedvalue1.creationTotal) +
          getDurationForTotal(storedvalue1.hourlyTotal);
        startTimer("hourly", duration);
      } else {
        setTimers((prev) => ({ ...prev, hourly: null }));
        fetchRulesForTab("hourly");
      }
    
      return () => {
        // Clear intervals on cleanup
        Object.values(timerIntervals.current).forEach((t) => clearInterval(t));
      };
    }, [storedvalue1]);
    
    // ----------------------------------------
    // Step 3: Add callback for when timers reach zero (example implementation)
    // ----------------------------------------
    
    const onTimerComplete = useCallback(async (activeTab) => {
      // When timer reaches zero, fetch the latest rules
      if (activeTab) {
        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);
        }
      }
    }, []);
    

    Notes:

    • startTimer function must accept a callback or some way to notify when the timer reaches zero, so you can call onTimerComplete(tab) accordingly.
    • For example, you might modify startTimer:
    function startTimer(tab, duration) {
      // Clear any existing timer
      if (timerIntervals.current[tab]) clearInterval(timerIntervals.current[tab]);
    
      let timeLeft = duration;
    
      timerIntervals.current[tab] = setInterval(() => {
        timeLeft -= 1; // assuming decrement by 1 sec or your base unit
    
        if (timeLeft <= 0) {
          clearInterval(timerIntervals.current[tab]);
          timerIntervals.current[tab] = null;
    
          onTimerComplete(tab);  // call when timer finishes
        } else {
          // update timer states if you want
          setTimers(prev => ({ ...prev, [tab]: timeLeft }));
        }
      }, 1000);
    }
    

    Summary:

    • When counts are 0, fetch corresponding rules immediately.
    • When counts are > 0, start timer.
    • When the timer hits zero, fetch associated rules again.
    • You need to modify your startTimer to call back onTimerComplete when timer ends.

    Let me know if you want me to provide a full working snippet with dummy startTimer and other code integrated!

  3. User

    /* Timer start function */ const startTimer = (tabKey, duration) => { if (timerIntervals.current[tabKey]) { clearInterval(timerIntervals.current[tabKey]); }

    setTimers((prev) => ({ ...prev, [tabKey]: duration, }));

    timerIntervals.current[tabKey] = setInterval(() => { setTimers((prev) => { if (!prev[tabKey]) return prev; const newTime = prev[tabKey] - 1; if (newTime <= 0) { clearInterval(timerIntervals.current[tabKey]); timerIntervals.current[tabKey] = null; return { ...prev, [tabKey]: null }; } return { ...prev, [tabKey]: newTime }; }); }, 1000); };

    /* Start timers when storedvalue1 (RulesDB data) changes */ useEffect(() => {

    if (!storedvalue1) return;

    // Ticket Creation if (storedvalue1.creationTotal > 0) { const duration = getDurationForTotal(storedvalue1.creationTotal); startTimer("ticketcreate", duration); } else { setTimers((prev) => ({ ...prev, ticketcreate: null })); }

    // Ticket Updates if (storedvalue1.updateTotal > 0) { const duration = getDurationForTotal(storedvalue1.creationTotal) + getDurationForTotal(storedvalue1.hourlyTotal) + getDurationForTotal(storedvalue1.updateTotal); startTimer("ticketupdate", duration); } else { setTimers((prev) => ({ ...prev, ticketupdate: null })); }

    // Hourly Triggers if (storedvalue1.hourlyTotal > 0) { const duration = getDurationForTotal(storedvalue1.creationTotal) + getDurationForTotal(storedvalue1.hourlyTotal); startTimer("hourly", duration); } else { setTimers((prev) => ({ ...prev, hourly: null })); }

    return () => { Object.values(timerIntervals.current).forEach((t) => clearInterval(t)); }; }, [storedvalue1]);

    i have it. when a tab comes to zero check what tab and fetch and show the data

  4. Assistant

    You already have a nice timer setup where you decrement the timer every second and clear it when it reaches zero via startTimer. Now you want to detect when a timer reaches 0, know which tab reached zero, and then fetch and show the data for that tab.


    How to do this?

    You are using setTimers inside a state updater callback, so right after the timer reaches zero, you can trigger your data fetching logic by running a side effect whenever a timer value switches from a positive number to null.


    Step 1: Add a useEffect watching your timer state (timers)

    useEffect(() => {
      // timers is an object like { ticketcreate: number|null, ticketupdate: number|null, hourly: number|null }
      
      const fetchDataForTab = async (tabKey) => {
        if (tabKey === "ticketcreate") {
          const data = await Filterrecords(ticketCreate, newRulePloadDB5.current);
          setTicketCreationRules(data);
        } else if (tabKey === "ticketupdate") {
          const data = await Filterrecords(ticketUpdate, newRulePloadDB5.current);
          setTicketUpdateRules(data);
        } else if (tabKey === "hourly") {
          const data = await Filterrecords(hourlyTriggers, newRulePloadDB5.current);
          setHourlyTriggerRules(data);
        }
      };
    
      // Check timers for ones that became null (ie: just hit zero)
      Object.entries(timers).forEach(([tabKey, time]) => {
        // If timer is null (meaning finished), fetch data.
        // Optionally track previous value to avoid repeated fetches.
        if (time === null) {
          fetchDataForTab(tabKey);
        }
      });
    }, [timers]);
    

    Optional Improvement: Avoid fetching repeatedly on every render when timers[tabKey] stays null

    To avoid repeated fetches (because once timer is null, the effect runs whenever timers changes), you can use a ref to track which tabs have already been fetched after timer end.

    const fetchedAfterTimerEnd = useRef({}); // e.g. { ticketcreate: true }
    
    useEffect(() => {
      const fetchDataForTab = async (tabKey) => {
        if (tabKey === "ticketcreate") {
          const data = await Filterrecords(ticketCreate, newRulePloadDB5.current);
          setTicketCreationRules(data);
        } else if (tabKey === "ticketupdate") {
          const data = await Filterrecords(ticketUpdate, newRulePloadDB5.current);
          setTicketUpdateRules(data);
        } else if (tabKey === "hourly") {
          const data = await Filterrecords(hourlyTriggers, newRulePloadDB5.current);
          setHourlyTriggerRules(data);
        }
      };
    
      Object.entries(timers).forEach(([tabKey, time]) => {
        if (time === null && !fetchedAfterTimerEnd.current[tabKey]) {
          fetchedAfterTimerEnd.current[tabKey] = true;  // mark fetched
          fetchDataForTab(tabKey);
        }
    
        // Optionally reset fetchedAfterTimerEnd when timer restarts
        if (time !== null && fetchedAfterTimerEnd.current[tabKey]) {
          fetchedAfterTimerEnd.current[tabKey] = false;
        }
      });
    
    }, [timers]);
    

    Summary:

    • Your existing startTimer handles decrementing and setting timer to null at zero.
    • Use an effect that listens to timers state changes.
    • When a timer changes to null, trigger your fetch for that tab.
    • Use a ref to avoid multiple fetches for the same zero event.

    If you want, I can help you integrate this fully with your existing code!

  5. User

    give me what to add in my code

  6. Assistant

    Sure! Here's exactly what you need to add to your existing code to fetch and show data when a timer reaches zero:


    1. Add this at the top of your component (above your useEffects):

    const fetchedAfterTimerEnd = useRef({
      ticketcreate: false,
      ticketupdate: false,
      hourly: false,
    });
    

    2. Add this new useEffect below your existing useEffect (that starts timers):

    useEffect(() => {
      const fetchDataForTab = async (tabKey) => {
        if (tabKey === "ticketcreate") {
          const data = await Filterrecords(ticketCreate, newRulePloadDB5.current);
          setTicketCreationRules(data);
        } else if (tabKey === "ticketupdate") {
          const data = await Filterrecords(ticketUpdate, newRulePloadDB5.current);
          setTicketUpdateRules(data);
        } else if (tabKey === "hourly") {
          const data = await Filterrecords(hourlyTriggers, newRulePloadDB5.current);
          setHourlyTriggerRules(data);
        }
      };
    
      Object.entries(timers).forEach(([tabKey, time]) => {
        // If timer reached zero (null) and we haven't fetched yet
        if (time === null && !fetchedAfterTimerEnd.current[tabKey]) {
          fetchedAfterTimerEnd.current[tabKey] = true;
          fetchDataForTab(tabKey);
        }
    
        // Reset flag if timer restarts (> 0)
        if (time !== null && fetchedAfterTimerEnd.current[tabKey]) {
          fetchedAfterTimerEnd.current[tabKey] = false;
        }
      });
    }, [timers]);
    

    Explanation:

    • This watches timers state.
    • When any timer changes to null (meaning it ended), it fetches data for that tab once.
    • When timer restarts, the fetched flag resets so fetching can happen again next time timer ends.

    No other changes needed—your existing startTimer and timer-setting effect will continue working as they are.


    If you want me to combine this with your full snippet, just ask!

  7. User

    async function checkAndSetButtonState1(data, containerid) { try {

    localStorage.setItem("checkState_data", JSON.stringify(data));
    localStorage.setItem("checkState_containerid", containerid);
    
    console.log("automationtypeid inside checkAndSetButtonState",data);
    
    console.log("Initially stored all value from RulesDB:", storedvalue1);
    console.log("creationtotal",storedvalue1.creationTotal);
    console.log("hourlyTotal",storedvalue1.hourlyTotal);
    console.log("updateTotal",storedvalue1.updateTotal);
    console.log("Initial stored true/false value from RulesDB:", storedvalue1.stored);
    
    
    
    if (containerid === "Ticketcreation" && storedvalue1.creationTotal > 0) {
      showLoader("Ticketcreation");
      const duration = getDurationForTotal(storedvalue1.creationTotal);
    
      if (typeof duration !== "number" || isNaN(duration)) {
        console.error("❌ Invalid duration calculated. Skipping timer setup.");
        return;
      }
    
      console.log(`✅ Timer condition met. Setting timer for ${duration} seconds.`);
    
      const container = document.getElementById("Ticketcreation");
      if (!container) {
        console.error("❌ Ticketcreation container not found.");
        return;
      }
    
      const timerId = "simple-timer-Ticketcreation";
      if (document.getElementById(timerId)) {
        console.log("⚠️ Timer already running for Ticketcreation. Skipping new timer setup.");
        return;
      }
    
      // Create timer
      const timerDiv = document.createElement("div");
      timerDiv.id = timerId;
      timerDiv.style.cssText = `
      position: fixed;
      top: 63%;
      left: 50%;
      transform: translateX(-50%);
     
      color: black;
      padding: 10px 20px;
      border-radius: 5px;
      font-family: sans-serif;
      font-size: 16px;
      z-index: 9999;
    `;
      timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${duration} sec...`;
      container.appendChild(timerDiv);
    
      let remaining = duration;
      const interval = setInterval(() => {
        remaining--;
        timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${remaining} sec...`;
    
        if (remaining <= 0) {
          clearInterval(interval);
          timerDiv.remove();
          console.log("Ticketcreation timer ended. Calling handleDuplicateRulestype(1).");
          handleDuplicateRulestype(1);
        }
      }, 1000);
    }
    else if (containerid === "HourlyTriggers" && storedvalue1.hourlyTotal > 0) {
      showLoader("HourlyTriggers");
    
      const creationDuration = getDurationForTotal(storedvalue1.creationTotal);
      const hourlyDuration = getDurationForTotal(storedvalue1.hourlyTotal);
      const totalDuration = creationDuration + hourlyDuration;
    
      if (typeof totalDuration !== "number" || isNaN(totalDuration)) {
        console.error("❌ Invalid duration calculated. Skipping timer setup.");
        return;
      }
    
      console.log(`✅ Timer condition met. Setting timer for ${totalDuration} seconds.`);
    
      const container = document.getElementById("HourlyTriggers");
      if (!container) {
        console.error("❌ HourlyTriggers container not found.");
        return;
      }
    
      const timerId = "simple-timer-HourlyTriggers";
      if (document.getElementById(timerId)) {
        console.log("⚠️ Timer already running for HourlyTriggers. Skipping new timer setup.");
        return;
      }
    
      // Create timer
      const timerDiv = document.createElement("div");
      timerDiv.id = timerId;
      timerDiv.style.cssText = `
     position: fixed;
      top: 63%;
      left: 50%;
      transform: translateX(-50%);
     
      color: black;
      padding: 10px 20px;
      border-radius: 5px;
      font-family: sans-serif;
      font-size: 16px;
      z-index: 9999;
    `;
      timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${totalDuration} sec...`;
      container.appendChild(timerDiv);
    
      let remaining = totalDuration;
      const interval = setInterval(() => {
        remaining--;
        timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${remaining} sec...`;
    
        if (remaining <= 0) {
          clearInterval(interval);
          timerDiv.remove();
          console.log("✅ HourlyTriggers timer ended. Calling handleDuplicateRulestype(3).");
          handleDuplicateRulestype(3);
        }
      }, 1000);
    }
    else if (containerid === "TicketUpdates" && storedvalue1.updateTotal > 0) {
      showLoader("TicketUpdates");
      const creationDuration = getDurationForTotal(storedvalue1.creationTotal);
      const hourlyDuration = getDurationForTotal(storedvalue1.hourlyTotal);
      const updateDuration = getDurationForTotal(storedvalue1.updateTotal);
    
      const totalDuration = creationDuration + hourlyDuration + updateDuration;
    
      if (typeof totalDuration !== "number" || isNaN(totalDuration)) {
        console.error("❌ Invalid duration calculated. Skipping timer setup.");
        return;
      }
    
      console.log(`✅ Timer condition met. Setting timer for ${totalDuration} seconds.`);
    
      const timerId = "simple-timer-TicketUpdates";
      if (document.getElementById(timerId)) {
        console.log("⚠️ Timer already running for TicketUpdates. Skipping new timer setup.");
        return;
      }
    
      const container = document.getElementById("TicketUpdates");
      if (!container) {
        console.error("❌ TicketUpdates container not found.");
        return;
      }
    
      // Create the timer element
      const timerDiv = document.createElement("div");
      timerDiv.id = timerId;
      timerDiv.style.cssText = `
       position: fixed;
      top: 63%;
      left: 50%;
      transform: translateX(-50%);
     
      color: black;
      padding: 10px 20px;
      border-radius: 5px;
      font-family: sans-serif;
      font-size: 16px;
      z-index: 9999;
      `;
      timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${totalDuration} sec...`;
      container.appendChild(timerDiv);
    
      let remaining = totalDuration;
      const interval = setInterval(() => {
        remaining--;
        timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after  ${remaining} sec...`;
    
        if (remaining <= 0) {
          clearInterval(interval);
          timerDiv.remove();
          console.log("✅ TicketUpdates timer ended. Calling handleDuplicateRulestype(4).");
          handleDuplicateRulestype(4);
        }
      }, 1000);
    }
    
    
    
    
    if (
      storedvalue1.creationTotal === 0 ||
      storedvalue1.hourlyTotal === 0 ||
      storedvalue1.updateTotal === 0
    ) {
      await initializeDatabase();
    }
    
    if(containerid === "Ticketcreation" && storedvalue1.creationTotal === 0){
      handleDuplicateRulestype(1);
    } else if(containerid === "HourlyTriggers" && storedvalue1.hourlyTotal=== 0){
      handleDuplicateRulestype(3);
    }else if (containerid === "TicketUpdates" && storedvalue1.updateTotal === 0)
    {
      handleDuplicateRulestype(4);
    }
    if (containerid === "Ticketcreation" &&
      Number(storedvalue1.creationTotal) === 0 &&
      storedvalue1.stored === true
    )
    {
      handleDuplicateRulestype(1);
    } else if(containerid === "HourlyTriggers" && storedvalue1.hourlyTotal=== 0 && storedvalue1.stored === true){
      handleDuplicateRulestype(3);
    }else if (containerid === "TicketUpdates" && storedvalue1.updateTotal === 0 && storedvalue1.stored === true)
    {
      handleDuplicateRulestype(4);
    }
    
    

    } catch (error) { if (error.status === 404) { console.warn("⚠️ RulesDB not found, assuming first-time install."); const button = document.querySelector("fw-button"); if (button) { button.disabled = true; } } else { console.error("❌ Error retrieving stored value from RulesDB:", error); } } }

    in this how is handled is this code and the code you gave are functionality by same or not?

  8. Assistant

    Great question! Let's clarify the difference and overlap between your checkAndSetButtonState1 function and the timer logic I helped you with earlier.


    What your checkAndSetButtonState1 is doing:

    1. Manually creating and displaying timers for UI inside specific container elements (Ticketcreation, HourlyTriggers, TicketUpdates).
    2. Using manual setInterval inside this function to count down the timer in seconds and update DOM elements.
    3. When the timer ends, it calls handleDuplicateRulestype with the correct argument (1, 3, or 4).
    4. When the respective totals are zero, or a stored flag is true with zero totals, it directly calls handleDuplicateRulestype without a timer.
    5. Also calls initializeDatabase if any of the totals are zero before proceeding.

    What my earlier suggested timer code is doing:

    1. Using React state (timers) and useEffect to centrally manage timers for all tabs.
    2. Timer values stored in React state, decremented every second via setInterval inside startTimer.
    3. When a timer reaches zero (timer state becomes null), we use a React useEffect watching the timers state to trigger the fetching of new data asynchronously and update your rules state.
    4. The fetching uses your Filterrecords function and sets your rules into React state (presumably for showing in UI).
    5. Using a fetchedAfterTimerEnd ref to prevent redundant fetches.

    Are they the same functionality?

    Partially related, but not the same:

    • Your checkAndSetButtonState1 function:

      • Manages timers by directly manipulating the DOM.
      • Shows a message on the page saying "processing data, please refresh after X seconds".
      • Calls handleDuplicateRulestype when timer ends or when counts are 0.
      • It’s a manual, imperative approach managing countdowns & UI outside React state.
    • My suggested useEffect + startTimer logic:

      • Fully manages timers inside the React lifecycle & React state.
      • Handles timer countdown updates in React state.
      • Triggers fetching and updating your React UI data when timers reach zero.
      • It’s a React state-driven approach to timers and data fetching.

    Can they coexist or do you need to pick one?

    • If you prefer manual DOM manipulation and directly showing countdown messages inside container elements, your checkAndSetButtonState1 works fine for that.
    • But if you want React-friendly timers linked to timed data fetching and UI updates, my React useEffect / startTimer approach is better.

    How to unify?

    1. Decide where you want timers:

      • If you want UI timers in React components (not raw DOM elements), use React state timers (startTimer + timers + useEffect).
      • If you want raw DOM timer popup messages exactly like in your code, keep your current checkAndSetButtonState1.
    2. If sticking with your manual timer code, you can still integrate the fetching after timer ends by invoking Filterrecords after your handleDuplicateRulestype call in the timer setInterval completion block.

    For example, in your timer setInterval callback’s remaining <= 0 branch, after calling handleDuplicateRulestype(...), you can fetch new data for that tab and update corresponding React state.

    1. If moving to React timers, your checkAndSetButtonState1 timers would be redundant, and you’d remove that DOM timer manipulation, replacing it with React timers + useEffect to fetch when timers hit 0.

    TL;DR

    AspectYour checkAndSetButtonState1 timerMy React Timers + useEffect suggestion
    Timer managementImperative DOM elements + setIntervalReact state + useEffect + interval
    Timer displayCreates fixed-position text div inside containersTimer values in React state, UI controlled via React
    Timer ending actionCalls handleDuplicateRulestype()Calls fetch function to update React state with new rules
    Data fetchingNot included after timer ends (only calls handler)Fetches fresh data when timer reaches zero
    Integration with ReactManual manipulation outside React's render cycleFully React lifecycle compatible

    My recommendation

    • If you want a React-friendly solution with proper state management, error handling, and side effects, use the React timers and effects approach.
    • If you want quick inline DOM timers and simple messaging with immediate handleDuplicateRulestype calls, your current checkAndSetButtonState1 approach is simpler but not following React best practices.

    If you want, I can help you:

    • Integrate your existing timer UI/messages into React controlled components combined with your React timers.
    • Or convert your manual timers fully to React timers and fetching.

    Just let me know!

  9. User

    import React, { useState, useEffect } from "react"; import AutomationTabs from "./components/AutomationTabs"; import WorkflowDashboard from './components/workflow_dashboard';

    import { getAllTicketFields, getAllContactFields, getAllCompanyFields } from "./common";

    const App = ({ client }) => { const [activeTab, setActiveTab] = useState("dashboard"); const [ticketFields, setTicketFields] = useState([]); const [contactFields, setContactFields] = useState([]); const [companyFields, setCompanyFields] = useState([]);

    useEffect(() => { getAllTicketFields(window.client, setTicketFields); getAllContactFields(window.client, setContactFields); getAllCompanyFields(window.client, setCompanyFields); }, []);

    const sidebarStyle = { width: "60px", height: "99vh", backgroundColor: "#0d3147", display: "flex", flexDirection: "column", alignItems: "center", // paddingTop: "20px", position: "fixed", boxShadow: "4px 0px 10px rgba(0, 0, 0, 0.2)" // Shadow for sidebar

    };

    const buttonStyle = { margin: "15px 0" };

    const mainContentStyle = { marginLeft: "90px", // paddingLeft: "20px", width: "100%", minHeight: "95vh", backgroundColor: "#fff" };

    const activeColor = "#ffffff"; const inactiveColor = "#d3d3d3";

    return ( <div style={{ display: "flex" }}> {/* Sidebar */} <fw-button size="icon" color="primary" style={{ color: activeTab === "dashboard" ? activeColor : inactiveColor }} onClick={() => setActiveTab("dashboard")} >

        <div style={buttonStyle}>
          <fw-button
            size="icon"
            color="primary"
            style={{ color: activeTab === "automation" ? activeColor : inactiveColor }}
            onClick={() => setActiveTab("automation")}
          >
            <fw-icon name="settings" size="20"></fw-icon>
          </fw-button>
        </div>
      </div>
    
      {/* Main Content Area */}
      <div style={mainContentStyle}>
        {activeTab === "dashboard" && <Workflow_dashboard client={client} />}
        {activeTab === "automation" && <AutomationTabs client={client} />}
      </div>
    </div>
    

    ); };

    export default App;

    is workflow_dashboard importede correctlhy?

    import React, { useState, useEffect } from "react"; import AutomationTabs from "./components/AutomationTabs"; import WorkflowDashboard from './components/workflow_dashboard';

    import { getAllTicketFields, getAllContactFields, getAllCompanyFields } from "./common";

    const App = ({ client }) => { const [activeTab, setActiveTab] = useState("dashboard"); const [ticketFields, setTicketFields] = useState([]); const [contactFields, setContactFields] = useState([]); const [companyFields, setCompanyFields] = useState([]);

    useEffect(() => { getAllTicketFields(window.client, setTicketFields); getAllContactFields(window.client, setContactFields); getAllCompanyFields(window.client, setCompanyFields); }, []);

    const sidebarStyle = { width: "60px", height: "99vh", backgroundColor: "#0d3147", display: "flex", flexDirection: "column", alignItems: "center", // paddingTop: "20px", position: "fixed", boxShadow: "4px 0px 10px rgba(0, 0, 0, 0.2)" // Shadow for sidebar

    };

    const buttonStyle = { margin: "15px 0" };

    const mainContentStyle = { marginLeft: "90px", // paddingLeft: "20px", width: "100%", minHeight: "95vh", backgroundColor: "#fff" };

    const activeColor = "#ffffff"; const inactiveColor = "#d3d3d3";

    return ( <div style={{ display: "flex" }}> {/* Sidebar */} <fw-button size="icon" color="primary" style={{ color: activeTab === "dashboard" ? activeColor : inactiveColor }} onClick={() => setActiveTab("dashboard")} >

        <div style={buttonStyle}>
          <fw-button
            size="icon"
            color="primary"
            style={{ color: activeTab === "automation" ? activeColor : inactiveColor }}
            onClick={() => setActiveTab("automation")}
          >
            <fw-icon name="settings" size="20"></fw-icon>
          </fw-button>
        </div>
      </div>
    
      {/* Main Content Area */}
      <div style={mainContentStyle}>
        {activeTab === "dashboard" && <Workflow_dashboard client={client} />}
        {activeTab === "automation" && <AutomationTabs client={client} />}
      </div>
    </div>
    

    ); };

    export default App;

  10. Assistant

    Your import and usage have a mismatch in component naming:

    You import as:

    import WorkflowDashboard from './components/workflow_dashboard';
    

    But use as:

    <Workflow_dashboard client={client} />
    

    React components should be PascalCase consistently.

    You should change your usage to:

    {activeTab === "dashboard" && <WorkflowDashboard client={client} />}
    

    Summary:

    • Keep the import as WorkflowDashboard
    • Use the component as <WorkflowDashboard /> (not <Workflow_dashboard />)

    So the fixed part in your code is:

    {/* Main Content Area */}
    <div style={mainContentStyle}>
      {activeTab === "dashboard" && <WorkflowDashboard client={client} />}
      {activeTab === "automation" && <AutomationTabs client={client} />}
    </div>
    

    This will make sure React knows which component you’re rendering and avoid any ReferenceError for undefined component.

  11. User

    import React, { useState, useEffect, useRef, useMemo } from "react"; import { FwTabs, FwTab, FwTabPanel, FwSpinner, ToastController, FwToast, FwPagination, FwModalTitle, FwModalContent, FwToggle, FwButton, FwIcon, FwListOptions, FwPopover, FwModal, } from "@freshworks/crayons/react"; import { getTicketCreationRules, getTicketUpdationRules, getHourlyRules, getAgents, pagination, } from "../common";

    const cleanText = (text) => String(text || "") .toLowerCase() .replace(/<img[^>]>/gi, "") .replace(/ /gi, " ") .replace(/<[^>]>/g, "") .replace(/[,.]/g, "") .replace(/([a-zA-Z])(\d)/g, "11 2") .replace(/(\d)([a-zA-Z])/g, "11 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 if (typeof rawConditions === "object" && rawConditions !== null) { parts = Object.values(rawConditions).flat(); } 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 = set1;

    currentSet.push(cleaned);
    

    }

    set1.sort(); set2.sort();

    return { set1, set2 }; };

    const normalizeActions = (actions) => { if (Array.isArray(actions)) { return actions .map((action) => { if (typeof action === "string") { return cleanText(action); } else if (typeof action === "object" && action !== null) { return Object.values(action) .map((v) => cleanText(v)) .join(" "); } else { return ""; } }) .sort() .join(","); } else if (typeof actions === "string") { return actions .split(",") .map((a) => cleanText(a)) .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; };

    const groupDuplicates = (rules) => { const groups = {};

    rules .filter((rule) => rule.active === true || rule.active === "true") .forEach((rule) => { const signature = getRuleSignatureNormalized(rule); if (!groups[signature]) groups[signature] = []; groups[signature].push(rule); });

    return Object.values(groups); };

    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,
      }));
    
      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);
    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); } };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
    

    }, []);

    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();
    }
    
    // console.log("Actual Text :", text);
    return text;  // do not convert to lowercase here
    

    }

    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); 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)} <div style={{ display: "flex", alignItems: "center", gap: "8px", padding: "8px 16px", flexBasis: "20%", flexShrink: 0, marginTop: "-50px", justifyContent: "flex-end", position: "relative", }} > <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", }} > <MenuList visible={menuOpen} onEdit={() => alert("Edit clicked")} onClone={() => alert("Clone clicked")} rule={rule} /> <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", }} > Last Modified: {calculateLastModified(updated_at)} | By: {renderAgentName()} | Impacted tickets (Last 7 days): {affected_tickets_count}

      <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>
    </>
    

    ); };

    const AutomationTabs = ({ client }) => { const [isRulesDBReady, setIsRulesDBReady] = useState(false); const [loadingBannerVisible, setLoadingBannerVisible] = useState(true); const intervalIdRef = useRef(null); const [showSearchHint, setShowSearchHint] = useState(false);

    const [searchTerm, setSearchTerm] = useState(""); const [searchQuery, setSearchQuery] = useState(""); const [searchTriggered, setSearchTriggered] = useState(false);

    const [errorMessage, setErrorMessage] = useState(null);

    const [activeTab, setActiveTab] = useState("ticketcreate"); const [inputState, setInputState] = useState("normal"); 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 rulesPerPage = 30;

    const [currentPage, setCurrentPage] = useState({ ticketcreate: 1, ticketupdate: 1, hourly: 1, });

    const [recentDataCache, setRecentDataCache] = useState({ ticketcreate: null, ticketupdate: null, hourly: null, });

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

    const newRulePloadDB5 = useRef(null); const warningTimerRef = useRef(null);

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

    const [fetchFromApi, setFetchFromApi] = useState(false);

    const [showPagination, setShowPagination] = useState(false);

    const [ticketCreationRuleGroups, setTicketCreationRuleGroups] = useState([]); const [ticketUpdateRuleGroups, setTicketUpdateRuleGroups] = useState([]); const [hourlyRuleGroups, setHourlyRuleGroups] = useState([]);

    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]);

    const paginateDuplicateGroups = (groups, rulesPerPage, searchQuery) => { const filteredGroups = groups .map((group) => group.filter( (rule) => !searchQuery.trim() || rule.name?.toLowerCase().includes(searchQuery.toLowerCase()) || rule.description?.toLowerCase().includes(searchQuery.toLowerCase()) ) ) .filter((group) => group.length > 0);

    const paginatedGroups = [];
    let currentChunk = [];
    let currentCount = 0;
    
    for (const group of filteredGroups) {
      const groupSize = group.length;
    
      if (groupSize > rulesPerPage) {
        if (currentCount > 0) {
          paginatedGroups.push(currentChunk);
          currentChunk = [];
          currentCount = 0;
        }
        paginatedGroups.push([group]);
      } else {
        if (currentCount + groupSize <= rulesPerPage) {
          currentChunk.push(group);
          currentCount += groupSize;
        } else {
          if (currentCount > 0) {
            paginatedGroups.push(currentChunk);
          }
          currentChunk = [group];
          currentCount = groupSize;
        }
      }
    }
    if (currentCount > 0) {
      paginatedGroups.push(currentChunk);
    }
    
    return paginatedGroups;
    

    };

    useEffect(() => { const initializeDatabase = async () => { const entity = await client.db.entity({ version: "v1" }); newRulePloadDB5.current = entity.get("newRulePloadDB5");

      const agentdaa = await getAgents(client);
      setAgent(agentdaa);
    
      try {
        const tabData = await client.db.get("TabDB");
        if (!tabData || !tabData.LastVisitedTab) {
          await client.db.set("TabDB", { LastVisitedTab: "ticketcreate" });
          setActiveTab("ticketcreate");
        } else {
          setActiveTab(tabData.LastVisitedTab);
        }
      } catch (error) {
        await client.db.set("TabDB", { LastVisitedTab: "ticketcreate" });
        setActiveTab("ticketcreate");
      } finally {
        setTabsInitialized(true);
      }
    };
    
    initializeDatabase();
    

    }, [client]);

    useEffect(() => { setCurrentPage((prev) => ({ ...prev, [activeTab]: 1, })); setRuleViewFilter(ruleViewOptions[0]); }, [activeTab, fetchFromApi]);

    useEffect(() => { const fetchOnTabOrModeChange = async () => { setLoading(true); setErrorMessage(null);

      try {
        let error = null;
    
        if (fetchFromApi) {
          if (recentDataCache.agent) {
            setAgent(recentDataCache.agent);
          } else {
            await getAgents(client, (data) => {
              setAgent(data);
              setRecentDataCache((prev) => ({ ...prev, agent: data }));
            });
          }
    
          if (recentDataCache[activeTab]) {
            if (activeTab === "ticketcreate") {
              setTicketCreationRules(recentDataCache.ticketcreate);
            } else if (activeTab === "ticketupdate") {
              setTicketUpdateRules(recentDataCache.ticketupdate);
            } else if (activeTab === "hourly") {
              setHourlyTriggerRules(recentDataCache.hourly);
            }
          } else {
            if (activeTab === "ticketcreate") {
              error = await getTicketCreationRules(client, (data) => {
                setTicketCreationRules(data);
                setRecentDataCache((prev) => ({ ...prev, ticketcreate: data }));
              });
            } else if (activeTab === "ticketupdate") {
              error = await getTicketUpdationRules(client, (data) => {
                setTicketUpdateRules(data);
                setRecentDataCache((prev) => ({ ...prev, ticketupdate: data }));
              });
            } else if (activeTab === "hourly") {
              error = await getHourlyRules(client, (data) => {
                setHourlyTriggerRules(data);
                setRecentDataCache((prev) => ({ ...prev, hourly: data }));
              });
            }
          }
        } else {
          if (!newRulePloadDB5.current) {
            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);
          }
    
          setRecentDataCache({
            ticketcreate: null,
            ticketupdate: null,
            hourly: null,
            agent: null,
          });
    
          setAgent(null);
        }
    
        if (error) {
          setErrorMessage(error);
        }
      } catch (err) {
        setErrorMessage("An unexpected error occurred while fetching data.");
      }
    
      setLoading(false);
    };
    
    if (tabsInitialized && isRulesDBReady) {
      fetchOnTabOrModeChange();
    }
    

    }, [activeTab, fetchFromApi, client, tabsInitialized, isRulesDBReady]);

    const duplicateGroupsMap = useMemo(() => { // groups: array of arrays of duplicate rules with length > 1 let allRules = []; if (activeTab === "ticketcreate") allRules = ticketCreationRules; else if (activeTab === "ticketupdate") allRules = ticketUpdateRules; else if (activeTab === "hourly") allRules = hourlyTriggerRules;

    // group duplicates, filtered active only
    const groups = groupDuplicates(allRules).filter((g) => g.length > 1);
    
    // Map rule_id -> isFirstInGroup flag (true only for first rule of each duplicate group)
    const firstRuleIds = new Set();
    groups.forEach((group) => {
      if (group.length > 0) {
        firstRuleIds.add(group[0].id);
      }
    });
    
    // Return structure for lookup: firstRuleIds set + flattened set of all duplicate IDs
    const duplicateRuleIds = new Set(groups.flat().map((r) => r.id));
    
    return { firstRuleIds, duplicateRuleIds };
    

    }, [activeTab, ticketCreationRules, ticketUpdateRules, hourlyTriggerRules]);

    const highlightDuplicates = ruleViewFilter.value === "all_rules" && (!searchQuery || searchQuery.trim() === "");

    const getFilteredRules = (rules) => { if (!searchQuery.trim()) return rules;

    return rules.filter(
      (rule) =>
        rule.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        rule.description?.toLowerCase().includes(searchQuery.toLowerCase())
    );
    

    };

    const flattenGroups = (groups) => groups.flat();

    // const getCurrentPageItemCount = () => { // if (ruleViewFilter.value !== "duplicate_rules") { // return rulesPerPage; // }

    // let groups = []; // if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups; // else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups; // else if (activeTab === "hourly") groups = hourlyRuleGroups;

    // const paginatedGroups = paginateDuplicateGroups(groups, rulesPerPage, searchQuery); // const pageIndex = currentPage[activeTab] - 1; // const groupsToShow = paginatedGroups[pageIndex] || []; // const count = flattenGroups(groupsToShow).length || rulesPerPage;

    // console.log([Pagination] Duplicate mode per-page on tab '${activeTab}' page ${pageIndex + 1}: ${count});

    // return count; // };

    const getCurrentPageItemCount = () => {

    if (ruleViewFilter.value !== "duplicate_rules") {
      return rulesPerPage;
    }
    
    let groups = [];
    
    if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups;
    else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups;
    else if (activeTab === "hourly") groups = hourlyRuleGroups;
    
    const paginatedGroups = paginateDuplicateGroups(groups, rulesPerPage, searchQuery);
    const pageIndex = currentPage[activeTab] - 1;
    const groupsToShow = paginatedGroups[pageIndex];
    
    if (!groupsToShow || groupsToShow.length === 0) {
      return 0;
    }
    
    // exact count of items on current page
    const count = flattenGroups(groupsToShow).length;  
    console.log(`[Pagination] Duplicate mode per-page on tab '${activeTab}' page ${pageIndex + 1}: ${count}`);   
    
    return count;
    

    };

    const getPaginationTotalCount = () => {

    if (ruleViewFilter.value === "duplicate_rules") {
      let groups = [];
      if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups;
      else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups;
      else if (activeTab === "hourly") groups = hourlyRuleGroups;
    
      const filteredGroups = groups
        .map((group) =>
          group.filter(
            (rule) =>
              !searchQuery.trim() ||
              rule.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
              rule.description?.toLowerCase().includes(searchQuery.toLowerCase())
          )
        )
        .filter((group) => group.length > 0);
    
      return filteredGroups.reduce((acc, g) => acc + g.length, 0);
    
    
    } else {
      return getCurrentTotalCount();
    }
    

    };

    // 4.41pm 16th may 2025 useEffect(() => { if (ruleViewFilter.value === "duplicate_rules") { // Recalculate duplicate groups for the active tab automatically if (activeTab === "ticketcreate") { const grouped = groupDuplicates(ticketCreationRules); const duplicateGroups = grouped .filter((group) => group.length > 1) .sort((a, b) => b.length - a.length); 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); 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); setHourlyRuleGroups(duplicateGroups); setCurrentPage((prev) => ({ ...prev, hourly: 1 })); } } else { // Clear duplicate groups when switching away from duplicate_rules view setTicketCreationRuleGroups([]); setTicketUpdateRuleGroups([]); setHourlyRuleGroups([]); } }, [ruleViewFilter, activeTab, ticketCreationRules, ticketUpdateRules, hourlyTriggerRules]);

    const getCurrentTotalCount = () => { 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; };

    const renderRulesOrGroups = () => { let groups = []; let flatRules = [];

    if (activeTab === "ticketcreate") {
      groups = ticketCreationRuleGroups;
      flatRules = ticketCreationRules;
    } else if (activeTab === "ticketupdate") {
      groups = ticketUpdateRuleGroups;
      flatRules = ticketUpdateRules;
    } else if (activeTab === "hourly") {
      groups = hourlyRuleGroups;
      flatRules = hourlyTriggerRules;
    }
    
    if (loading) {
      return (
        <div
          style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "200px" }}
        >
          <FwSpinner size="medium" color="green" />
        </div>
      );
    }
    
    if (ruleViewFilter.value === "duplicate_rules") {
      if (groups.length === 0) {
        return <p style={{ textAlign: "center", marginTop: "20px" }}>No Rules Found.</p>;
      }
    
      const paginatedGroups = paginateDuplicateGroups(groups, rulesPerPage, searchQuery);
      const pageIndex = currentPage[activeTab] - 1;
      const groupsToShow = paginatedGroups[pageIndex] || [];
    
      const flattenedRulesOnPage = flattenGroups(groupsToShow);
      const filteredRulesOnPage = getFilteredRules(flattenedRulesOnPage);
    
      const filteredGroupsToShow = groupsToShow
        .map((group) =>
          group.filter((rule) =>
            filteredRulesOnPage.some((filteredRule) => filteredRule.id === rule.id)
          )
        )
        .filter((group) => group.length > 0);
    
      if (filteredGroupsToShow.length === 0) {
        return <p style={{ textAlign: "center", marginTop: "20px" }}>No Rules Found.</p>;
      }
    
      return (
        <div style={{ marginLeft: 10, marginRight: "auto" }}>
          {filteredGroupsToShow.map((group, idx) => (
            <div
              key={`group-${pageIndex}-${idx}`}
              style={{ marginBottom: "12px", boxShadow: "0 4px 8px rgba(0, 0, 0, 0.2)" }}
            >
              {group.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) => {
        // If duplicates coloring enabled and this rule is a duplicate
        if (highlightDuplicates && duplicateGroupsMap.duplicateRuleIds.has(rule.id)) {
          const isFirstInGroup = duplicateGroupsMap.firstRuleIds.has(rule.id);
          return (
            <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={isFirstInGroup} // first in duplicates = true, no color; others = false, colored
                onDelete={() => deleteRule(rule, filteredFlatRules)}
                activeTab={activeTab}
                onSelect={openRuleDetails}
                agent={agent}
              />
            </div>
          );
        } else {
          // Not duplicate or highlight not enabled: normal card
          return (
            <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>
          );
        }
      });
    
    
    }
    

    };

    // Fetch storedvalue1 and update processingStatus when it changes useEffect(() => { async function fetchStoredValue() { try { const val = await client.db.get("RulesDB"); setStoredValue1(val);

      // Update the processing flag states
      setProcessingStatus({
        Ticketcreation: val?.creationTotal > 0,
        HourlyTriggers: val?.hourlyTotal > 0,
        TicketUpdates: val?.updateTotal > 0,
      });
    } catch (error) {
      setStoredValue1(null);
      setProcessingStatus({
        Ticketcreation: false,
        HourlyTriggers: false,
        TicketUpdates: false,
      });
      console.error("Error fetching RulesDB", error);
    }
    

    } fetchStoredValue(); }, [client]);

    /* Timer state for each tab */ const [timers, setTimers] = useState({ ticketcreate: null, ticketupdate: null, hourly: null, }); const timerIntervals = useRef({ ticketcreate: null, ticketupdate: null, hourly: null, });

    /* Stored RulesDB data */ const [storedvalue1, setStoredValue1] = useState(null); const [processingStatus, setProcessingStatus] = useState({ Ticketcreation: false, HourlyTriggers: false, TicketUpdates: false, });

    // Fetch storedvalue1 and update processingStatus when it changes useEffect(() => { async function fetchStoredValue() { try { const val = await client.db.get("RulesDB"); setStoredValue1(val);

      setProcessingStatus({
        Ticketcreation: val?.creationTotal > 0,
        HourlyTriggers: val?.hourlyTotal > 0,
        TicketUpdates: val?.updateTotal > 0,
      });
    } catch (error) {
      setStoredValue1(null);
      setProcessingStatus({
        Ticketcreation: false,
        HourlyTriggers: false,
        TicketUpdates: false,
      });
      console.error("Error fetching RulesDB", error);
    }
    

    } fetchStoredValue(); }, [client]);

    const fetchedAfterTimerEnd = useRef({ ticketcreate: false, ticketupdate: false, hourly: false, });

    /* Timer start function */ const startTimer = (tabKey, duration) => { if (timerIntervals.current[tabKey]) { clearInterval(timerIntervals.current[tabKey]); }

    setTimers((prev) => ({ ...prev, [tabKey]: duration, }));

    timerIntervals.current[tabKey] = setInterval(() => { setTimers((prev) => { if (!prev[tabKey]) return prev; const newTime = prev[tabKey] - 1; if (newTime <= 0) { clearInterval(timerIntervals.current[tabKey]); timerIntervals.current[tabKey] = null; return { ...prev, [tabKey]: null }; } return { ...prev, [tabKey]: newTime }; }); }, 1000); };

    useEffect(() => { const fetchDataForTab = async (tabKey) => { if (tabKey === "ticketcreate") { const data = await Filterrecords(ticketCreate, newRulePloadDB5.current); setTicketCreationRules(data); } else if (tabKey === "ticketupdate") { const data = await Filterrecords(ticketUpdate, newRulePloadDB5.current); setTicketUpdateRules(data); } else if (tabKey === "hourly") { const data = await Filterrecords(hourlyTriggers, newRulePloadDB5.current); setHourlyTriggerRules(data); } };

    Object.entries(timers).forEach(([tabKey, time]) => { // If timer reached zero (null) and we haven't fetched yet if (time === null && !fetchedAfterTimerEnd.current[tabKey]) { fetchedAfterTimerEnd.current[tabKey] = true; fetchDataForTab(tabKey); }

    // Reset flag if timer restarts (> 0)
    if (time !== null && fetchedAfterTimerEnd.current[tabKey]) {
      fetchedAfterTimerEnd.current[tabKey] = false;
    }
    

    }); }, [timers]);

    /* Start timers when storedvalue1 (RulesDB data) changes */ useEffect(() => {

    if (!storedvalue1) return;

    // Ticket Creation if (storedvalue1.creationTotal > 0) { const duration = getDurationForTotal(storedvalue1.creationTotal); startTimer("ticketcreate", duration); } else { setTimers((prev) => ({ ...prev, ticketcreate: null })); }

    // Ticket Updates if (storedvalue1.updateTotal > 0) { const duration = getDurationForTotal(storedvalue1.creationTotal) + getDurationForTotal(storedvalue1.hourlyTotal) + getDurationForTotal(storedvalue1.updateTotal); startTimer("ticketupdate", duration); } else { setTimers((prev) => ({ ...prev, ticketupdate: null })); }

    // Hourly Triggers if (storedvalue1.hourlyTotal > 0) { const duration = getDurationForTotal(storedvalue1.creationTotal) + getDurationForTotal(storedvalue1.hourlyTotal); startTimer("hourly", duration); } else { setTimers((prev) => ({ ...prev, hourly: null })); }

    return () => { Object.values(timerIntervals.current).forEach((t) => clearInterval(t)); }; }, [storedvalue1]);

    /* Render timer message overlay */ const renderTimerMessage = (tabKey) => { if (!timers[tabKey]) return null;

    return ( <div style={{ position: "fixed", top: "63%", left: "50%", transform: "translateX(-50%)", backgroundColor: "white", padding: "10px 20px", borderRadius: 5, fontFamily: "sans-serif", fontSize: 16, color: "black", zIndex: 9999, boxShadow: "0 0 5px rgba(0,0,0,0.15)", maxWidth: 350, textAlign: "center", userSelect: "none", }} > The app is currently processing the data. Please refresh the page or revisit the app after {timers[tabKey]} sec... ); };

    const getDurationForTotal = (total) => { if (total <= 0) return 60; // Default 60 seconds if no data

    const baseDuration = 120; // Minimum 2 minutes const itemsPerStep = 100; const secondsPerStep = 60;

    const steps = Math.ceil(total / itemsPerStep); return baseDuration + (steps - 1) * secondsPerStep; };

    // const deleteRule = async (rule, allRulesList) => { // 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: // return; // }

    // const targetDisplayId = matchedRecord ? matchedRecord.display_id : undefined;

    // if (targetDisplayId && newRulePloadDB5.current) { // try { // await newRulePloadDB5.current.delete(targetDisplayId); // } catch (err) {} // }

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

    // if (response.status === 204) { // const updatedRules = currentRules.filter((r) => r.id !== id); // setRulesFunc(updatedRules);

    // groupSetterFunc([]);

    // let filteredRules = getFilteredRules(updatedRules);

    // const paginatedItems = pagination(filteredRules, currentTabPage);

    // 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) { // toast.current.trigger({ type: "error", content: "Error deleting rule." }); // } // };

    const deleteRule = async (rule, allRulesList) => { 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:
        return;
    }
    
    const targetDisplayId = matchedRecord ? matchedRecord.display_id : undefined;
    
    if (targetDisplayId && newRulePloadDB5.current) {
      try {
        await newRulePloadDB5.current.delete(targetDisplayId);
      } catch (err) {}
    }
    
    try {
      const response = await client.request.invokeTemplate("deleterule", {
        context: {
          automationid: automationTypeId,
          ruleid: id,
        },
      });
    
      if (response.status === 204) {
        // Remove deleted rule from the current flat rules list
        const updatedRules = currentRules.filter((r) => r.id !== id);
        setRulesFunc(updatedRules);
    
        if (ruleViewFilter.value === "duplicate_rules") {
          // Recalculate duplicate groups with updated rules after deletion
          const updatedGroups = groupDuplicates(updatedRules)
            .filter((g) => g.length > 1)
            // Optional: sort largest groups first or as you prefer
            .sort((a, b) => b.length - a.length);
    
          groupSetterFunc(updatedGroups);
    
          // Flatten the updated groups to find rules on current page
          const flattenUpdatedGroups = flattenGroups(updatedGroups);
          const filteredRules = getFilteredRules(flattenUpdatedGroups);
          const paginated = pagination(filteredRules, currentTabPage);
    
          // If current page empty and not first page, shift current page back
          if (paginated.length === 0 && currentTabPage > 1) {
            setCurrentPage((prev) => ({ ...prev, [tabKey]: prev[tabKey] - 1 }));
          }
        } else {
          // In "all_rules" mode or others, just clear groups cache (optional)
          groupSetterFunc([]);
        }
    
        toast.current.trigger({ type: "success", content: "Rule deleted successfully!" });
      } else {
        toast.current.trigger({ type: "error", content: "Failed to delete rule." });
      }
    } catch (error) {
      console.log(error);
      toast.current.trigger({ type: "error", content: "Error deleting rule." });
    }
    

    };

    const openRuleDetails = (rule) => {};

    const closeRuleDetails = () => {};

    const handleFilterApiClick = () => { if (activeTab === "ticketcreate") { const grouped = groupDuplicates(ticketCreationRules); const duplicateGroups = grouped .filter((group) => group.length > 1) .sort((a, b) => b.length - a.length); 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); 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); 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;

    let groups = [];
    if (activeTab === "ticketcreate") groups = ticketCreationRuleGroups;
    else if (activeTab === "ticketupdate") groups = ticketUpdateRuleGroups;
    else if (activeTab === "hourly") groups = hourlyRuleGroups;
    
    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 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");

    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) {}
    };
    
    if (fwTabs) {
      fwTabs.addEventListener("fwChange", saveActiveTab);
    }
    
    return () => {
      if (fwTabs) {
        fwTabs.removeEventListener("fwChange", saveActiveTab);
      }
    };
    

    }, [client]);

    const fetchData = async () => { 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);

        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(faise);
        setLoadingBannerVisible(true);
        if (intervalIdRef.current) {
          clearInterval(intervalIdRef.current);
          intervalIdRef.current = null;
        }
      }
    }
    

    };

    useEffect(() => { checkAndSetButtonState(); return () => { if (intervalIdRef.current) clearInterval(intervalIdRef.current); }; }, []);

    // const ruleViewPopoverRef = useRef(null);

    const ruleViewPopoverRef = useRef(null);

    const searchInputs = ( <div style={{ display: "flex", alignItems: "center", marginBottom: 10, marginLeft: 20, marginTop: 15, maxWidth: "100%", gap: "20px", }} >

            if (selected.value === "all_rules") {
              setTicketCreationRuleGroups([]);
              setTicketUpdateRuleGroups([]);
              setHourlyRuleGroups([]);
            } else if (selected.value === "duplicate_rules") {
              handleFilterApiClick();
            }
    
            // Close popover programmatically
            if (ruleViewPopoverRef.current) {
              ruleViewPopoverRef.current.close();
            }
          }
        }}
        selectedOptions={[ruleViewFilter]}
        options={ruleViewOptions}
        variant="icon"
      />
    </div>
    
      <div style={{ flex: 1, display: "flex", justifyContent: "center", marginTop: 20 }}>
        <fw-input
          clear-input
          ref={useRef(null)}
          icon-left="search"
          hint-text="Type Keyword to Search"
          placeholder="Enter a Keyword to Search..."
          warning-text="Please Enter a Keyword to Search..."
          state={inputState}
          style={{
            width: "400px",
            height: "60px",
            fontSize: "18px",
          }}
          value={searchTerm}
          onInput={(e) => {
            const val = e.target.value;
            if (val.length < searchTerm.length) {
              setSearchQuery("");
            }
            setSearchTerm(val);
            if (showSearchHint) setShowSearchHint(false);
            if (inputState !== "normal") setInputState("normal");
            if (warningTimerRef.current) {
              clearTimeout(warningTimerRef.current);
              warningTimerRef.current = null;
            }
          }}
          onKeyDown={(e) => {
            if (e.key === "Enter") {
              const trimmed = e.target.value.trim();
              if (!trimmed) {
                setSearchQuery("");
                setShowSearchHint(false);
                setInputState("warning");
    
                warningTimerRef.current = setTimeout(() => {
                  setInputState("normal");
                  warningTimerRef.current = null;
                }, 3000);
              } else {
                setSearchQuery(trimmed);
                setShowSearchHint(false);
                setInputState("normal");
              }
              setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
            }
          }}
          fwInputClear={() => {
            setSearchTerm("");
            setSearchQuery("");
            setCurrentPage((prev) => ({ ...prev, [activeTab]: 1 }));
            setInputState("normal");
    
            if (warningTimerRef.current) {
              clearTimeout(warningTimerRef.current);
              warningTimerRef.current = null;
            }
          }}
        />
      </div>
    
      <div style={{ flexShrink: 0 }}>
        <FwButton color="primary" onFwClick={() => {}}>
          <fw-icon name="plus" size="16" style={{ marginRight: "8px" }}></fw-icon>
          Add New Rule
        </FwButton>
      </div>
    </div>
    

    );

    // return ( // <> // {errorMessage ? ( // <div // style={{ // position: "fixed", // top: 0, // left: 0, // width: "100vw", // height: "100vh", // display: "flex", // justifyContent: "center", // alignItems: "center", // backgroundColor: "rgba(255, 255, 255, 0.8)", // zIndex: 9999, // }} // > // <div // style={{ // color: "red", // fontSize: "2rem", // fontWeight: "bold", // textAlign: "center", // padding: "20px", // backgroundColor: "white", // }} // > // {errorMessage} // // // ) : ( // <> // Automations - Rules

    // {showSearchHint && ( // <p style={{ color: "red", marginTop: "4px", fontSize: "0.9em" }}> // Please enter a search term before searching. // // )}

    // {loadingBannerVisible && !isRulesDBReady && ( // <div // style={{ // justifyContent: "center", // alignItems: "center", // height: "40px", // width: "50%", // margin: "0 auto", // }} // > // // <span style={{ marginLeft: "8px" }}>Waiting for rules to be ready... // // )}

    // {tabsInitialized && ( // <div style={{ width: "60%", marginRight: "auto" }}> // <div // style={{ // display: "flex", // justifyContent: fetchFromApi ? "flex-start" : "flex-end", // marginBottom: 15, // }} // > // // {fetchFromApi ? ( // <> // <FwIcon // slot="before-label" // name="arrow-left" // size={16} // style={{ marginRight: "8px" }} // /> // Back // </> // ) : ( // <> // Get Recent Data // <FwIcon // slot="after-label" // name="refresh" // size={16} // style={{ marginLeft: "8px" }} // /> // </> // )} // //

    // // <FwTab slot="tab" panel="ticketcreate" onClick={() => setActiveTab("ticketcreate")}> // Ticket Creation // // <FwTab slot="tab" panel="ticketupdate" onClick={() => setActiveTab("ticketupdate")}> // Ticket Updates // // <FwTab slot="tab" panel="hourly" onClick={() => setActiveTab("hourly")}> // Hourly Triggers //

    // // {searchInputs} // {renderRulesOrGroups()} // {showPagination && getPaginatedItemCount() > 0 && ( // <div style={{ marginTop: 10 }}> // <div style={{ display: "flex", justifyContent: "center" }}> // <FwPagination // per-page={getCurrentPageItemCount()} // total={getPaginationTotalCount()} // page={currentPage.ticketcreate} // onFwChange={handlePageChange("ticketcreate")} // /> // // // )} //

    // // {searchInputs} // {renderRulesOrGroups()} // {showPagination && getPaginatedItemCount() > 0 && ( // <div style={{ marginTop: 10 }}> // <div style={{ display: "flex", justifyContent: "center" }}> // <FwPagination // per-page={getCurrentPageItemCount()} // total={getPaginationTotalCount()} // page={currentPage.ticketupdate} // onFwChange={handlePageChange("ticketupdate")} // /> // // // )} //

    // // {searchInputs} // {renderRulesOrGroups()} // {showPagination && getPaginatedItemCount() > 0 && ( // <div style={{ marginTop: 10 }}> // <div style={{ display: "flex", justifyContent: "center" }}> // <FwPagination // per-page={getCurrentPageItemCount()} // total={getPaginationTotalCount()} // page={currentPage.hourly} // onFwChange={handlePageChange("hourly")} // /> // // // )} // // // // )} // </> // )}

    // // </> // );

    return ( <> {errorMessage ? ( <div style={{ position: "fixed", top: 0, left: 0, width: "100vw", height: "100vh", display: "flex", justifyContent: "center", alignItems: "center", backgroundColor: "rgba(255, 255, 255, 0.8)", zIndex: 9999, }} > <div style={{ color: "red", fontSize: "2rem", fontWeight: "bold", textAlign: "center", padding: "20px", backgroundColor: "white", }} > {errorMessage} ) : ( <> Automations - Rules

          {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={getCurrentPageItemCount()}
                          total={getPaginationTotalCount()}
                          page={currentPage.ticketcreate}
                          onFwChange={handlePageChange("ticketcreate")}
                        />
                      </div>
                    </div>
                  )}
                  {renderTimerMessage("ticketcreate")}
                </FwTabPanel>
    
                <FwTabPanel name="ticketupdate">
                  {searchInputs}
                  {renderRulesOrGroups()}
                  {showPagination && getPaginatedItemCount() > 0 && (
                    <div style={{ marginTop: 10 }}>
                      <div style={{ display: "flex", justifyContent: "center" }}>
                        <FwPagination
                          per-page={getCurrentPageItemCount()}
                          total={getPaginationTotalCount()}
                          page={currentPage.ticketupdate}
                          onFwChange={handlePageChange("ticketupdate")}
                        />
                      </div>
                    </div>
                  )}
                  {renderTimerMessage("ticketupdate")}
                </FwTabPanel>
    
                <FwTabPanel name="hourly">
                  {searchInputs}
                  {renderRulesOrGroups()}
                  {showPagination && getPaginatedItemCount() > 0 && (
                    <div style={{ marginTop: 10 }}>
                      <div style={{ display: "flex", justifyContent: "center" }}>
                        <FwPagination
                          per-page={getCurrentPageItemCount()}
                          total={getPaginationTotalCount()}
                          page={currentPage.hourly}
                          onFwChange={handlePageChange("hourly")}
                        />
                      </div>
                    </div>
                  )}
                  {renderTimerMessage("hourly")}
                </FwTabPanel>
              </FwTabs>
            </div>
          )}
        </>
      )}
    
      <FwToast />
    </>
    

    );

    };

    export default AutomationTabs;

    in this code in return how client is passed

  12. Assistant

    In your AutomationTabs component, the client is received as a prop:

    const AutomationTabs = ({ client }) => {
      // component code
    };
    

    That means the client value is passed from the parent component that renders <AutomationTabs />.


    In your App component, you have:

    <AutomationTabs client={client} />
    

    This means:

    • The client received by App is passed down to AutomationTabs via the client prop.
    • Inside AutomationTabs, you access it via destructuring: ({ client }).

    Summary

    • The client is passed to AutomationTabs via props.
    • Somewhere higher up in your component tree (e.g., App component), you have something like this:
    <AutomationTabs client={someClientObject} />
    
    • Then inside AutomationTabs, you use client (as you do) to fetch data, interact with DB, etc.

    So in your return statement, you don’t explicitly pass client — it’s already available inside your function as a prop.

    For example:

    // Usage inside the component
    useEffect(() => {
      getAllTicketFields(client, setTicketFields);
    }, [client]);
    
    // or in your fetch calls:
    const data = await Filterrecords(ticketCreate, newRulePloadDB5.current); 
    // and you also have client available for other calls
    

    If you want a quick check:

    1. Wherever you render <AutomationTabs />, are you passing client as a prop?

    2. Inside AutomationTabs, you receive it with: ({ client })

    3. You just use it directly; no need to do anything special in the JSX return unless passing it further down.


    Let me know if you want me to check your App component or where you render AutomationTabs!

  13. User

    import React, { useState, useEffect } from "react";

    const Workflow_dashboard = ({ client }) => { return ( <> <div style={{ backgroundColor: '#f0f0f0', height: '100vh', padding: '20px' }}> Dashboard Tab </> ); }

    export default Workflow_dashboard;

    same way pass in this

  14. Assistant

    Yes! To pass client to your Workflow_dashboard component in the same way:

    1. Make sure your component accepts client as a prop:
    const Workflow_dashboard = ({ client }) => {
      // You can now use client here
      return (
        <div style={{ backgroundColor: '#f0f0f0', height: '100vh', padding: '20px' }}>
          <h1>Dashboard Tab</h1>
        </div>
      );
    };
    export default Workflow_dashboard;
    
    1. When rendering Workflow_dashboard in your parent component (e.g. App), pass client as a prop:
    <Workflow_dashboard client={client} />
    

    Just like your AutomationTabs usage, you:

    • Pass the prop (client={client}) from parent
    • Accept it in the child component via destructuring ({ client })

    So from your earlier App component (snippet):

    <div style={mainContentStyle}>
      {activeTab === "dashboard" && <Workflow_dashboard client={client} />}
      {activeTab === "automation" && <AutomationTabs client={client} />}
    </div>
    

    This is the correct way to pass the client prop to Workflow_dashboard, consistent with how you handle AutomationTabs. Your Workflow_dashboard can now use client internally.


    In short: your Workflow_dashboard component is correct for receiving client prop. Just make sure you pass it as shown above when rendering.

  15. User

    log the client

  16. Assistant

    To log the client inside your Workflow_dashboard component, you can use a useEffect that runs once when the component mounts (or whenever client changes):

    import React, { useEffect } from "react";
    
    const Workflow_dashboard = ({ client }) => {
      useEffect(() => {
        console.log("client inside Workflow_dashboard:", client);
      }, [client]); // run whenever client changes
    
      return (
        <div style={{ backgroundColor: '#f0f0f0', height: '100vh', padding: '20px' }}>
          <h1>Dashboard Tab</h1>
        </div>
      );
    }
    
    export default Workflow_dashboard;
    

    This will print the client value to the console whenever the component mounts or whenever client prop changes.

  17. User

    import React, { useEffect } from "react";

    const Workflow_dashboard = ({ client }) => { useEffect(() => { console.log("client inside Workflow_dashboard:", client); }, [client]);

    return ( <div style={{ backgroundColor: '#f0f0f0', height: '100vh', padding: '20px' }}> Dashboard Tab ); }

    export default Workflow_dashboard;

    int his code add this functinality

    vasync function checkAndSetButtonState1(data, containerid) { try {

    localStorage.setItem("checkState_data", JSON.stringify(data));
    localStorage.setItem("checkState_containerid", containerid);
    
    console.log("automationtypeid inside checkAndSetButtonState",data);
    
    console.log("Initially stored all value from RulesDB:", storedvalue1);
    console.log("creationtotal",storedvalue1.creationTotal);
    console.log("hourlyTotal",storedvalue1.hourlyTotal);
    console.log("updateTotal",storedvalue1.updateTotal);
    console.log("Initial stored true/false value from RulesDB:", storedvalue1.stored);
    
    
    
    if (containerid === "Ticketcreation" && storedvalue1.creationTotal > 0) {
      showLoader("Ticketcreation");
      const duration = getDurationForTotal(storedvalue1.creationTotal);
    
      if (typeof duration !== "number" || isNaN(duration)) {
        console.error("❌ Invalid duration calculated. Skipping timer setup.");
        return;
      }
    
      console.log(`✅ Timer condition met. Setting timer for ${duration} seconds.`);
    
      const container = document.getElementById("Ticketcreation");
      if (!container) {
        console.error("❌ Ticketcreation container not found.");
        return;
      }
    
      const timerId = "simple-timer-Ticketcreation";
      if (document.getElementById(timerId)) {
        console.log("⚠️ Timer already running for Ticketcreation. Skipping new timer setup.");
        return;
      }
    
      // Create timer
      const timerDiv = document.createElement("div");
      timerDiv.id = timerId;
      timerDiv.style.cssText = `
      position: fixed;
      top: 63%;
      left: 50%;
      transform: translateX(-50%);
     
      color: black;
      padding: 10px 20px;
      border-radius: 5px;
      font-family: sans-serif;
      font-size: 16px;
      z-index: 9999;
    `;
      timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${duration} sec...`;
      container.appendChild(timerDiv);
    
      let remaining = duration;
      const interval = setInterval(() => {
        remaining--;
        timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${remaining} sec...`;
    
        if (remaining <= 0) {
          clearInterval(interval);
          timerDiv.remove();
          console.log("Ticketcreation timer ended. Calling handleDuplicateRulestype(1).");
          handleDuplicateRulestype(1);
        }
      }, 1000);
    }
    else if (containerid === "HourlyTriggers" && storedvalue1.hourlyTotal > 0) {
      showLoader("HourlyTriggers");
    
      const creationDuration = getDurationForTotal(storedvalue1.creationTotal);
      const hourlyDuration = getDurationForTotal(storedvalue1.hourlyTotal);
      const totalDuration = creationDuration + hourlyDuration;
    
      if (typeof totalDuration !== "number" || isNaN(totalDuration)) {
        console.error("❌ Invalid duration calculated. Skipping timer setup.");
        return;
      }
    
      console.log(`✅ Timer condition met. Setting timer for ${totalDuration} seconds.`);
    
      const container = document.getElementById("HourlyTriggers");
      if (!container) {
        console.error("❌ HourlyTriggers container not found.");
        return;
      }
    
      const timerId = "simple-timer-HourlyTriggers";
      if (document.getElementById(timerId)) {
        console.log("⚠️ Timer already running for HourlyTriggers. Skipping new timer setup.");
        return;
      }
    
      // Create timer
      const timerDiv = document.createElement("div");
      timerDiv.id = timerId;
      timerDiv.style.cssText = `
     position: fixed;
      top: 63%;
      left: 50%;
      transform: translateX(-50%);
     
      color: black;
      padding: 10px 20px;
      border-radius: 5px;
      font-family: sans-serif;
      font-size: 16px;
      z-index: 9999;
    `;
      timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${totalDuration} sec...`;
      container.appendChild(timerDiv);
    
      let remaining = totalDuration;
      const interval = setInterval(() => {
        remaining--;
        timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${remaining} sec...`;
    
        if (remaining <= 0) {
          clearInterval(interval);
          timerDiv.remove();
          console.log("✅ HourlyTriggers timer ended. Calling handleDuplicateRulestype(3).");
          handleDuplicateRulestype(3);
        }
      }, 1000);
    }
    else if (containerid === "TicketUpdates" && storedvalue1.updateTotal > 0) {
      showLoader("TicketUpdates");
      const creationDuration = getDurationForTotal(storedvalue1.creationTotal);
      const hourlyDuration = getDurationForTotal(storedvalue1.hourlyTotal);
      const updateDuration = getDurationForTotal(storedvalue1.updateTotal);
    
      const totalDuration = creationDuration + hourlyDuration + updateDuration;
    
      if (typeof totalDuration !== "number" || isNaN(totalDuration)) {
        console.error("❌ Invalid duration calculated. Skipping timer setup.");
        return;
      }
    
      console.log(`✅ Timer condition met. Setting timer for ${totalDuration} seconds.`);
    
      const timerId = "simple-timer-TicketUpdates";
      if (document.getElementById(timerId)) {
        console.log("⚠️ Timer already running for TicketUpdates. Skipping new timer setup.");
        return;
      }
    
      const container = document.getElementById("TicketUpdates");
      if (!container) {
        console.error("❌ TicketUpdates container not found.");
        return;
      }
    
      // Create the timer element
      const timerDiv = document.createElement("div");
      timerDiv.id = timerId;
      timerDiv.style.cssText = `
       position: fixed;
      top: 63%;
      left: 50%;
      transform: translateX(-50%);
     
      color: black;
      padding: 10px 20px;
      border-radius: 5px;
      font-family: sans-serif;
      font-size: 16px;
      z-index: 9999;
      `;
      timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after ${totalDuration} sec...`;
      container.appendChild(timerDiv);
    
      let remaining = totalDuration;
      const interval = setInterval(() => {
        remaining--;
        timerDiv.textContent = `The app is currently processing the data. Please refresh the page or revisit the app after  ${remaining} sec...`;
    
        if (remaining <= 0) {
          clearInterval(interval);
          timerDiv.remove();
          console.log("✅ TicketUpdates timer ended. Calling handleDuplicateRulestype(4).");
          handleDuplicateRulestype(4);
        }
      }, 1000);
    }
    
    
    
    
    if (
      storedvalue1.creationTotal === 0 ||
      storedvalue1.hourlyTotal === 0 ||
      storedvalue1.updateTotal === 0
    ) {
      await initializeDatabase();
    }
    
    if(containerid === "Ticketcreation" && storedvalue1.creationTotal === 0){
      handleDuplicateRulestype(1);
    } else if(containerid === "HourlyTriggers" && storedvalue1.hourlyTotal=== 0){
      handleDuplicateRulestype(3);
    }else if (containerid === "TicketUpdates" && storedvalue1.updateTotal === 0)
    {
      handleDuplicateRulestype(4);
    }
    if (containerid === "Ticketcreation" &&
      Number(storedvalue1.creationTotal) === 0 &&
      storedvalue1.stored === true
    )
    {
      handleDuplicateRulestype(1);
    } else if(containerid === "HourlyTriggers" && storedvalue1.hourlyTotal=== 0 && storedvalue1.stored === true){
      handleDuplicateRulestype(3);
    }else if (containerid === "TicketUpdates" && storedvalue1.updateTotal === 0 && storedvalue1.stored === true)
    {
      handleDuplicateRulestype(4);
    }
    
    

    } catch (error) { if (error.status === 404) { console.warn("⚠️ RulesDB not found, assuming first-time install."); const button = document.querySelector("fw-button"); if (button) { button.disabled = true; } } else { console.error("❌ Error retrieving stored value from RulesDB:", error); } } }

    on showing the seconds make total of three tab and show as total also add 2 mins extra from the actual (120 seconds add to actual data )

  18. Assistant

    To incorporate the functionality of checkAndSetButtonState1 in your Workflow_dashboard component with the requested timer behavior — showing a combined total timer of all three tabs plus an additional 2 minutes — here is an approach:


    What we want:

    • Receive data and containerid (like in your function).
    • Calculate durations from the three totals (creationTotal, hourlyTotal, updateTotal).
    • Sum them, add 120 seconds extra.
    • Show a centered timer message on the page.
    • Count down seconds updating message text.
    • On timer end, call the relevant handleDuplicateRulestype with your container-specific codes.
    • Store some info in localStorage as original function does.

    Here is a React hook + function you can add into your Workflow_dashboard component:

    import React, { useEffect, useState, useRef } from "react";
    
    const Workflow_dashboard = ({ client }) => {
      const [timerSeconds, setTimerSeconds] = useState(null);
      const intervalRef = useRef(null);
    
      // Stub implementations — you need to implement or import these appropriately
      const getDurationForTotal = (total) => {
        if (total <= 0) return 0;
        const baseDuration = 120; // Minimum 2 minutes
        const itemsPerStep = 100;
        const secondsPerStep = 60;
        const steps = Math.ceil(total / itemsPerStep);
        return baseDuration + (steps - 1) * secondsPerStep;
      };
    
      const showLoader = (containerid) => {
        console.log("Show loader for:", containerid);
      };
    
      const handleDuplicateRulestype = (type) => {
        console.log("handleDuplicateRulestype called with:", type);
        // Your existing handler logic
      };
    
      // Assuming data 'storedvalue1' is passed as part of 'data'
      const checkAndSetButtonState1 = async (data, containerid) => {
        try {
          localStorage.setItem("checkState_data", JSON.stringify(data));
          localStorage.setItem("checkState_containerid", containerid);
    
          const storedvalue1 = data; // for easier reference
    
          console.log("automationtypeid inside checkAndSetButtonState", data);
          console.log("storedvalue1:", storedvalue1);
    
          // Calculate total duration from all 3 totals plus 120 extra seconds
          const creationDuration = getDurationForTotal(storedvalue1.creationTotal);
          const hourlyDuration = getDurationForTotal(storedvalue1.hourlyTotal);
          const updateDuration = getDurationForTotal(storedvalue1.updateTotal);
        
          const totalDuration = creationDuration + hourlyDuration + updateDuration + 120;
    
          if (typeof totalDuration !== "number" || isNaN(totalDuration)) {
            console.error("❌ Invalid total duration calculated. Skipping timer setup.");
            return;
          }
        
          // Show loader
          showLoader(containerid);
    
          // Set timer seconds state so React shows the message and counts down
          setTimerSeconds(totalDuration);
    
          // Clear old intervals first
          if (intervalRef.current) clearInterval(intervalRef.current);
    
          let remaining = totalDuration;
    
          intervalRef.current = setInterval(() => {
            remaining--;
            setTimerSeconds(remaining);
    
            if (remaining <= 0) {
              clearInterval(intervalRef.current);
              intervalRef.current = null;
              setTimerSeconds(null);
    
              console.log(`${containerid} timer ended. Calling handleDuplicateRulestype.`);
              if (containerid === "Ticketcreation") handleDuplicateRulestype(1);
              else if (containerid === "HourlyTriggers") handleDuplicateRulestype(3);
              else if (containerid === "TicketUpdates") handleDuplicateRulestype(4);
            }
          }, 1000);
    
          // If any total is zero, call initializeDatabase async (assuming defined elsewhere)
          if (
            storedvalue1.creationTotal === 0 ||
            storedvalue1.hourlyTotal === 0 ||
            storedvalue1.updateTotal === 0
          ) {
            // await initializeDatabase();  
            // You can implement as needed
            console.log("Initialize database since one total is zero.");
          }
    
          // If totals are 0, call handleDuplicateRulestype immediately
          if (
            (containerid === "Ticketcreation" && storedvalue1.creationTotal === 0) ||
            (containerid === "HourlyTriggers" && storedvalue1.hourlyTotal === 0) ||
            (containerid === "TicketUpdates" && storedvalue1.updateTotal === 0)
          ) {
            if (containerid === "Ticketcreation") handleDuplicateRulestype(1);
            else if (containerid === "HourlyTriggers") handleDuplicateRulestype(3);
            else if (containerid === "TicketUpdates") handleDuplicateRulestype(4);
          }
    
        } catch (error) {
          console.error("Error in checkAndSetButtonState1:", error);
        }
      };
    
      // Example usage: call this after you fetch data or based on some event
      // Replace below with your actual data & containerid inputs
      useEffect(() => {
        const dummyData = {
          creationTotal: 150,
          hourlyTotal: 200,
          updateTotal: 100,
          stored: true,
        };
        const containerid = "Ticketcreation"; // or "HourlyTriggers", "TicketUpdates"
        checkAndSetButtonState1(dummyData, containerid);
    
        // Cleanup timer on unmount
        return () => {
          if (intervalRef.current) clearInterval(intervalRef.current);
        };
      }, []);
    
      return (
        <div style={{ backgroundColor: "#f0f0f0", height: "100vh", padding: 20 }}>
          <h1>Dashboard Tab</h1>
    
          {/* Render timer overlay if timer running */}
          {timerSeconds !== null && (
            <div
              style={{
                position: "fixed",
                top: "60%",
                left: "50%",
                transform: "translateX(-50%)",
                backgroundColor: "white",
                padding: "10px 20px",
                borderRadius: 5,
                fontFamily: "sans-serif",
                fontSize: 16,
                color: "black",
                zIndex: 9999,
                boxShadow: "0 0 10px rgba(0,0,0,0.15)",
                maxWidth: 350,
                textAlign: "center",
                userSelect: "none",
              }}
            >
              The app is currently processing the data.<br />
              Please refresh the page or revisit the app after {timerSeconds} sec...
            </div>
          )}
        </div>
      );
    };
    
    export default Workflow_dashboard;
    

    Explanation

    • We sum the durations for each tab using your existing getDurationForTotal.
    • Then add 120 seconds extra.
    • We show a timer message as a fixed overlay div.
    • We count down every second and update React state.
    • When timer reaches zero, clear interval, hide timer, and call handleDuplicateRulestype with appropriate code.
    • Also store some state info in localStorage (per your original function).

    Notes

    • You will need to adjust your environment to:

      • Provide the real storedvalue1 data (I've used dummyData as example).
      • Implement or import showLoader, handleDuplicateRulestype, and getDurationForTotal properly.
      • If needed, implement initializeDatabase.
    • The timer UI and logic are now React-friendly, so you do not manipulate DOM manually with document.createElement—React handles rendering.


    Let me know if you want to enhance this further or connect it with your existing data fetching logic!

  19. User

    no no t needed calling handleduplicate just make total when every data is stored, then show the dashboard until then show the seconds in html.

  20. Assistant

    Got it! You want to:

    • When you have all three totals (creationTotal, hourlyTotal, updateTotal) stored (i.e., data fetched and available),
    • Calculate the total combined timer (sum of all three durations + 120 seconds extra),
    • Show a countdown timer on the dashboard page (e.g., a message with remaining seconds),
    • When the timer reaches zero, hide the timer message and show dashboard content normally,
    • And do not call handleDuplicateRulestype or any other extra function.

    Here is a simplified version of Workflow_dashboard component that does exactly that:

    import React, { useEffect, useState, useRef } from "react";
    
    const Workflow_dashboard = ({ client }) => {
      const [timerSeconds, setTimerSeconds] = useState(null);
      const intervalRef = useRef(null);
      const [storedvalue1, setStoredvalue1] = useState(null);
    
      const getDurationForTotal = (total) => {
        if (total <= 0) return 0;
        const baseDuration = 120; // 2 mins
        const itemsPerStep = 100;
        const secondsPerStep = 60;
        const steps = Math.ceil(total / itemsPerStep);
        return baseDuration + (steps - 1) * secondsPerStep;
      };
    
      // Function to fetch storedvalue1 from client.db (or simulate it)
      const fetchStoredValueFromDB = async () => {
        try {
          const val = await client.db.get("RulesDB");
          return val;
        } catch (err) {
          console.error("Error fetching RulesDB", err);
          return null;
        }
      };
    
      // When storedvalue1 is available, start timer
      useEffect(() => {
        if (!storedvalue1) return;
    
        // Calculate combined total timer + 120 seconds extra
        const creationDuration = getDurationForTotal(storedvalue1.creationTotal || 0);
        const hourlyDuration = getDurationForTotal(storedvalue1.hourlyTotal || 0);
        const updateDuration = getDurationForTotal(storedvalue1.updateTotal || 0);
    
        // Total = sum + 120 seconds (extra)
        const totalDuration = creationDuration + hourlyDuration + updateDuration + 120;
    
        if (totalDuration <= 0) {
          setTimerSeconds(null); // no timer needed
          return;
        }
    
        // Set timer and start countdown
        setTimerSeconds(totalDuration);
    
        let remaining = totalDuration;
        if (intervalRef.current) clearInterval(intervalRef.current);
        intervalRef.current = setInterval(() => {
          remaining -= 1;
          setTimerSeconds(remaining);
          if (remaining <= 0) {
            clearInterval(intervalRef.current);
            intervalRef.current = null;
            setTimerSeconds(null);
          }
        }, 1000);
    
        return () => {
          if (intervalRef.current) clearInterval(intervalRef.current);
        };
      }, [storedvalue1]);
    
      // Fetch storedvalue1 once on mount
      useEffect(() => {
        fetchStoredValueFromDB().then((val) => {
          setStoredvalue1(val);
        });
      }, []);
    
      return (
        <div style={{ backgroundColor: "#f0f0f0", height: "100vh", padding: 20 }}>
          {timerSeconds !== null ? (
            <div
              style={{
                marginTop: 50,
                padding: "20px",
                borderRadius: 6,
                maxWidth: 400,
                backgroundColor: "white",
                fontSize: 18,
                textAlign: "center",
                userSelect: "none",
                boxShadow: "0 0 10px rgba(0,0,0,0.15)",
                marginLeft: "auto",
                marginRight: "auto",
              }}
            >
              The app is currently processing the data.<br />
              Please wait for <strong>{timerSeconds}</strong> seconds before using the dashboard.
            </div>
          ) : (
            <>
              <h1>Dashboard Tab</h1>
              {/* Your actual dashboard content here */}
            </>
          )}
        </div>
      );
    };
    
    export default Workflow_dashboard;
    

    How this works:

    • On mount, it fetches storedvalue1 from your database.
    • When storedvalue1 is received, it calculates the total duration:
      • sum of durations from all three totals using your existing logic getDurationForTotal
      • plus an extra fixed 120 seconds.
    • Starts a countdown timer.
    • While timer is running (timerSeconds !== null), it shows the timer message.
    • When timer reaches zero, it hides the timer message and shows your dashboard content.
    • No calls to handleDuplicateRulestype or other side effects.

    You can replace the dummy dashboard content with your real dashboard UI.


    Let me know if you want me to help connect this with your existing timer logic or other parts!