jeudi 30 mars 2023

Want to save to checked and unchecked checkboxes in react?

i have popup modal in which there is "Select All" checkbox of module and its features checkboxes and when i click on Select All checkbox then its features checkboxes should also checked and vice versa . And when i click on save button then all the unchecked and checked checkboxes should be sent to server in which checked checkboxes as true and unchecked checkboxes as false.But the problem is here that "rights" are saving correctly then after closing popup if i want to edit rights for which i click on "Access" button again then popup should be open with selected right but in my case all checkboxes are checked coming and when i want to uncheck any checkbox this it is not working neither it is saved when click on "save" button .Anyone can help me ?

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

const ManageAccessGroups_assignRightsModal = ({ AgetGroupName }) => {
  const [GAMgetGroupsRights, setGAMgetGroupsRights] = useState([]);
  const [checkboxValues, setCheckboxValues] = useState([]);
  const [selectAll, setSelectAll] = useState([
    { moduleId: 1, checked: false },
    { moduleId: 2, checked: false },
    { moduleId: 4, checked: false },
    { moduleId: 5, checked: false },
    { moduleId: 6, checked: false },
    { moduleId: 7, checked: false },
    { moduleId: 8, checked: false },
    { moduleId: 9, checked: false },
    { moduleId: 10,checked: false },
    { moduleId: 11,checked: false },
    { moduleId: 12,checked: false },
  ]);
  
  const ManageAccessGroups_assignRightsModal_getAccessRights = async (id) => 
  {
    try 
    {
      const response = await axios.get(
        `${process.env.REACT_APP_API_URL}accessgrouprights/group/${id}`,
        {
          headers: 
          {
            "content-type": "application/json",
            Authorization: localStorage.getItem("token"),
          },
        }
      );
      const data = await response.data;
      setGAMgetGroupsRights(data);
      console.log(
        "group access rights   ==> ManageAccessGroups_assignRightsModal_getAccessRights",
        data
      );
      return data;
    } catch (error) 
    {
      console.log(
        "group access rights error ==> ManageAccessGroups_assignRightsModal_getAccessRights",
        error
      );
    }
  };
 // save rights   --start
 
  const handleCheckboxChange = (event, index) => 
  {
    const { name, checked } = event.target;
    const newGAMgetGroupsRights = [...GAMgetGroupsRights];
    const item = newGAMgetGroupsRights.flatMap((gRights) => gRights.accessGroupRightsList).find((item, i) => i === index);
    if (item) {
      item[name] = checked;
      setGAMgetGroupsRights(newGAMgetGroupsRights);
    }
  };

  const getSelectedPermissions = () => 
  {
    const selectedPermissions = [];
    GAMgetGroupsRights?.forEach((module) => {
      module.accessGroupRightsList?.forEach((item) => 
      {
        if (item.features.allowedView) 
        {
          selectedPermissions.push({
            createdBy: 12,
            createdOn: "2023-03-13T05:04:53.681Z", 
            viewRights: true,
            addRights: false,
            editRights: false,
            deleteRights: false,
            accessGroupId: item.accessGroupId,
            featureId: item.features.featureId,
          });
        }
        if (item.features.allowedAdd) 
        {
          selectedPermissions.push({
            createdBy: 12, 
            createdOn: "2023-03-13T05:04:53.681Z", 
            viewRights: false,
            addRights: true,
            editRights: false,
            deleteRights: false,
            accessGroupId: item.accessGroupId, 
            featureId: item.features.featureId,
          });
        }
        if (item.features.allowedEdit) {
          selectedPermissions.push({
            createdBy: 12, 
            createdOn: "2023-03-13T05:04:53.681Z", 
            viewRights: false,
            addRights: false,
            editRights: true,
            deleteRights: false,
            accessGroupId: item.accessGroupId, 
            featureId: item.features.featureId,
          });
        }
        if (item.features.allowedDelete) 
        {
          selectedPermissions.push({
            createdBy: 12, 
            createdOn: "2023-03-13T05:04:53.681Z", 
            viewRights: false,
            addRights: false,
            editRights: false,
            deleteRights: true,
            accessGroupId: item.accessGroupId, 
            featureId: item.features.featureId,
          });
        }
      });
    });
    return selectedPermissions;
  };
  
  const handleSelectAll = (event, moduleId) => 
  {
    const { checked } = event.target;
    const newGAMgetGroupsRights = [...GAMgetGroupsRights];
    const moduleIndex = newGAMgetGroupsRights.findIndex((module) => module.moduleId === moduleId);
    if (moduleIndex !== -1) 
    {
      newGAMgetGroupsRights[moduleIndex].accessGroupRightsList.forEach((item) => 
      {
        if (item.features.allowedView) 
        {
          item.viewRights = checked;
        }
        if (item.features.allowedAdd) 
        {
          item.addRights = checked;
        }
        if (item.features.allowedEdit) 
        {
          item.editRights = checked;
        }
        if (item.features.allowedDelete) 
        {
          item.deleteRights = checked;
        }
      });
    }
      setGAMgetGroupsRights(newGAMgetGroupsRights);
  
      const newSelectAll = [...selectAll];
      const moduleSelectAll = newSelectAll.find((item) => item.moduleId === moduleId);
    if (moduleSelectAll) 
    {
      moduleSelectAll.checked = checked;
      setSelectAll(newSelectAll);
    }
  };

  const ManageAccessGroups_assignRightsModal_insertGroupRights = async () => 
  { 
   
    const selectedPermissions = getSelectedPermissions();
    console.log("check adata", selectedPermissions)
    try 
    {
      const response = await axios.post(
        `${process.env.REACT_APP_API_URL}accessgrouprights/insert-data`,
        selectedPermissions,
        {
          headers: 
          {
            "Content-Type": "application/json",
            Authorization: localStorage.getItem("token"),
          },
        }
      );
      console.log("Rights saved success ==> ManageAccessGroups_assignRightsModal_insertGroupRights:", response.data);
    } 
    catch (error) 
    {
      console.error("Error saving rights error ==> ManageAccessGroups_assignRightsModal_insertGroupRights:", error);
    }
  };

  useEffect(() => 
  {
    const initialCheckboxValues = [];
    GAMgetGroupsRights?.forEach((gRights) => {
      gRights.accessGroupRightsList?.forEach((item) => {
        initialCheckboxValues.push({
          moduleId: gRights.moduleId,
          accessGroupId: item.accessGroupId,
          featureId: item.features.featureId,
          read:   item.viewRights,
          create: item.addRights,
          update: item.editRights,
          delete: item.deleteRights,
        });
      });
    });
  
    setCheckboxValues(initialCheckboxValues);
  }, []);
  
  // save rights  ---end

  useEffect(() => 
  {
    ManageAccessGroups_assignRightsModal_getAccessRights(AgetGroupName?.id);
  }, [AgetGroupName?.id]);

  return (
    <div>
      <div
        class="modal modal-static fade"
        id="kf-AccessRightsModal"
        tabindex="-1"
        aria-hidden="true"
        data-bs-backdrop="static"
      >
        <div class="modal-dialog modal-dialog-centered mw-750px">
          <div class="modal-content">
            <div class="modal-header">
              <h2 class="fw-bold">Group Access Rights</h2>
              <div
                class="btn btn-icon btn-sm btn-active-icon-primary"
                data-bs-dismiss="modal"
              >
                <span class="svg-icon svg-icon-1">
                  <svg
                    width="24"
                    height="24"
                    viewBox="0 0 24 24"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <rect
                      opacity="0.5"
                      x="6"
                      y="17.3137"
                      width="16"
                      height="2"
                      rx="1"
                      transform="rotate(-45 6 17.3137)"
                      fill="currentColor"
                    />
                    <rect
                      x="7.41422"
                      y="6"
                      width="16"
                      height="2"
                      rx="1"
                      transform="rotate(45 7.41422 6)"
                      fill="currentColor"
                    />
                  </svg>
                </span>
              </div>
            </div>
            <div class="modal-body scroll-y mx-5 my-7" style=>
              <form id="kt_modal_update_role_form" class="form" action="#">
                <div
                  class="d-flex flex-column scroll-y me-n7 pe-7"
                  id="kt_modal_update_role_scroll"
                  data-kt-scroll="true"
                  data-kt-scroll-activate="{default: false, lg: true}"
                  data-kt-scroll-max-height="auto"
                  data-kt-scroll-dependencies="#kt_modal_update_role_header"
                  data-kt-scroll-wrappers="#kt_modal_update_role_scroll"
                  data-kt-scroll-offset="300px"
                >
                  <div class="fv-row mb-10">
                    <label class="fs-5 fw-bold form-label mb-2">
                      <span class="required">Group name</span>
                    </label>
                    <input
                      class="form-control form-control-solid"
                      placeholder="Enter a role name"
                      name="role_name"
                      value={AgetGroupName?.name}
                    />
                  </div>
                  <div class="fv-row">
                    <label class="fs-5 fw-bold form-label mb-2">
                      Group Permissions
                    </label>
                    <div class="table-responsive">
                      <table class="table align-middle table-row-dashed fs-6 gy-5">
                        {GAMgetGroupsRights?.map((gRights) => (
                          <tbody class="text-gray-600 fw-semibold">
                            <>
                            {console.log("grights ",gRights )}
                              <tr className="row">
                                <td
                                  class="col-4 text-gray-800  px-4 text-start"
                                  key={gRights?.moduleId}
                                  style=
                                >
                                  {console.log("grights ",gRights.moduleNameEn )}
                                  {gRights?.moduleNameEn}
                                  <i
                                    class="fas fa-exclamation-circle ms-1 fs-7"
                                    data-bs-toggle="tooltip"
                                    title="Allows a full access to the system"
                                  ></i>
                                </td>
                                <td className="col-4">
                                  <label class=" form-check form-check-sm form-check-custom form-check-solid ">
                                    <input
                                      class="form-check-input"
                                      type="checkbox"
                                      value=""
                                      id={`select-all-${gRights.accessGroupId}`}
                                      checked={selectAll.find((item) => item.moduleId === gRights.moduleId)?.checked || false}  
                                      onChange={(event) => handleSelectAll(event, gRights.moduleId)}
                                    />
                                    <span
                                      class="form-check-label"
                                      for="kt_roles_select_all"
                                    >
                                      Select all
                                    </span>
                                  </label>
                                </td>
                              </tr>
                              <tr>
                                <td>
                                  {gRights?.accessGroupRightsList?.map(
                                    (item, index) => (
                                      <td className="d-flex justify-content-between ">
                                        <label class="text-gray-800 w-200px">
                                          {item?.features?.featureNameEn}
                                        </label>
                                        <td>
                                          <div class="d-flex mx-12 ">
                                            <label class="form-check form-check-sm form-check-custom form-check-solid me-lg-10 ">
                                              <input
                                                class="form-check-input"
                                                type="checkbox"
                                                value=""
                                                disabled={!item?.features?.allowedView}
                                                id={`read-${index}`} name="read" checked={item.viewRights} onChange={(event) => handleCheckboxChange(event, index)}
                                              />
                                              <span class="form-check-label">
                                                Read
                                              </span>
                                            </label>
                                            <label class="form-check form-check-sm form-check-custom form-check-solid me-lg-10 ">
                                              <input
                                                class="form-check-input"
                                                type="checkbox"
                                                value=""
                                                disabled={!item.features.allowedAdd}
                                                id={`create-${index}`} name="create" checked={item.addRights} onChange={(event) => handleCheckboxChange(event, index)}
                                              />
                                              <span class="form-check-label">
                                                Create
                                              </span>
                                            </label>
                                            <label class="form-check form-check-sm form-check-custom form-check-solid me-lg-10 ">
                                              <input
                                                class="form-check-input"
                                                type="checkbox"
                                                value=""
                                                disabled={!item.features.allowedEdit}
                                                id={`update-${index}`} name="update" checked={item.editRights} onChange={(event) => handleCheckboxChange(event, index)} 
                                              />
                                              <span class="form-check-label">
                                                Update
                                              </span>
                                            </label>
                                            <label class="form-check form-check-sm form-check-custom form-check-solid me-lg-10 ">
                                              <input
                                                class="form-check-input"
                                                type="checkbox"
                                                value=""
                                                disabled={!item.features.allowedDelete}
                                                id={`delete-${index}`} name="delete" checked={item.deleteRights} onChange={(event) => handleCheckboxChange(event, index)}
                                              />
                                              <span class="form-check-label">
                                                Delete
                                              </span>
                                            </label>
                                          </div>
                                        </td>
                                      </td>
                                    )
                                  )}
                                </td>
                              </tr>
                            </>
                          </tbody>
                        ))}
                      </table>
                    </div>
                  </div>
                </div>
                <div class="text-center pt-15">
                  <button
                    type="reset"
                    class="btn btn-light me-3"
                    data-bs-dismiss="modal"
                  >
                    Discard
                  </button>
                  <button
                    type="submit"
                    class="btn btn-primary"
                    data-kt-roles-modal-action="submit"
                    onClick={() => ManageAccessGroups_assignRightsModal_insertGroupRights(AgetGroupName?.id)}
                  >
                    <span class="indicator-label">Save</span>
                    <span class="indicator-progress">
                      Please wait...
                      <span class="spinner-border spinner-border-sm align-middle ms-2"></span>
                    </span>
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ManageAccessGroups_assignRightsModal;




Aucun commentaire:

Enregistrer un commentaire