Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

import React, { useState, useEffect } from "react"; import { FwTabs, FwTab, FwTabPanel,…

  1. User

    import React, { useState, useEffect } from "react"; import { FwTabs, FwTab, FwTabPanel, FwSpinner } from "@freshworks/crayons/react"; import AutomationCard from "./AutomationCard"; import { getTicketCreationRules, getTicketUpdationRules, getHourlyRules } from '../common';

    const ITEMS_PER_PAGE = 30;

    const getRuleSignature = (rule) => { return JSON.stringify({ conditions: rule.summary.conditions, actions: rule.summary.actions, }); };

    const groupDuplicates = (rules) => { const grouped = {}; rules.forEach((rule) => { const signature = getRuleSignature(rule); if (!grouped[signature]) { grouped[signature] = []; } grouped[signature].push(rule); }); return Object.values(grouped); };

    const AutomationTabs = ({ client }) => { const [searchTerm, setSearchTerm] = useState(""); const [searchTriggered, setSearchTriggered] = useState(false); const [activeTab, setActiveTab] = useState("ticketcreate");

    const [ticketCreationRules, setTicketCreationRules] = useState([]); const [ticketUpdateRules, setTicketUpdateRules] = useState([]); const [hourlyTriggerRules, setHourlyTriggerRules] = useState([]);

    const [loading, setLoading] = useState(true);

    const [currentPage, setCurrentPage] = useState(1);

    useEffect(() => { const fetchRules = async () => { setLoading(true); await Promise.all([ getTicketCreationRules(client, setTicketCreationRules), getTicketUpdationRules(client, setTicketUpdateRules), getHourlyRules(client, setHourlyTriggerRules), ]); setLoading(false); }; fetchRules(); }, [client]);

    const getFilteredGroups = (rules) => { const groupedRules = groupDuplicates(rules); if (!searchTriggered || !searchTerm.trim()) return groupedRules;

    return groupedRules.filter((rule) =>
      rule.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      rule.description?.toLowerCase().includes(searchTerm.toLowerCase())
    );
    

    };

    const paginate = (rules) => { const startIndex = (currentPage - 1) * ITEMS_PER_PAGE; return rules.slice(startIndex, startIndex + ITEMS_PER_PAGE); };

    const renderGroupedRules = (groups) => { if (loading) { return ( <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '200px' }}> ); }

    return groups.length > 0 ? (
      paginate(groups).map((group, index) => (
        <div key={index} className="fw-card-1 fw-py-16" style={{ border: "1px solid #ddd", borderRadius: "8px", marginBottom: "20px", marginTop: "20px", padding: "10px 16px", boxShadow: "0 4px 8px rgba(0, 0, 0, 0.1)", width: "80%", marginLeft: "auto", marginRight: "auto" }}>
          {group.map((rule, idx) => (
            <AutomationCard key={idx} rule={rule} index={idx + 1} isFirstInGroup={idx === 0} />
          ))}
        </div>
      ))
    ) : (
      <p style={{ textAlign: "center", marginTop: "20px" }}>No Rules Found Matched Your Search: {searchTerm}</p>
    );
    

    };

    const getRulesByTab = () => { switch (activeTab) { case "ticketcreate": return ticketCreationRules; case "ticketupdate": return ticketUpdateRules; case "hourly": return hourlyTriggerRules; default: return []; } };

    const totalRules = getRulesByTab().length; const startIndex = (currentPage - 1) * ITEMS_PER_PAGE + 1; const endIndex = Math.min(currentPage * ITEMS_PER_PAGE, totalRules);

    return ( <> Automations - Rules <input type="text" placeholder="Search by name or description" value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} /> <button onClick={() => { setSearchTriggered(true); }}>Search

      <FwTabs onFwChange={(e) => { setActiveTab(e.target.panel); setCurrentPage(1); }}>
        <FwTab slot="tab" panel="ticketcreate">Ticket Create</FwTab>
        <FwTab slot="tab" panel="ticketupdate">Ticket Update</FwTab>
        <FwTab slot="tab" panel="hourly">Hourly Triggers</FwTab>
    
        <FwTabPanel name="ticketcreate">
          {renderGroupedRules(getFilteredGroups(ticketCreationRules))}
        </FwTabPanel>
    
        <FwTabPanel name="ticketupdate">
          {renderGroupedRules(getFilteredGroups(ticketUpdateRules))}
        </FwTabPanel>
    
        <FwTabPanel name="hourly">
          {renderGroupedRules(getFilteredGroups(hourlyTriggerRules))}
        </FwTabPanel>
      </FwTabs>
    
      <div style={{ textAlign: 'center', marginTop: '20px' }}>
        <p>{startIndex} - {endIndex} of {totalRules}</p>
        <button disabled={currentPage === 1} onClick={() => setCurrentPage(currentPage - 1)}>Previous</button>
        <span style={{ margin: '0 10px' }}>Page {currentPage}</span>
        <button disabled={paginate(getRulesByTab()).length < ITEMS_PER_PAGE} onClick={() => setCurrentPage(currentPage + 1)}>Next</button>
      </div>
    </>
    

    ); };

    export default AutomationTabs;

    pagination is not working correctly

    please fix that

  2. Assistant

    It looks like the pagination logic in your AutomationTabs component may have a couple of issues, particularly when fetching paginated data after applying your filters. Let's take a closer look and ensure the pagination works as you expect.

    Fixes to Consider

    1. Update the paginate Function: You need to use the filtered rules based on the active tab and the search term while paginating. Make sure that pagination is applied to the already filtered rules, not the entire list.

    2. Adjust totalRules: Make sure totalRules reflects the number of rules based on the active tab and the search filters.

    Updated Code

    Here's an updated version of your AutomationTabs component with some fixes incorporated:

    import React, { useState, useEffect } from "react";
    import { FwTabs, FwTab, FwTabPanel, FwSpinner } from "@freshworks/crayons/react";
    import AutomationCard from "./AutomationCard";
    import { getTicketCreationRules, getTicketUpdationRules, getHourlyRules } from '../common';
    
    const ITEMS_PER_PAGE = 30;
    
    const getRuleSignature = (rule) => {
      return JSON.stringify({
        conditions: rule.summary.conditions,
        actions: rule.summary.actions,
      });
    };
    
    const groupDuplicates = (rules) => {
      const grouped = {};
      rules.forEach((rule) => {
        const signature = getRuleSignature(rule);
        if (!grouped[signature]) {
          grouped[signature] = [];
        }
        grouped[signature].push(rule);
      });
      return Object.values(grouped);
    };
    
    const AutomationTabs = ({ client }) => {
      const [searchTerm, setSearchTerm] = useState("");
      const [searchTriggered, setSearchTriggered] = useState(false);
      const [activeTab, setActiveTab] = useState("ticketcreate");
    
      const [ticketCreationRules, setTicketCreationRules] = useState([]);
      const [ticketUpdateRules, setTicketUpdateRules] = useState([]);
      const [hourlyTriggerRules, setHourlyTriggerRules] = useState([]);
    
      const [loading, setLoading] = useState(true);
      const [currentPage, setCurrentPage] = useState(1);
    
      useEffect(() => {
        const fetchRules = async () => {
          setLoading(true);
          await Promise.all([
            getTicketCreationRules(client, setTicketCreationRules),
            getTicketUpdationRules(client, setTicketUpdateRules),
            getHourlyRules(client, setHourlyTriggerRules),
          ]);
          setLoading(false);
        };
        fetchRules();
      }, [client]);
    
      const getFilteredGroups = (rules) => {
        const groupedRules = groupDuplicates(rules);
        if (!searchTriggered || !searchTerm.trim()) return groupedRules;
    
        return groupedRules.filter((rule) =>
          rule.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
          rule.description?.toLowerCase().includes(searchTerm.toLowerCase())
        );
      };
    
      const paginate = (rules) => {
        const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
        return rules.slice(startIndex, startIndex + ITEMS_PER_PAGE);
      };
    
      const renderGroupedRules = (groups) => {
        if (loading) {
          return (
            <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '200px' }}>
              <FwSpinner size="medium" color="green" />
            </div>
          );
        }
    
        return groups.length > 0 ? (
          paginate(groups).map((group, index) => (
            <div key={index} className="fw-card-1 fw-py-16" style={{ border: "1px solid #ddd", borderRadius: "8px", marginBottom: "20px", marginTop: "20px", padding: "10px 16px", boxShadow: "0 4px 8px rgba(0, 0, 0, 0.1)", width: "80%", marginLeft: "auto", marginRight: "auto" }}>
              {group.map((rule, idx) => (
                <AutomationCard key={idx} rule={rule} index={idx + 1} isFirstInGroup={idx === 0} />
              ))}
            </div>
          ))
        ) : (
          <p style={{ textAlign: "center", marginTop: "20px" }}>No Rules Found Matched Your Search: {searchTerm}</p>
        );
      };
    
      const getRulesByTab = () => {
        switch (activeTab) {
          case "ticketcreate":
            return ticketCreationRules;
          case "ticketupdate":
            return ticketUpdateRules;
          case "hourly":
            return hourlyTriggerRules;
          default:
            return [];
        }
      };
    
      // Filtering rules based on active tab and search term
      const filteredRules = getFilteredGroups(getRulesByTab());
    
      // Pagination
      const totalRules = filteredRules.length;
      const startIndex = (currentPage - 1) * ITEMS_PER_PAGE + 1;
      const endIndex = Math.min(currentPage * ITEMS_PER_PAGE, totalRules);
    
      return (
        <>
          <h2>Automations - Rules</h2>
          <input
            type="text"
            placeholder="Search by name or description"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
          <button onClick={() => { setSearchTriggered(true); }}>Search</button>
    
          <FwTabs onFwChange={(e) => { setActiveTab(e.target.panel); setCurrentPage(1); }}>
            <FwTab slot="tab" panel="ticketcreate">Ticket Create</FwTab>
            <FwTab slot="tab" panel="ticketupdate">Ticket Update</FwTab>
            <FwTab slot="tab" panel="hourly">Hourly Triggers</FwTab>
    
            <FwTabPanel name="ticketcreate">
              {renderGroupedRules(filteredRules)}
            </FwTabPanel>
    
            <FwTabPanel name="ticketupdate">
              {renderGroupedRules(filteredRules)}
            </FwTabPanel>
    
            <FwTabPanel name="hourly">
              {renderGroupedRules(filteredRules)}
            </FwTabPanel>
          </FwTabs>
    
          <div style={{ textAlign: 'center', marginTop: '20px' }}>
            <p>{startIndex} - {endIndex} of {totalRules}</p>
            <button disabled={currentPage === 1} onClick={() => setCurrentPage(currentPage - 1)}>Previous</button>
            <span style={{ margin: '0 10px' }}>Page {currentPage}</span>
            <button disabled={paginate(filteredRules).length < ITEMS_PER_PAGE} onClick={() => setCurrentPage(currentPage + 1)}>Next</button>
          </div>
        </>
      );
    };
    
    export default AutomationTabs;
    

    Summary of Changes

    1. Filtering rules is done based on the content relevant to the tab currently selected and the search term.
    2. Pagination is now done on the filteredRules derived from getFilteredGroups(getRulesByTab()), ensuring correct pagination based on the search criteria.
    3. Ensure that the pagination buttons logic works properly by checking the length of the paginated filtered rules.

    With these changes, the pagination should now work correctly, reflecting the rules based on the active tab and any search filters applied.