From a5b194e002e4ee7a025be1ce6e2c03f2e15770de Mon Sep 17 00:00:00 2001 From: Clara Ribeiro Date: Sun, 19 Jan 2025 10:07:44 -0300 Subject: [PATCH 1/5] chore: atualiza arquivo sonar-metrics.py --- metrics/sonar-metrics.py | 237 ++++++++++++++++++++++++++++++--------- 1 file changed, 186 insertions(+), 51 deletions(-) diff --git a/metrics/sonar-metrics.py b/metrics/sonar-metrics.py index 906045f1..a3b9211f 100644 --- a/metrics/sonar-metrics.py +++ b/metrics/sonar-metrics.py @@ -1,58 +1,193 @@ import json +import requests import sys -import urllib.request from datetime import datetime +import requests +# import datetime +import pandas as pd +import os +from packaging import version +from dotenv import load_dotenv -def generate_metrics(): - # url base do sonar, inicio da rota que devolverá as métricas - base_url = "https://sonarcloud.io/api/measures/component_tree?component=" - # prefixo da disciplina, identificador da organização no sonarcloud - prefix = "fga-eps-mds" - # todas as métricas que serão requisitadas para o sonarcloud - metrics = [ - "files", - "functions", - "complexity", - "comment_lines_density", - "duplicated_lines_density", - "coverage", - "ncloc", - "tests", - "test_errors", - "test_failures", - "test_execution_time", - "security_rating" - ] - - # nome do repositório, vem como argumento no release.yml - repository_name = sys.argv[1] - # nome da branch onde foi chamada o script, vem de argumento no release.yml - ref_name = sys.argv[2] - - # url montada - # base url = api do sonar - # prefix = id da org da disciplina - # repository_name = nome do repositorio (unido com prefix separado por _ é o identificador do projeto no sonar) - # o join do metrics une as métricas a serem solicitadas como parâmetros - # branch = específica o nome da branch para pegar as métricas daquela branch em específicp - - # Verifica se a referência é uma branch ou uma tag - url = f'{base_url}{prefix}_{repository_name}&metricKeys={",".join(metrics)}&branch={ref_name}' if 'refs/heads/' in sys.argv[2] else f'{base_url}{prefix}_{repository_name}&metricKeys={",".join(metrics)}&tag={ref_name}' - - - with urllib.request.urlopen(url) as res: - data = json.load(res) - date = datetime.now() - date_padrao_hilmer = f"{date.month}-{date.day}-{date.year}-{date.hour}-{date.minute}-{date.second}" - - underlined_repo_name = repository_name[:16] + \ - repository_name[16:].replace('-', "_") - - filename = f"{prefix}-{underlined_repo_name}-{date_padrao_hilmer}-{ref_name}.json" - print(filename) - with open(filename, "w") as file: - json.dump(data, file) +###################################### +# DECLARAÇÃO DE CONSTANTES/VARIÁVEIS # +###################################### +TODAY = datetime.now() +load_dotenv() +# Variáveis globais ao repositório +OWNER = "fga-eps-mds" +REPO = os.getenv('REPO') +REPO_ISSUES = os.getenv('REPO_DOC') + +# Configurar as variáveis de ambiente +GITHUB_TOKEN = os.getenv('GITHUB_TOKEN') +RELEASE_MAJOR = os.getenv('RELEASE_MAJOR') +RELEASE_MINOR = os.getenv('RELEASE_MINOR') +RELEASE_FIX = os.getenv('RELEASE_FIX') +DEVELOP = os.getenv('DEVELOP') + +METRICS_SONAR = [ + "files", + "functions", + "complexity", + "comment_lines_density", + "duplicated_lines_density", + "coverage", + "ncloc", + "tests", + "test_errors", + "test_failures", + "test_execution_time", + "security_rating", +] + +BASE_URL_SONAR = "https://sonarcloud.io/api/measures/component_tree?component=fga-eps-mds_" + +# Utilize a api que for necessária +# api_url_workflows = f"https://api.github.com/repos/{owner}/{repo}/actions/workflows" +# api_url_jobs = f"https://api.github.com/repos/{owner}/{repo}/actions/runs/3624383254/jobs" +# api_url_deployments = f"https://api.github.com/repos/{owner}/{repo}/deployments" +api_url_runs = f"https://api.github.com/repos/{OWNER}/{REPO}/actions/runs" +api_url_issues = f"https://api.github.com/repos/{OWNER}/{REPO_ISSUES}/issues" + +################### +# FUNÇÕES RELEASE # +################### +# Pega a última release +def get_latest_release(): + url = f'https://api.github.com/repos/{OWNER}/{REPO}/releases' + headers = { + 'Authorization': f'token {GITHUB_TOKEN}' + } + response = requests.get(url, headers=headers) + releases = response.json() + + if releases: + return releases[0].get('tag_name', '0.0.0') + return '0.0.0' + +# Cria um novo nome de tag +def new_tag_name(): + old_tag = get_latest_release() + try: + old_version = version.parse(old_tag) + except version.InvalidVersion: + old_version = version.parse('0.0.0') + + if RELEASE_MAJOR == 'true': + return f'{old_version.major + 1}.0.0' + elif RELEASE_MINOR == 'true': + return f'{old_version.major}.{old_version.minor + 1}.0' + elif RELEASE_FIX == 'true': + return f'{old_version.major}.{old_version.minor}.{old_version.micro + 1}' + else: + return f'{old_version.major}.{old_version.minor}.{old_version.micro + 1}' + +# Cria a nova release +def create_release(): + tag = new_tag_name() + url = f'https://api.github.com/repos/{OWNER}/{REPO}/releases' + headers = { + 'Authorization': f'token {GITHUB_TOKEN}', + 'Accept': 'application/vnd.github.v3+json' + } + payload = { + 'tag_name': tag, + 'name': tag + } + response = requests.post(url, headers=headers, json=payload) + res_data = response.json() + return res_data.get('upload_url'), tag + +################# +# FUNÇÕES SONAR # +################# + +def save_sonar_metrics(tag): + response = requests.get(f'{BASE_URL_SONAR}{REPO}&metricKeys={",".join(METRICS_SONAR)}&ps=500') + + j = json.loads(response.text) + + print("Extração do Sonar concluída.") + + file_path = f'./analytics-raw-data/fga-eps-mds-{REPO}-{TODAY.strftime("%m-%d-%Y-%H-%M-%S")}-{tag}.json' + + with open(file_path, 'w') as fp: + fp.write(json.dumps(j)) + fp.close() + + return + +################## +# FUNÇÕES GITHUB # +################## + +def all_request_pages(data): + total_runs = data["total_count"] + pages = (total_runs // 100) + (1 if total_runs % 100 > 0 else 0) + for i in range(pages+1): + if i == 0 or i == 1: + continue + api_url_now = api_url_runs + "?page=" + str(i) + response = requests.get(api_url_now) + for j in ((response.json()['workflow_runs'])): + data['workflow_runs'].append(j) + return data + +def filter_request_per_date(data, date): + data_filtered = [] + for i in data["workflow_runs"]: + if datetime.strptime(i["created_at"][:10],"%Y-%m-%d").strftime("%Y-%m-%d") == date: + data_filtered.append(i) + return {"workflow_runs": data_filtered} + +def save_github_metrics_runs(): + response = requests.get(api_url_runs, params={'per_page': 100,}) + + data = response.json() + + # date = datetime.strptime("2023-03-23","%Y-%m-%d").strftime("%Y-%m-%d") + data = all_request_pages(data) + + print("Quantidade de workflow_runs: " + str(len(data["workflow_runs"]))) + + file_path = f'./analytics-raw-data/GitHub_API-Runs-fga-eps-mds-{REPO}-{TODAY.strftime("%m-%d-%Y-%H-%M-%S")}.json' + + # Salva os dados em um json file + with open(file_path, 'w') as fp: + fp.write(json.dumps(data)) + fp.close() + + return + +def save_github_metrics_issues(): + issues = [] + page = 1 + + while True: + response = requests.get(api_url_issues, params={'state': 'all', 'per_page': 100, 'page': page}) + + page_issues = response.json() + if not page_issues: + break + + issues.extend(page_issues) + print(f"Página {page}: {len(page_issues)} issues carregadas.") + + page += 1 + + print("Quantidade total de issues: " + str(len(issues))) + + file_path = f'./analytics-raw-data/GitHub_API-Issues-fga-eps-mds-{REPO_ISSUES}.json' + + # Salvar todas as issues em um arquivo JSON + with open(file_path, 'w') as fp: + json.dump(issues, fp, indent=4) if __name__ == "__main__": - generate_metrics() + _, tag = create_release() + + save_sonar_metrics(tag) + save_github_metrics_runs() + save_github_metrics_issues() \ No newline at end of file From 69fb56cdd7d1ad9fc72080dc4ac0854531981530 Mon Sep 17 00:00:00 2001 From: Clara Ribeiro Date: Sun, 19 Jan 2025 10:24:30 -0300 Subject: [PATCH 2/5] fix: release workflow --- .github/workflows/release.yml | 61 +++++++++++-------- .../parser.py | 0 2 files changed, 34 insertions(+), 27 deletions(-) rename metrics/sonar-metrics.py => sonar_scripts/parser.py (100%) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7754c40e..81edc3b4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,6 @@ -name: front-release +name: Export de métricas -on: +on: push: branches: [master] tags: @@ -9,39 +9,46 @@ on: branches: - master - devel - types: [closed] - + types: [ closed ] jobs: - generate-release: - runs-on: ubuntu-latest + release: + if: github.event.pull_request.merged == true && contains(github.event.pull_request.labels.*.name, 'NOT RELEASE') == false + runs-on: "ubuntu-latest" + environment: actions + steps: - - name: Checkout code - uses: actions/checkout@v3 - - - name: 'Get Previous tag' - id: previoustag - uses: "WyriHaximus/github-action-get-previous-tag@v1" + - uses: actions/checkout@v3 with: - fallback: 1.0.0 + fetch-depth: 0 + + - name: Install dotenv + run: pip install python-dotenv packaging pandas + + - name: Cria arquivo .env + run: | + touch ./sonar_scripts/.env + echo GITHUB_TOKEN=${{secrets.PERSONAL_TOKEN}} >> ./sonar_scripts/.env + echo RELEASE_MAJOR=${{ contains(github.event.pull_request.labels.*.name, 'MAJOR RELEASE') }} >> ./sonar_scripts/.env + echo RELEASE_MINOR=${{ contains(github.event.pull_request.labels.*.name, 'MINOR RELEASE') }} >> ./sonar_scripts/.env + echo RELEASE_FIX=${{ contains(github.event.pull_request.labels.*.name, 'FIX RELEASE') }} >> ./sonar_scripts/.env + echo DEVELOP=${{ contains(github.event.pull_request.labels.*.name, 'DEVELOP') }} >> ./sonar_scripts/.env + echo REPO=${{ github.event.repository.name }} >> ./sonar_scripts/.env - - name: Use Node.js 16.x - uses: actions/setup-node@v3 - with: - node-version: 16.x + - name: Criar diretório + run: mkdir -p analytics-raw-data - - name: Cria métricas do SonarCloud - run: python metrics/sonar-metrics.py ${{ github.event.repository.name }} ${{ github.ref_name }} + - name: Coletar métricas no SonarCloud + run: python ./sonar_scripts/parser.py - - name: Commita arquivos de métricas do SonarCloud + - name: Envia métricas para repo de Doc run: | - git config --global user.email "${{ secrets.GIT_EMAIL }}" - git config --global user.name "${{ secrets.GIT_USER }}" - git clone --single-branch --branch main "https://x-access-token:${{ secrets.PERSONAL_TOKEN }}@github.com/fga-eps-mds/2024.2-SENTINELA-DOC" doc + git config --global user.email "${{secrets.GIT}}" + git config --global user.name "${{secrets.GIT}}" + git clone --single-branch --branch main "https://x-access-token:${{secrets.PERSONAL_TOKEN}}@github.com/fga-eps-mds/2024.2-SENTINELA-DOC" doc mkdir -p doc/analytics-raw-data - cp -R fga-eps-mds*.json doc/analytics-raw-data + cp -R analytics-raw-data/*.json doc/analytics-raw-data cd doc git add . - git commit -m "Métricas SonarCloud - ${{ github.event.repository.name }} ${{ github.ref_name }}" - git push - echo "Arquivos de métricas gerado com sucesso." \ No newline at end of file + git commit -m "Adicionando métricas do repositório ${{ github.event.repository.name }} ${{ github.ref_name }}" + git push \ No newline at end of file diff --git a/metrics/sonar-metrics.py b/sonar_scripts/parser.py similarity index 100% rename from metrics/sonar-metrics.py rename to sonar_scripts/parser.py From fc21a43e86b81f7a954d0a03513e7b675f9108e0 Mon Sep 17 00:00:00 2001 From: Clara Ribeiro Date: Sun, 19 Jan 2025 10:33:17 -0300 Subject: [PATCH 3/5] fix: lint --- src/Components/SideBar/index.jsx | 3 +-- src/Context/auth.jsx | 2 +- src/Pages/Protected/Benefit/Benefits/index.jsx | 4 ++-- src/Pages/Protected/Benefit/BenefitsCreate/index.jsx | 4 ++-- src/Pages/Protected/Benefit/BenefitsList/index.jsx | 4 ++-- src/Pages/Protected/Benefit/BenefitsValue/index.jsx | 1 + src/Pages/Protected/Carteirinha/index.jsx | 1 + src/Pages/Protected/Finance/BankAccountCreate/index.jsx | 1 + src/Pages/Protected/Finance/BankAccountList/index.jsx | 3 +-- src/Pages/Protected/Finance/BankAccountUpdate/index.jsx | 4 ++-- .../Protected/FinancialMovements/FinancialList/index.jsx | 4 ++-- .../FinancialMovements/FinancialUpdate/index.jsx | 3 +-- src/Pages/Protected/Organ/OrganUpdate/index.jsx | 4 ++-- src/Pages/Protected/Permissions/permissionsHandler.jsx | 1 + src/Pages/Protected/Roles/RolesListPage/index.jsx | 8 ++++---- src/Pages/Protected/Roles/RolesUpdatePage/index.jsx | 1 + src/Pages/Protected/Supplier/ListSupplier/index.jsx | 3 +-- src/Pages/Protected/Supplier/UpdateSupplier/index.jsx | 4 ++-- src/Pages/Protected/Users/userHubPage/index.jsx | 4 +--- src/Pages/Protected/Users/userUpdatePage/index.jsx | 4 ++-- src/Routes/permissionProtect.jsx | 1 + src/Utils/permission.jsx | 1 + 22 files changed, 33 insertions(+), 32 deletions(-) diff --git a/src/Components/SideBar/index.jsx b/src/Components/SideBar/index.jsx index 04e20a6a..c8dc520a 100644 --- a/src/Components/SideBar/index.jsx +++ b/src/Components/SideBar/index.jsx @@ -10,7 +10,7 @@ import { AiOutlineUser } from "react-icons/ai"; import { RiLogoutCircleRLine } from "react-icons/ri"; import { useNavigate } from "react-router-dom"; import AuthContext, { useAuth } from "../../Context/auth"; -import { usePermissions, checkModule, checkAction } from "../../Utils/permission"; +import { checkAction } from "../../Utils/permission"; import { getRoleById } from "../../Services/RoleService/roleService"; export default function SideBar() { @@ -19,7 +19,6 @@ export default function SideBar() { const navigate = useNavigate(); const context = useContext(AuthContext); const { user } = useAuth(); - const permissions = usePermissions(); const [role, setRole] = useState(""); useEffect(() => { }, [navigate]); diff --git a/src/Context/auth.jsx b/src/Context/auth.jsx index e8fbe31d..c23ff2fe 100644 --- a/src/Context/auth.jsx +++ b/src/Context/auth.jsx @@ -10,7 +10,7 @@ export const AuthProvider = ({ children }) => { useEffect(() => { const storagedUser = localStorage.getItem("@App:user"); const storagedToken = localStorage.getItem("@App:token"); - const storagedPermissions = localStorage.getItem("@App:permissions"); + // const storagedPermissions = localStorage.getItem("@App:permissions"); if (storagedToken && storagedUser) { setUser(JSON.parse(storagedUser)); diff --git a/src/Pages/Protected/Benefit/Benefits/index.jsx b/src/Pages/Protected/Benefit/Benefits/index.jsx index 7743faf3..4cd221ff 100644 --- a/src/Pages/Protected/Benefit/Benefits/index.jsx +++ b/src/Pages/Protected/Benefit/Benefits/index.jsx @@ -4,12 +4,12 @@ import SecondaryButton from "../../../../Components/SecondaryButton"; import sindpol_logo from "../../../../assets/sindpol-logo.png"; import sentinela_logo from "../../../../assets/sentinela-logo.png"; import "./index.css"; -import { checkAction, usePermissions } from "../../../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; const Benefits = () => { const navigate = useNavigate(); const { user } = useAuth(); - const permissions = usePermissions(); + // const permissions = usePermissions(); const handleBenefitsList = () => { navigate("/beneficios/lista"); diff --git a/src/Pages/Protected/Benefit/BenefitsCreate/index.jsx b/src/Pages/Protected/Benefit/BenefitsCreate/index.jsx index bd5982f1..1f6be8bf 100644 --- a/src/Pages/Protected/Benefit/BenefitsCreate/index.jsx +++ b/src/Pages/Protected/Benefit/BenefitsCreate/index.jsx @@ -17,7 +17,7 @@ import { isValidCelular, isValidSite, } from "../../../../Utils/validators"; -import { checkAction, usePermissions } from "../../../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; export default function BenefitsCreate() { const navigate = useNavigate(); @@ -45,7 +45,7 @@ export default function BenefitsCreate() { const [isChecked, setIsChecked] = useState(false); const [showModal, setShowModal] = useState(false); const [openError, setOpenError] = useState(false); - const permissions = usePermissions(); + // const permissions = usePermissions(); const tipoPessoaList = ["Jurídica", "Física"]; const categoriaList = [ diff --git a/src/Pages/Protected/Benefit/BenefitsList/index.jsx b/src/Pages/Protected/Benefit/BenefitsList/index.jsx index 2f4bdab2..ea41f627 100644 --- a/src/Pages/Protected/Benefit/BenefitsList/index.jsx +++ b/src/Pages/Protected/Benefit/BenefitsList/index.jsx @@ -9,13 +9,13 @@ import ListItemText from "@mui/material/ListItemText"; import Divider from "@mui/material/Divider"; import "./index.css"; import { getBenefitsForm } from "../../../../Services/benefitsService"; -import { checkAction, usePermissions } from "../../../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; export default function BenefitsList() { const [search, setSearch] = useState(""); const [benefits, setBenefits] = useState([]); const navigate = useNavigate(); - const permissions = usePermissions(); + // const permissions = usePermissions(); // const canCreate = checkAction( "beneficios_criar"); const handleSubmit = () => { diff --git a/src/Pages/Protected/Benefit/BenefitsValue/index.jsx b/src/Pages/Protected/Benefit/BenefitsValue/index.jsx index de0f6d00..2af3bf09 100644 --- a/src/Pages/Protected/Benefit/BenefitsValue/index.jsx +++ b/src/Pages/Protected/Benefit/BenefitsValue/index.jsx @@ -1,5 +1,6 @@ import { useState, useEffect } from "react"; import { getBenefitsForm } from "../../../../Services/benefitsService"; +import { checkAction } from "../../Utils/permission"; import { FaWhatsapp } from "react-icons/fa"; import List from "@mui/material/List"; diff --git a/src/Pages/Protected/Carteirinha/index.jsx b/src/Pages/Protected/Carteirinha/index.jsx index 595774bb..da2e83d2 100644 --- a/src/Pages/Protected/Carteirinha/index.jsx +++ b/src/Pages/Protected/Carteirinha/index.jsx @@ -1,6 +1,7 @@ import { useRef, useState, useEffect } from "react"; import QRCode from "react-qr-code"; import "./index.css"; +import { checkAction } from "../../Utils/permission"; import { jsPDF } from "jspdf"; import html2canvas from "html2canvas"; diff --git a/src/Pages/Protected/Finance/BankAccountCreate/index.jsx b/src/Pages/Protected/Finance/BankAccountCreate/index.jsx index 31455350..14c519e0 100644 --- a/src/Pages/Protected/Finance/BankAccountCreate/index.jsx +++ b/src/Pages/Protected/Finance/BankAccountCreate/index.jsx @@ -9,6 +9,7 @@ import { Snackbar } from "@mui/material"; import Alert from "@mui/material/Alert"; import { createBankAccount } from "../../../../Services/bankAccountService"; import Modal from "../../../../Components/Modal"; +import { checkAction } from "../../Utils/permission"; const BankAccount = () => { const [name, setName] = useState(""); diff --git a/src/Pages/Protected/Finance/BankAccountList/index.jsx b/src/Pages/Protected/Finance/BankAccountList/index.jsx index 595b7aa8..41917a50 100644 --- a/src/Pages/Protected/Finance/BankAccountList/index.jsx +++ b/src/Pages/Protected/Finance/BankAccountList/index.jsx @@ -10,14 +10,13 @@ import ListItemButton from "@mui/material/ListItemButton"; import ListItemText from "@mui/material/ListItemText"; import FieldText from "../../../../Components/FieldText"; import { getAll } from "../../../../../src/Services/bankAccountService"; -import { checkAction, usePermissions } from "../../../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; export default function ListBankAccount() { const [busca, setBusca] = useState(""); const navigate = useNavigate(); const { user } = useAuth(); const [bankAccounts, setBankAccounts] = useState([]); - const permissions = usePermissions(); const canCreate = checkAction( "create"); useEffect(() => { diff --git a/src/Pages/Protected/Finance/BankAccountUpdate/index.jsx b/src/Pages/Protected/Finance/BankAccountUpdate/index.jsx index e4f0b209..6698203f 100644 --- a/src/Pages/Protected/Finance/BankAccountUpdate/index.jsx +++ b/src/Pages/Protected/Finance/BankAccountUpdate/index.jsx @@ -14,7 +14,7 @@ import { updateBankAccount, } from "../../../../Services/bankAccountService"; import Modal from "../../../../Components/Modal"; -import { checkAction, usePermissions } from "../../../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; const BankAccountId = () => { const [name, setName] = useState(""); @@ -26,7 +26,7 @@ const BankAccountId = () => { const [status, setStatus] = useState(""); const [agency, setAgency] = useState(""); const [openError, setOpenError] = useState(false); - const permissions = usePermissions(); + // const permissions = usePermissions(); const canUpdate = checkAction("update"); const canDelete = checkAction("delete"); diff --git a/src/Pages/Protected/FinancialMovements/FinancialList/index.jsx b/src/Pages/Protected/FinancialMovements/FinancialList/index.jsx index b7837b59..9193b2ae 100644 --- a/src/Pages/Protected/FinancialMovements/FinancialList/index.jsx +++ b/src/Pages/Protected/FinancialMovements/FinancialList/index.jsx @@ -10,7 +10,7 @@ import ListItemText from "@mui/material/ListItemText"; import DataSelect from "../../../../Components/DataSelect"; import FieldText from "../../../../Components/FieldText"; import { APIBank } from "../../../../Services/BaseService"; -import { checkAction, usePermissions } from "../../../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; export default function FinancialList() { const [movements, setMovements] = useState([]); @@ -18,7 +18,7 @@ export default function FinancialList() { const navigate = useNavigate(); const [dataInicio, setDataInicio] = useState(null); const [dataFinal, setDataFinal] = useState(null); - const permissions = usePermissions(); + // const permissions = usePermissions(); const canCreate = checkAction( "create"); const storagedUser = JSON.parse(localStorage.getItem("@App:user")); diff --git a/src/Pages/Protected/FinancialMovements/FinancialUpdate/index.jsx b/src/Pages/Protected/FinancialMovements/FinancialUpdate/index.jsx index 81e3a182..ab53bef5 100644 --- a/src/Pages/Protected/FinancialMovements/FinancialUpdate/index.jsx +++ b/src/Pages/Protected/FinancialMovements/FinancialUpdate/index.jsx @@ -16,7 +16,7 @@ import { getUsers } from "../../../../Services/userService"; import { getSupplierForm } from "../../../../Services/supplierService"; import dayjs from "dayjs"; import { handleCpfCnpjInput } from "../../../../Utils/validators"; -import { checkAction, usePermissions } from "../../../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; export default function FinancialUpdate() { const [contaOrigem, setContaOrigem] = useState(""); @@ -39,7 +39,6 @@ export default function FinancialUpdate() { const [nomesOrigem, setNomesOrigem] = useState([]); const [nomesDestino, setNomesDestino] = useState([]); const maxDescricaoLength = 130; - const permissions = usePermissions(); const canUpdate = checkAction( "update"); const canDelete = checkAction( "delete"); diff --git a/src/Pages/Protected/Organ/OrganUpdate/index.jsx b/src/Pages/Protected/Organ/OrganUpdate/index.jsx index caffc11b..78373a00 100644 --- a/src/Pages/Protected/Organ/OrganUpdate/index.jsx +++ b/src/Pages/Protected/Organ/OrganUpdate/index.jsx @@ -7,7 +7,7 @@ import "./index.css"; import { Snackbar } from "@mui/material"; import Alert from "@mui/material/Alert"; import Modal from "../../../../Components/Modal"; -import { checkAction, usePermissions } from "../../../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; import { getOrganById, deleteOrganById, @@ -22,7 +22,7 @@ export const OrganId = () => { const { state } = useLocation(); const organsId = state?.organsId; const navigate = useNavigate(); - const permissions = usePermissions(); + // const permissions = usePermissions(); const canUpdate = checkAction( "orgaos_editar"); const canDelete = checkAction( "orgaos_deletar"); diff --git a/src/Pages/Protected/Permissions/permissionsHandler.jsx b/src/Pages/Protected/Permissions/permissionsHandler.jsx index 7ed774fb..a51f21ad 100644 --- a/src/Pages/Protected/Permissions/permissionsHandler.jsx +++ b/src/Pages/Protected/Permissions/permissionsHandler.jsx @@ -1,3 +1,4 @@ +/* eslint-disable no-unused-vars */ import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { Box, Button, TextField, Typography, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, IconButton } from '@mui/material'; diff --git a/src/Pages/Protected/Roles/RolesListPage/index.jsx b/src/Pages/Protected/Roles/RolesListPage/index.jsx index 3b4ab0f4..59795748 100644 --- a/src/Pages/Protected/Roles/RolesListPage/index.jsx +++ b/src/Pages/Protected/Roles/RolesListPage/index.jsx @@ -10,20 +10,20 @@ import Divider from "@mui/material/Divider"; import ListItemText from "@mui/material/ListItemText"; import FieldText from "../../../../Components/FieldText"; import { APIUsers } from "../../../../Services/BaseService"; -import { checkAction, usePermissions } from "../../../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; import { getToken } from "../../../../Services/Functions/loader"; export default function RolesListPage() { const [roles, setRoles] = useState([]); const [search, setSearch] = useState(""); - const permissions = usePermissions(); + // const permissions = usePermissions(); const navigate = useNavigate(); useEffect(() => { const fetchRoleForm = async () => { try { - const storagedUserString = localStorage.getItem("@App:user"); - const storagedUser = JSON.parse(storagedUserString); + // const storagedUserString = localStorage.getItem("@App:user"); + // const storagedUser = JSON.parse(storagedUserString); const response = await APIUsers.get("role", { diff --git a/src/Pages/Protected/Roles/RolesUpdatePage/index.jsx b/src/Pages/Protected/Roles/RolesUpdatePage/index.jsx index 829709fb..6a1a5b0e 100644 --- a/src/Pages/Protected/Roles/RolesUpdatePage/index.jsx +++ b/src/Pages/Protected/Roles/RolesUpdatePage/index.jsx @@ -1,3 +1,4 @@ +/* eslint-disable no-unused-vars */ import { useState, useEffect } from "react"; import "../RolesCreatePage/index.css"; import FieldText from "../../../../Components/FieldText"; diff --git a/src/Pages/Protected/Supplier/ListSupplier/index.jsx b/src/Pages/Protected/Supplier/ListSupplier/index.jsx index 5d53aefe..398a17dc 100644 --- a/src/Pages/Protected/Supplier/ListSupplier/index.jsx +++ b/src/Pages/Protected/Supplier/ListSupplier/index.jsx @@ -9,13 +9,12 @@ import ListItemText from "@mui/material/ListItemText"; import PrimaryButton from "../../../../Components/PrimaryButton"; import FieldText from "../../../../Components/FieldText"; import { getSupplierForm } from "../../../../Services/supplierService"; -import { checkAction, usePermissions } from "../../../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; export default function ListSupplier() { const [suppliers, setSuppliers] = useState([]); const [search, setSearch] = useState(""); const navigate = useNavigate(); - const permissions = usePermissions(); const canCreate = checkAction( "create"); useEffect(() => { const fetchSupplierForm = async () => { diff --git a/src/Pages/Protected/Supplier/UpdateSupplier/index.jsx b/src/Pages/Protected/Supplier/UpdateSupplier/index.jsx index cfa50e67..b142b5c8 100644 --- a/src/Pages/Protected/Supplier/UpdateSupplier/index.jsx +++ b/src/Pages/Protected/Supplier/UpdateSupplier/index.jsx @@ -13,10 +13,10 @@ import { useLocation, useNavigate } from "react-router-dom"; import Modal from "../../../../Components/Modal"; import { Alert, Snackbar } from "@mui/material"; import { isValidEmail } from "../../../../Utils/validators"; -import { checkAction, usePermissions } from "../../../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; export default function UpdateSupplier() { - const permissions = usePermissions(); + // const permissions = usePermissions(); const canUpdate = checkAction( "update"); const canDelete = checkAction( "delete"); const [nome, setNome] = useState(""); diff --git a/src/Pages/Protected/Users/userHubPage/index.jsx b/src/Pages/Protected/Users/userHubPage/index.jsx index cd7e4c17..d9032ef5 100644 --- a/src/Pages/Protected/Users/userHubPage/index.jsx +++ b/src/Pages/Protected/Users/userHubPage/index.jsx @@ -5,12 +5,10 @@ import SecondaryButton from "../../../../Components/SecondaryButton"; import sindpol_logo from "../../../../assets/sindpol-logo.png"; import sentinela_logo from "../../../../assets/sentinela-logo.png"; import "./index.css"; -import { usePermissions, checkAction } from "../../../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; export default function UserHubPage() { const navigate = useNavigate(); - const permissions = usePermissions(); - const canAprove = checkAction( "create"); const handleListaClick = () => { navigate("/usuarios"); diff --git a/src/Pages/Protected/Users/userUpdatePage/index.jsx b/src/Pages/Protected/Users/userUpdatePage/index.jsx index 637d9f1d..2ff69e88 100644 --- a/src/Pages/Protected/Users/userUpdatePage/index.jsx +++ b/src/Pages/Protected/Users/userUpdatePage/index.jsx @@ -12,7 +12,7 @@ import { getUserById, patchUserById, } from "../../../../Services/userService"; -import { checkAction, usePermissions } from "../../../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; import "./index.css"; import { isValidCelular, @@ -21,7 +21,7 @@ import { } from "../../../../Utils/validators"; export default function UserUpdatePage() { - const permissions = usePermissions(); + // const permissions = usePermissions(); const { state } = useLocation(); const navigate = useNavigate(); const userId = state?.userId; diff --git a/src/Routes/permissionProtect.jsx b/src/Routes/permissionProtect.jsx index 31d5c9ee..d0d229bf 100644 --- a/src/Routes/permissionProtect.jsx +++ b/src/Routes/permissionProtect.jsx @@ -1,3 +1,4 @@ +/* eslint-disable no-unreachable */ import { useContext, useState, useEffect } from "react"; import AuthContext from "../Context/auth"; import PropTypes from "prop-types"; diff --git a/src/Utils/permission.jsx b/src/Utils/permission.jsx index 1f2d26dc..0386b1d9 100644 --- a/src/Utils/permission.jsx +++ b/src/Utils/permission.jsx @@ -1,3 +1,4 @@ +/* eslint-disable no-unreachable */ // src/hooks/usePermissions.js import { useContext, useState, useEffect } from "react"; From 946a17492d40caad8694a0df41e2870360c97398 Mon Sep 17 00:00:00 2001 From: Clara Ribeiro Date: Sun, 19 Jan 2025 10:34:47 -0300 Subject: [PATCH 4/5] fix: prettier --- src/Components/SideBar/index.jsx | 45 ++- src/Context/auth.jsx | 5 +- .../Protected/Benefit/Benefits/index.jsx | 4 +- .../Benefit/BenefitsCreate/index.jsx | 317 ++++++++------- .../Protected/Benefit/BenefitsList/index.jsx | 2 +- .../Benefit/BenefitsUpdate/index.jsx | 368 +++++++++--------- .../Protected/Benefit/BenefitsValue/index.jsx | 121 +++--- src/Pages/Protected/Carteirinha/index.jsx | 212 +++++----- .../Finance/BankAccountCreate/index.jsx | 171 ++++---- .../Finance/BankAccountList/index.jsx | 89 +++-- .../Finance/BankAccountUpdate/index.jsx | 247 ++++++------ .../Finance/FinanceHubPage/index.jsx | 17 +- .../FinancialList/index.jsx | 2 +- .../FinancialUpdate/index.jsx | 4 +- src/Pages/Protected/Organ/ListOrgan/index.jsx | 2 +- .../Protected/Organ/OrganUpdate/index.jsx | 4 +- .../Permissions/permissionsHandler.jsx | 122 +++--- .../Protected/Roles/RolesListPage/index.jsx | 17 +- .../Protected/Roles/RolesUpdatePage/index.css | 1 - .../Protected/Roles/RolesUpdatePage/index.jsx | 33 +- .../Protected/Supplier/ListSupplier/index.jsx | 2 +- .../Supplier/UpdateSupplier/index.jsx | 4 +- .../Protected/Users/userHubPage/index.jsx | 65 ++-- .../Protected/Users/userUpdatePage/index.jsx | 4 +- src/Routes/permissionProtect.jsx | 2 +- src/Routes/protectedRoutes.jsx | 27 +- src/Services/BaseService/index.js | 1 - .../Permissions/permissionsService.js | 15 +- src/Services/RoleService/roleService.js | 19 +- src/Services/organService.js | 27 +- src/Utils/permission.jsx | 6 +- src/Utils/permissions.test.jsx | 14 +- 32 files changed, 996 insertions(+), 973 deletions(-) diff --git a/src/Components/SideBar/index.jsx b/src/Components/SideBar/index.jsx index c8dc520a..48974d46 100644 --- a/src/Components/SideBar/index.jsx +++ b/src/Components/SideBar/index.jsx @@ -21,7 +21,7 @@ export default function SideBar() { const { user } = useAuth(); const [role, setRole] = useState(""); - useEffect(() => { }, [navigate]); + useEffect(() => {}, [navigate]); const handleItemClick = async (user) => { if (user) { @@ -42,7 +42,6 @@ export default function SideBar() { } }; - return ( <>
@@ -116,7 +115,7 @@ export default function SideBar() { setIsSideBarOpen(false); }} /> - {(checkAction("filiados_cadastrar") && + {checkAction("filiados_cadastrar") && ( )} - {(checkAction("filiado_visualizar_carteirinha") && -
diff --git a/src/Context/auth.jsx b/src/Context/auth.jsx index c23ff2fe..16d9b229 100644 --- a/src/Context/auth.jsx +++ b/src/Context/auth.jsx @@ -23,7 +23,10 @@ export const AuthProvider = ({ children }) => { setUser(response.data); localStorage.setItem("@App:user", JSON.stringify(response.data.user)); localStorage.setItem("@App:token", JSON.stringify(response.data.token)); - localStorage.setItem("@App:permissions", JSON.stringify(response.data.permissions)); + localStorage.setItem( + "@App:permissions", + JSON.stringify(response.data.permissions) + ); setFlag(!flag); return false; } catch (err) { diff --git a/src/Pages/Protected/Benefit/Benefits/index.jsx b/src/Pages/Protected/Benefit/Benefits/index.jsx index 4cd221ff..95a397d4 100644 --- a/src/Pages/Protected/Benefit/Benefits/index.jsx +++ b/src/Pages/Protected/Benefit/Benefits/index.jsx @@ -31,13 +31,13 @@ const Benefits = () => { alt="Sentinela Logo" />
- {checkAction( "beneficios_criar") && ( + {checkAction("beneficios_criar") && ( )} - { checkAction( "beneficios_visualizar") && ( + {checkAction("beneficios_visualizar") && ( -
-

Cadastro de benefícios

-

Dados do benefício

-
- setNome(e.target.value)} - required - /> - - setRazaoSocial(e.target.value)} - required - /> -
- - setDescricao(e.target.value)} - /> - -
- - - setCpfCnpj(mascaraCpfCnpj(e.target.value))} - /> - - setAns(e.target.value)} - /> - - - - - - setDataCadastro(newValue)} - /> - - - - - - + checkAction("beneficios_criar") && ( +
+
+

Cadastro de benefícios

+

Dados do benefício

+
+ setNome(e.target.value)} + required + /> + + setRazaoSocial(e.target.value)} + required + /> +
setSite(e.target.value)} + label="Descrição" + value={descricao} + onChange={(e) => setDescricao(e.target.value)} /> - setEmail(e.target.value)} +
+ + + setCpfCnpj(mascaraCpfCnpj(e.target.value))} + /> + + setAns(e.target.value)} + /> + + + + + + setDataCadastro(newValue)} + /> + + + + + + + + setSite(e.target.value)} + /> + + setEmail(e.target.value)} + /> + + + setTelefCelular(mascaraTelefCelular(e.target.value)) + } + /> +
+ +

Dados do contrato de benefício

+ +
+ setDataAssinatura(newValue)} + /> + + setDataInicio(newValue)} + /> + + + + setDataFinal(newValue)} + /> +
+ + setContratoSit(e.target.value)} + checked={isChecked} + onCheckboxChange={(e) => setIsChecked(e.target.checked)} + disabled={true} /> - - setTelefCelular(mascaraTelefCelular(e.target.value)) - } - /> +
+ +
+ + setOpenError(false)} + > + setOpenError(false)} severity="error"> + {openError} + + + + + +
- -

Dados do contrato de benefício

- -
- setDataAssinatura(newValue)} - /> - - setDataInicio(newValue)} - /> - - - - setDataFinal(newValue)} - /> -
- - setContratoSit(e.target.value)} - checked={isChecked} - onCheckboxChange={(e) => setIsChecked(e.target.checked)} - disabled={true} - /> - -
- -
- - setOpenError(false)} - > - setOpenError(false)} severity="error"> - {openError} - - - - - -
-
) ); } diff --git a/src/Pages/Protected/Benefit/BenefitsList/index.jsx b/src/Pages/Protected/Benefit/BenefitsList/index.jsx index ea41f627..56346c08 100644 --- a/src/Pages/Protected/Benefit/BenefitsList/index.jsx +++ b/src/Pages/Protected/Benefit/BenefitsList/index.jsx @@ -46,7 +46,7 @@ export default function BenefitsList() {

Lista de benefícios

- {checkAction( "beneficios_criar") && ( + {checkAction("beneficios_criar") && ( )}
diff --git a/src/Pages/Protected/Benefit/BenefitsUpdate/index.jsx b/src/Pages/Protected/Benefit/BenefitsUpdate/index.jsx index f84946e5..6d1a6831 100644 --- a/src/Pages/Protected/Benefit/BenefitsUpdate/index.jsx +++ b/src/Pages/Protected/Benefit/BenefitsUpdate/index.jsx @@ -55,8 +55,8 @@ export default function BenefitsUpdate() { const [showDeletedModal, setShowDeletedModal] = useState(false); const [openError, setOpenError] = useState(false); const permissions = usePermissions(); - const canUpdate = checkAction(permissions,"beneficios_editar"); - const canDelete = checkAction( "beneficios_deletar"); + const canUpdate = checkAction(permissions, "beneficios_editar"); + const canDelete = checkAction("beneficios_deletar"); const tipoPessoaList = ["Jurídica", "Física"]; const categoriaList = [ @@ -248,215 +248,213 @@ export default function BenefitsUpdate() { }; return ( - - checkAction( "beneficios_visualizar") && ( -
- -
-

Visualização de benefícios

- -

Dados do benefício

+ checkAction("beneficios_visualizar") && ( +
+
+

Visualização de benefícios

+ +

Dados do benefício

+ +
+ setNome(e.target.value)} + required + /> -
- setNome(e.target.value)} - required - /> + setRazaoSocial(e.target.value)} + disabled={true} + /> +
setRazaoSocial(e.target.value)} - disabled={true} + label="Descrição" + value={descricao} + onChange={(e) => setDescricao(e.target.value)} /> -
- setDescricao(e.target.value)} - /> - -
- +
+ - setCpfCnpj(mascaraCpfCnpj(e.target.value))} - /> + setCpfCnpj(mascaraCpfCnpj(e.target.value))} + /> - setAns(e.target.value)} - /> + setAns(e.target.value)} + /> - + - + - setDataCadastro(newValue)} - /> + setDataCadastro(newValue)} + /> - + - + - + - setSite(e.target.value)} - /> + setSite(e.target.value)} + /> - setEmail(e.target.value)} - /> + setEmail(e.target.value)} + /> - - setTelefCelular(mascaraTelefCelular(e.target.value)) - } - /> -
+ + setTelefCelular(mascaraTelefCelular(e.target.value)) + } + /> +
-

Dados do contrato de benefício

+

Dados do contrato de benefício

-
- setDataAssinatura(newValue)} - /> +
+ setDataAssinatura(newValue)} + /> - setDataInicio(newValue)} - /> + setDataInicio(newValue)} + /> - + - setDataFinal(newValue)} + setDataFinal(newValue)} + /> +
+ + setContratoSit(e.target.value)} + checked={isChecked} + onCheckboxChange={(e) => setIsChecked(e.target.checked)} + disabled={true} /> -
- setContratoSit(e.target.value)} - checked={isChecked} - onCheckboxChange={(e) => setIsChecked(e.target.checked)} - disabled={true} - /> - -
- {canDelete && ( - - )} - - {canUpdate && ( - handleUpdateBenefitsButton()} +
+ {canDelete && ( + + )} + + {canUpdate && ( + handleUpdateBenefitsButton()} + /> + )} +
+ + setOpenError(false)} + > + setOpenError("")} severity="error"> + {openError} + + + + + handleSaveModal()} + /> + + + + handleDeleteBenefitsButton()} + width="338px" + /> + handleDeleteCloseDialog()} + width="338px" /> - )} + + + + handleDeletedCloseDialog()} + width="338px" + /> +
- - setOpenError(false)} - > - setOpenError("")} severity="error"> - {openError} - - - - - handleSaveModal()} - /> - - - - handleDeleteBenefitsButton()} - width="338px" - /> - handleDeleteCloseDialog()} - width="338px" - /> - - - - handleDeletedCloseDialog()} - width="338px" - /> -
-
) ); } diff --git a/src/Pages/Protected/Benefit/BenefitsValue/index.jsx b/src/Pages/Protected/Benefit/BenefitsValue/index.jsx index 2af3bf09..74782699 100644 --- a/src/Pages/Protected/Benefit/BenefitsValue/index.jsx +++ b/src/Pages/Protected/Benefit/BenefitsValue/index.jsx @@ -29,73 +29,72 @@ export default function BenefitsValue() { }, []); return ( - checkAction( "beneficios_visualizar") && ( -
- -
-
-

Valores dos benefícios

-

Benefícios disponíveis

-
-
- - {benefits?.map( - (benefit, index) => ( - console.log(benefit), - ( -
- - - handleExpand(benefit._id)} - /> -
+ checkAction("beneficios_visualizar") && ( +
+
+
+

Valores dos benefícios

+

Benefícios disponíveis

+
+
+ + {benefits?.map( + (benefit, index) => ( + console.log(benefit), + ( +
+ + -
- - - {expandedBenefit === benefit._id && ( -
- - - - -
- )} + primary="Mais Detalhes" + onClick={() => handleExpand(benefit._id)} + /> +
+ +
+ + + {expandedBenefit === benefit._id && ( +
+ + + + +
+ )} - -
+ +
+ ) ) - ) - )} - + )} + +
-
-
+ ) ); } diff --git a/src/Pages/Protected/Carteirinha/index.jsx b/src/Pages/Protected/Carteirinha/index.jsx index da2e83d2..85d02ac1 100644 --- a/src/Pages/Protected/Carteirinha/index.jsx +++ b/src/Pages/Protected/Carteirinha/index.jsx @@ -21,13 +21,11 @@ const Carteirinha = () => { useEffect(() => { const fetchMembership = async () => { try { - const response = await fetch("http://localhost:3001/membership", - { - headers: { - Authorization: `Bearer ${getToken()}`, - }, - } - ); + const response = await fetch("http://localhost:3001/membership", { + headers: { + Authorization: `Bearer ${getToken()}`, + }, + }); const data = await response.json(); setMembershipData(data[0]); console.log("alohaa", data); @@ -82,117 +80,119 @@ const Carteirinha = () => { const { name, birthDate, cpf, expeditionDate, hiringDate } = membershipData; return ( - checkAction( "beneficios_criar") && ( -
- -
-
-

SINDPOL-DF

-

SINDICATO DOS POLICIAIS PENAIS DO DISTRITO FEDERAL

-
- - {/* Informações e Badge */} -
-
-
-
- TITULAR: -
-

-

- {name} -

+ checkAction("beneficios_criar") && ( +
+
+
+

SINDPOL-DF

+

SINDICATO DOS POLICIAIS PENAIS DO DISTRITO FEDERAL

+
+ + {/* Informações e Badge */} +
+
+
+
+ TITULAR: +
+

+

+ {name} +

+
-
-
-
- DATA DE NASCIMENTO: -
-

- -

- {new Date(birthDate).toLocaleDateString()} -

-
-
- DATA DE EXPEDIÇÃO: -
-

-

- {new Date(expeditionDate).toLocaleDateString()} -

-
-
-
-
- CPF: -
-

-

- {cpf} -

+
+
+ DATA DE NASCIMENTO: +
+

+ +

+ {new Date(birthDate).toLocaleDateString()} +

+
+
+ DATA DE EXPEDIÇÃO: +
+

+

+ {new Date(expeditionDate).toLocaleDateString()} +

+
-
- CONTRATAÇÃO: -
-

-

- {new Date(hiringDate).toLocaleDateString()} -

+
+
+ CPF: +
+

+

+ {cpf} +

+
+
+ CONTRATAÇÃO: +
+

+

+ {new Date(hiringDate).toLocaleDateString()} +

+
-
- {/* Badge Section */} -
- Sindicalizado Badge -

SINDICALIZADO

+ {/* Badge Section */} +
+ Sindicalizado Badge +

SINDICALIZADO

+
-
- {/* Segunda Parte da Carteirinha */} -
-
-

- Setor de Diversões Sul (SDS), Conjunto Baracat, Bloco F, 27, Salas - 313/315, Asa Sul, Brasília/DF, CEP 70392-900 -

-
-
-
- {" "} - {/* endereço que será passado no qrCode */} + {/* Segunda Parte da Carteirinha */} +
+
+

+ Setor de Diversões Sul (SDS), Conjunto Baracat, Bloco F, 27, Salas + 313/315, Asa Sul, Brasília/DF, CEP 70392-900 +

+
+
+
+ {" "} + {/* endereço que será passado no qrCode */} +
+

(61) 3321-1949

-

(61) 3321-1949

+ +
+

sindpol.org.br / contato@sindpol.org.br

+
+ + + + +
+ @sindpoldf +
+ Logo 1 + Logo 2 +
+
-
-

sindpol.org.br / contato@sindpol.org.br

-
- - - - -
- @sindpoldf -
- Logo 1 - Logo 2 -
-
+ {/* Botão */} +
- - {/* Botão */} - -
- ) + ) ); }; diff --git a/src/Pages/Protected/Finance/BankAccountCreate/index.jsx b/src/Pages/Protected/Finance/BankAccountCreate/index.jsx index 14c519e0..7e5dc511 100644 --- a/src/Pages/Protected/Finance/BankAccountCreate/index.jsx +++ b/src/Pages/Protected/Finance/BankAccountCreate/index.jsx @@ -102,93 +102,94 @@ const BankAccount = () => { }; return ( - checkAction( "contas_bancarias_criar") && ( -
-
-

Cadastro de Conta Bancária

-

Dados da Conta Bancária

-
- setName(e.target.value)} - /> - - setBank(e.target.value)} - /> - setAgency(agencia(e.target.value))} - /> - setAccountNumber(numeroConta(e.target.value))} - /> - setDv(digitverificator(e.target.value))} - /> - setPix(e.target.value)} - /> - setStatus(e.target.value)} - options={listStatus} - /> -
- -
- -
- - setOpenError(false)} - > - setOpenError(false)} severity="error"> - Certifique-se de que todos os campos obrigatórios estão preenchidos - - - setOpenErrorUnique(false)} - > - setOpenErrorUnique(false)} severity="error"> - Nome já cadastrado - - - - - navigate("/finance/list")} + checkAction("contas_bancarias_criar") && ( +
+
+

Cadastro de Conta Bancária

+

Dados da Conta Bancária

+
+ setName(e.target.value)} + /> + + setBank(e.target.value)} + /> + setAgency(agencia(e.target.value))} + /> + setAccountNumber(numeroConta(e.target.value))} + /> + setDv(digitverificator(e.target.value))} + /> + setPix(e.target.value)} + /> + setStatus(e.target.value)} + options={listStatus} + /> +
+ +
+ +
+ + setOpenError(false)} + > + setOpenError(false)} severity="error"> + Certifique-se de que todos os campos obrigatórios estão + preenchidos + + + setOpenErrorUnique(false)} + > + setOpenErrorUnique(false)} severity="error"> + Nome já cadastrado + + + + - + alertTitle="Cadastro concluído" + show={successCreate} + > + navigate("/finance/list")} + width="338px" + /> + +
-
) ); }; diff --git a/src/Pages/Protected/Finance/BankAccountList/index.jsx b/src/Pages/Protected/Finance/BankAccountList/index.jsx index 41917a50..dd32d2a0 100644 --- a/src/Pages/Protected/Finance/BankAccountList/index.jsx +++ b/src/Pages/Protected/Finance/BankAccountList/index.jsx @@ -17,7 +17,7 @@ export default function ListBankAccount() { const navigate = useNavigate(); const { user } = useAuth(); const [bankAccounts, setBankAccounts] = useState([]); - const canCreate = checkAction( "create"); + const canCreate = checkAction("create"); useEffect(() => { const fetchBankAccounts = async () => { @@ -45,54 +45,53 @@ export default function ListBankAccount() { ); return ( - checkAction( "contas_bancarias_visualizar") && ( - user && ( -
-
-
-

Lista de Contas Bancárias

- {canCreate && ( - - )} -
-
- setBusca(e.target.value)} + checkAction("contas_bancarias_visualizar") && + user && ( +
+
+
+

Lista de Contas Bancárias

+ {canCreate && ( + - - {filteredBankAccounts.map((bankAccount, index) => ( -
- - + )} +
+
+ setBusca(e.target.value)} + /> + + {filteredBankAccounts.map((bankAccount, index) => ( +
+ + (e.currentTarget.style.backgroundColor = "rgba(0, 0, 0, 0.1)") - } - onMouseLeave={(e) => - (e.currentTarget.style.backgroundColor = "transparent") - } - onClick={() => handleItemClick(bankAccount)} - > - - - - {index < filteredBankAccounts.length - 1 && } -
- ))} -
-
+ } + onMouseLeave={(e) => + (e.currentTarget.style.backgroundColor = "transparent") + } + onClick={() => handleItemClick(bankAccount)} + > + + + + {index < filteredBankAccounts.length - 1 && } +
+ ))} +
-
- ) +
+
) ); } diff --git a/src/Pages/Protected/Finance/BankAccountUpdate/index.jsx b/src/Pages/Protected/Finance/BankAccountUpdate/index.jsx index 6698203f..88825bd5 100644 --- a/src/Pages/Protected/Finance/BankAccountUpdate/index.jsx +++ b/src/Pages/Protected/Finance/BankAccountUpdate/index.jsx @@ -130,137 +130,136 @@ const BankAccountId = () => { } }; - return user ? ( - checkAction( "contas_bancarias_visualizar") && ( - -
-
-

Visualização de Conta Bancária

+ return user + ? checkAction("contas_bancarias_visualizar") && ( +
+
+

Visualização de Conta Bancária

-

Dados do benefício

+

Dados do benefício

-
- setName(e.target.value)} - /> - - setBank(e.target.value)} - /> - setAgency(agencia(e.target.value))} - /> - setAccountNumber(numeroConta(e.target.value))} - /> - setDv(digitverificator(e.target.value))} - /> - setPix(e.target.value)} - /> - setStatus(e.target.value)} - options={listStatus} - /> -
+
+ setName(e.target.value)} + /> + + setBank(e.target.value)} + /> + setAgency(agencia(e.target.value))} + /> + setAccountNumber(numeroConta(e.target.value))} + /> + setDv(digitverificator(e.target.value))} + /> + setPix(e.target.value)} + /> + setStatus(e.target.value)} + options={listStatus} + /> +
-
- {canDelete && ( - { - setOpenVerificationDelete(true); - }} - marginTop="1rem" - /> - )} - {canUpdate && ( - - )} -
-
+
+ {canDelete && ( + { + setOpenVerificationDelete(true); + }} + marginTop="1rem" + /> + )} + {canUpdate && ( + + )} +
+
- setOpenError(false)} - > - setOpenError(false)} severity="error"> - Certifique-se de que todos os campos obrigatórios estão preenchidos - - + setOpenError(false)} + > + setOpenError(false)} severity="error"> + Certifique-se de que todos os campos obrigatórios estão + preenchidos + + - - navigate("/finance/list")} - style={{ width: "250px", marginTop: "10px" }} - /> - + + navigate("/finance/list")} + style={{ width: "250px", marginTop: "10px" }} + /> + - - - setOpenVerificationDelete(false)} - style={{ width: "250px", marginTop: "10px" }} - /> - + + + setOpenVerificationDelete(false)} + style={{ width: "250px", marginTop: "10px" }} + /> + - - navigate("/finance/list")} - style={{ width: "250px", marginTop: "10px" }} - /> - -
- ) - ) : null; - + + navigate("/finance/list")} + style={{ width: "250px", marginTop: "10px" }} + /> + +
+ ) + : null; }; export default BankAccountId; diff --git a/src/Pages/Protected/Finance/FinanceHubPage/index.jsx b/src/Pages/Protected/Finance/FinanceHubPage/index.jsx index 692d06d3..f9754a2f 100644 --- a/src/Pages/Protected/Finance/FinanceHubPage/index.jsx +++ b/src/Pages/Protected/Finance/FinanceHubPage/index.jsx @@ -38,25 +38,34 @@ export default function Finance() { alt="Sentinela Logo" /> - {(checkAction("fornecedores_criar") || checkAction("fornecedores_editar") || checkAction("fornecedores_deletar") || checkAction("fornecedores_visualizar"))&& ( + {(checkAction("fornecedores_criar") || + checkAction("fornecedores_editar") || + checkAction("fornecedores_deletar") || + checkAction("fornecedores_visualizar")) && ( )} - {(checkAction("contas_bancarias_criar") || checkAction("contas_bancarias_editar") || checkAction("contas_bancarias_deletar") || checkAction("contas_bancarias_visualizar")) && ( + {(checkAction("contas_bancarias_criar") || + checkAction("contas_bancarias_editar") || + checkAction("contas_bancarias_deletar") || + checkAction("contas_bancarias_visualizar")) && ( )} - {(checkAction("movimentacao_financeira_criar") || checkAction("movimentacao_financeira_editar") || checkAction("movimentacao_financeira_deletar") || checkAction("movimentacao_financeira_visualizar")) && ( + {(checkAction("movimentacao_financeira_criar") || + checkAction("movimentacao_financeira_editar") || + checkAction("movimentacao_financeira_deletar") || + checkAction("movimentacao_financeira_visualizar")) && ( )} - {checkAction( "movimentacao_financeira_visualizar") && ( + {checkAction("movimentacao_financeira_visualizar") && ( { const getOrgansInfo = async () => { const response = await listOrgans(); diff --git a/src/Pages/Protected/Organ/OrganUpdate/index.jsx b/src/Pages/Protected/Organ/OrganUpdate/index.jsx index 78373a00..d0f47f6e 100644 --- a/src/Pages/Protected/Organ/OrganUpdate/index.jsx +++ b/src/Pages/Protected/Organ/OrganUpdate/index.jsx @@ -23,8 +23,8 @@ export const OrganId = () => { const organsId = state?.organsId; const navigate = useNavigate(); // const permissions = usePermissions(); - const canUpdate = checkAction( "orgaos_editar"); - const canDelete = checkAction( "orgaos_deletar"); + const canUpdate = checkAction("orgaos_editar"); + const canDelete = checkAction("orgaos_deletar"); const [openSave, setOpenSave] = useState(false); const [openDeleteOrgan, setOpenDeleteOrgan] = useState(false); diff --git a/src/Pages/Protected/Permissions/permissionsHandler.jsx b/src/Pages/Protected/Permissions/permissionsHandler.jsx index a51f21ad..346f64aa 100644 --- a/src/Pages/Protected/Permissions/permissionsHandler.jsx +++ b/src/Pages/Protected/Permissions/permissionsHandler.jsx @@ -1,24 +1,36 @@ /* eslint-disable no-unused-vars */ -import React, { useState, useEffect } from 'react'; -import axios from 'axios'; -import { Box, Button, TextField, Typography, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, IconButton } from '@mui/material'; -import { Delete, Edit, Search } from '@mui/icons-material'; +import React, { useState, useEffect } from "react"; +import axios from "axios"; +import { + Box, + Button, + TextField, + Typography, + Table, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Paper, + IconButton, +} from "@mui/material"; +import { Delete, Edit, Search } from "@mui/icons-material"; import { APIUsers } from "./../../../Services/BaseService/index"; import { getToken, getUser } from "./../../../Services/Functions/loader"; -import { checkAction } from '../../../Utils/permission'; - +import { checkAction } from "../../../Utils/permission"; const PermissionCRUD = () => { const [permissions, setPermissions] = useState([]); - const [form, setForm] = useState({ name: '' }); - const [searchQuery, setSearchQuery] = useState(''); + const [form, setForm] = useState({ name: "" }); + const [searchQuery, setSearchQuery] = useState(""); const [search, setSearch] = useState(""); const [editId, setEditId] = useState(null); - const canCreate = checkAction( "permissoes_criar"); - const canUpdate = checkAction( "permissoes_editar"); - const canDelete = checkAction( "permissoes_deletar"); - const canView = checkAction( "permissoes_visualizar"); + const canCreate = checkAction("permissoes_criar"); + const canUpdate = checkAction("permissoes_editar"); + const canDelete = checkAction("permissoes_deletar"); + const canView = checkAction("permissoes_visualizar"); useEffect(() => { fetchPermissions(); @@ -26,15 +38,14 @@ const PermissionCRUD = () => { const fetchPermissions = async () => { try { - const response = await APIUsers.get('permission', - { - headers: { - Authorization: `Bearer ${getToken()}`, - } - }); + const response = await APIUsers.get("permission", { + headers: { + Authorization: `Bearer ${getToken()}`, + }, + }); setPermissions(response.data); } catch (error) { - console.error('Error fetching permissions:', error); + console.error("Error fetching permissions:", error); } }; @@ -42,20 +53,19 @@ const PermissionCRUD = () => { e.preventDefault(); try { if (editId) { - await APIUsers.patch(`permission/patch/${editId}`, form, - { - headers: { - Authorization: `Bearer ${getToken()}`, - } - }); + await APIUsers.patch(`permission/patch/${editId}`, form, { + headers: { + Authorization: `Bearer ${getToken()}`, + }, + }); } else { - await APIUsers.post('permission/create/', form); + await APIUsers.post("permission/create/", form); } - setForm({ name: '' }); + setForm({ name: "" }); setEditId(null); fetchPermissions(); } catch (error) { - console.error('Error saving permission:', error); + console.error("Error saving permission:", error); } }; @@ -66,31 +76,31 @@ const PermissionCRUD = () => { const handleDelete = async (id) => { try { - await APIUsers.delete(`permission/delete/${id}`, - { - headers: { - Authorization: `Bearer ${getToken()}`, - } - }); + await APIUsers.delete(`permission/delete/${id}`, { + headers: { + Authorization: `Bearer ${getToken()}`, + }, + }); fetchPermissions(); } catch (error) { - console.error('Error deleting permission:', error); + console.error("Error deleting permission:", error); } }; const handleSearch = async () => { try { - const response = await APIUsers.get(`permissions/search`, + const response = await APIUsers.get( + `permissions/search`, { name: searchQuery }, { headers: { Authorization: `Bearer ${getToken()}`, - } + }, } ); setPermissions(response.data); } catch (error) { - console.error('Error searching permissions:', error); + console.error("Error searching permissions:", error); } }; @@ -104,10 +114,9 @@ const PermissionCRUD = () => { Permission Management {canCreate && ( - setForm({ ...form, name: e.target.value })} @@ -115,19 +124,30 @@ const PermissionCRUD = () => { fullWidth margin="normal" /> - )} - +
Name - {(canUpdate || canDelete) && ( - Actions - )} + {(canUpdate || canDelete) && Actions} @@ -136,12 +156,18 @@ const PermissionCRUD = () => { {permission.name} {canUpdate && ( - handleEdit(permission)}> + handleEdit(permission)} + > )} {canDelete && ( - handleDelete(permission._id)}> + handleDelete(permission._id)} + > )} diff --git a/src/Pages/Protected/Roles/RolesListPage/index.jsx b/src/Pages/Protected/Roles/RolesListPage/index.jsx index 59795748..dbfaf506 100644 --- a/src/Pages/Protected/Roles/RolesListPage/index.jsx +++ b/src/Pages/Protected/Roles/RolesListPage/index.jsx @@ -25,13 +25,11 @@ export default function RolesListPage() { // const storagedUserString = localStorage.getItem("@App:user"); // const storagedUser = JSON.parse(storagedUserString); - const response = await APIUsers.get("role", - { - headers: { - Authorization: `Bearer ${getToken()}`, - }, - } - ); + const response = await APIUsers.get("role", { + headers: { + Authorization: `Bearer ${getToken()}`, + }, + }); const data = response.data; if (Array.isArray(data)) { @@ -47,7 +45,7 @@ export default function RolesListPage() { fetchRoleForm(); }, []); - const hasPermission = checkAction( "perfis_criar"); + const hasPermission = checkAction("perfis_criar"); const handleSubmit = () => { navigate("/perfis/criar"); @@ -81,7 +79,7 @@ export default function RolesListPage() { /> - {checkAction( "perfis_visualizar") && ( + {checkAction("perfis_visualizar") && ( {filteredRoles.map((role, index) => (
@@ -109,7 +107,6 @@ export default function RolesListPage() { ))} )} -
); diff --git a/src/Pages/Protected/Roles/RolesUpdatePage/index.css b/src/Pages/Protected/Roles/RolesUpdatePage/index.css index 3d528bb7..52a6fc57 100644 --- a/src/Pages/Protected/Roles/RolesUpdatePage/index.css +++ b/src/Pages/Protected/Roles/RolesUpdatePage/index.css @@ -12,7 +12,6 @@ margin-bottom: 15px; } - .permissions-list { max-height: 300px; overflow-y: auto; diff --git a/src/Pages/Protected/Roles/RolesUpdatePage/index.jsx b/src/Pages/Protected/Roles/RolesUpdatePage/index.jsx index 6a1a5b0e..200ee75b 100644 --- a/src/Pages/Protected/Roles/RolesUpdatePage/index.jsx +++ b/src/Pages/Protected/Roles/RolesUpdatePage/index.jsx @@ -15,8 +15,8 @@ import { import { getAllPermissions, searchPermissionByName, -} from "../../../../Services/Permissions/permissionsService"; -import './index.css'; +} from "../../../../Services/Permissions/permissionsService"; +import "./index.css"; export default function RolesUpdatePage() { const [showSaveModal, setShowSaveModal] = useState(false); @@ -24,11 +24,11 @@ export default function RolesUpdatePage() { const [showSuccessModal, setShowSuccessModal] = useState(false); const [showSuccessDelModal, setShowSuccessDelModal] = useState(false); const [profileName, setProfileName] = useState(""); - + const [selectedPermissions, setSelectedPermissions] = useState([]); const [permissionsList, setPermissionsList] = useState([]); - const [searchQuery, setSearchQuery] = useState(""); - const [allPermissions, setAllPermissions] = useState([]); + const [searchQuery, setSearchQuery] = useState(""); + const [allPermissions, setAllPermissions] = useState([]); const navigate = useNavigate(); const location = useLocation(); @@ -66,7 +66,6 @@ export default function RolesUpdatePage() { const roleData = await getRoleById(roleId); setProfileName(roleData.name); - const rolePermissions = roleData.permissions.map((perm) => perm._id); setSelectedPermissions(rolePermissions); } catch (error) { @@ -88,8 +87,11 @@ export default function RolesUpdatePage() { })), }; - // await updateRole(roleId, updatedRole); - await assignPermissionsToRole(roleId, selectedPermissions.filter((item) => item !== undefined)); + // await updateRole(roleId, updatedRole); + await assignPermissionsToRole( + roleId, + selectedPermissions.filter((item) => item !== undefined) + ); setShowSuccessModal(true); } catch (error) { console.error("Erro ao atualizar o perfil:", error); @@ -123,10 +125,8 @@ export default function RolesUpdatePage() { setSelectedPermissions((prev) => { return prev.includes(permission) ? prev.filter((p) => p !== permission && p != undefined) - : [...prev, permission] - - } - ); + : [...prev, permission]; + }); }; return ( @@ -154,7 +154,7 @@ export default function RolesUpdatePage() { placeholder="Digite o nome da permissão" /> */} - + {/* Lista de permissões */}

Lista de Permissões

@@ -181,12 +181,7 @@ export default function RolesUpdatePage() { text="DELETAR" onClick={() => setShowDeleteModal(true)} /> - setShowSaveModal(true)} - /> - - + setShowSaveModal(true)} /> {/* Modais */} { const fetchSupplierForm = async () => { const response = await getSupplierForm(); diff --git a/src/Pages/Protected/Supplier/UpdateSupplier/index.jsx b/src/Pages/Protected/Supplier/UpdateSupplier/index.jsx index b142b5c8..d18566cb 100644 --- a/src/Pages/Protected/Supplier/UpdateSupplier/index.jsx +++ b/src/Pages/Protected/Supplier/UpdateSupplier/index.jsx @@ -17,8 +17,8 @@ import { checkAction } from "../../../../Utils/permission"; export default function UpdateSupplier() { // const permissions = usePermissions(); - const canUpdate = checkAction( "update"); - const canDelete = checkAction( "delete"); + const canUpdate = checkAction("update"); + const canDelete = checkAction("delete"); const [nome, setNome] = useState(""); const [tipoPessoa, setTipoPessoa] = useState(""); const [cpfCnpj, setCpfCnpj] = useState(""); diff --git a/src/Pages/Protected/Users/userHubPage/index.jsx b/src/Pages/Protected/Users/userHubPage/index.jsx index d9032ef5..5647f51e 100644 --- a/src/Pages/Protected/Users/userHubPage/index.jsx +++ b/src/Pages/Protected/Users/userHubPage/index.jsx @@ -35,38 +35,51 @@ export default function UserHubPage() { src={sentinela_logo} alt="Sentinela Logo" /> - {(checkAction("usuarios_visualizar") || checkAction("usuarios_editar")) && ( + {(checkAction("usuarios_visualizar") || + checkAction("usuarios_editar")) && ( navigate("filiacoes-pendentes/")} /> )} <> - {(checkAction("usuarios_criar") || checkAction("usuarios_visualizar") || checkAction("usuarios_editar") || checkAction("usuarios_deletar")) && ( - - )} - {((checkAction("perfis_criar") || checkAction("perfis_visualizar") || checkAction("perfis_editar") || checkAction("perfis_deletar")) && - - )} - {((checkAction("perfis_criar") || checkAction("perfis_visualizar") || checkAction("perfis_editar") || checkAction("perfis_deletar")) && - - )} - - {((checkAction("orgaos_criar") || checkAction("orgaos_visualizar") || checkAction("orgaos_editar") || checkAction("orgaos_deletar")) && - - )} + {(checkAction("usuarios_criar") || + checkAction("usuarios_visualizar") || + checkAction("usuarios_editar") || + checkAction("usuarios_deletar")) && ( + + )} + {(checkAction("perfis_criar") || + checkAction("perfis_visualizar") || + checkAction("perfis_editar") || + checkAction("perfis_deletar")) && ( + + )} + {(checkAction("perfis_criar") || + checkAction("perfis_visualizar") || + checkAction("perfis_editar") || + checkAction("perfis_deletar")) && ( + + )} + + {(checkAction("orgaos_criar") || + checkAction("orgaos_visualizar") || + checkAction("orgaos_editar") || + checkAction("orgaos_deletar")) && ( + + )}
diff --git a/src/Pages/Protected/Users/userUpdatePage/index.jsx b/src/Pages/Protected/Users/userUpdatePage/index.jsx index 2ff69e88..bdeb2063 100644 --- a/src/Pages/Protected/Users/userUpdatePage/index.jsx +++ b/src/Pages/Protected/Users/userUpdatePage/index.jsx @@ -38,8 +38,8 @@ export default function UserUpdatePage() { const [isEmailValid, setIsEmailValid] = useState(true); const [isCelularValid, setIsCelularValid] = useState(true); - const canDelete = checkAction( "usuarios_deletar"); - const canUpdate = checkAction( "usuarios_editar"); + const canDelete = checkAction("usuarios_deletar"); + const canUpdate = checkAction("usuarios_editar"); useEffect(() => { const loadRoles = async () => { diff --git a/src/Routes/permissionProtect.jsx b/src/Routes/permissionProtect.jsx index d0d229bf..b7238d27 100644 --- a/src/Routes/permissionProtect.jsx +++ b/src/Routes/permissionProtect.jsx @@ -34,7 +34,7 @@ const PermissionProtect = ({ element, moduleName, actions }) => { // Exibe um carregando enquanto as permissões estão sendo buscadas return
Loading...
; } - console.log(moduleName, 'chaama') + console.log(moduleName, "chaama"); return element; // Verifica se o usuário possui pelo menos uma das ações necessárias const hasPermission = actions.some((action) => diff --git a/src/Routes/protectedRoutes.jsx b/src/Routes/protectedRoutes.jsx index c54d81c6..8b546084 100644 --- a/src/Routes/protectedRoutes.jsx +++ b/src/Routes/protectedRoutes.jsx @@ -89,8 +89,7 @@ const ProtectedRoutes = () => { } moduleName="users" - actions={["create", "update", "read", "delete"] - } + actions={["create", "update", "read", "delete"]} /> } /> @@ -191,7 +190,7 @@ const ProtectedRoutes = () => { /> } /> - + { /> } /> - {(checkAction("filiado_visualizar_carteirinha") && - } - moduleName="users" - actions={["read", "create"]} - /> - } - /> + {checkAction("filiado_visualizar_carteirinha") && ( + } + moduleName="users" + actions={["read", "create"]} + /> + } + /> )} { if (!token) { throw new Error("No token found"); } - const response = await APIUsers.get("/permission", - { - headers: { - Authorization: `Bearer ${getToken()}`, - } - } - ); + const response = await APIUsers.get("/permission", { + headers: { + Authorization: `Bearer ${getToken()}`, + }, + }); return response.data; } catch (error) { console.error("Erro ao buscar permissões:", error.response?.data || error); @@ -42,7 +40,6 @@ export const getAllPermissions = async () => { } }; - // Get a permission by ID export const getPermissionById = async (id) => { try { @@ -121,5 +118,3 @@ export const searchPermissionByName = async (name) => { throw error; } }; - - diff --git a/src/Services/RoleService/roleService.js b/src/Services/RoleService/roleService.js index ae48ec99..18970aff 100644 --- a/src/Services/RoleService/roleService.js +++ b/src/Services/RoleService/roleService.js @@ -31,7 +31,6 @@ export const createRole = async (roleData) => { headers: { Authorization: `Bearer ${getToken()}`, }, - }); return response.data; } catch (error) { @@ -82,13 +81,17 @@ export const assignPermissionsToRole = async (roleId, permissions) => { throw new Error("No token found"); } - const response = await APIUsers.put(`/roles/${roleId}/permissions`, { - permissions, - }, { - headers: { - Authorization: `Bearer ${getToken()}`, + const response = await APIUsers.put( + `/roles/${roleId}/permissions`, + { + permissions, }, - }); + { + headers: { + Authorization: `Bearer ${getToken()}`, + }, + } + ); return response.data; } catch (error) { @@ -127,7 +130,6 @@ export const updateRole = async (id, roleData) => { headers: { Authorization: `Bearer ${getToken()}`, }, - }); return response.data; } catch (error) { @@ -166,7 +168,6 @@ export const deleteRole = async (id) => { headers: { Authorization: `Bearer ${getToken()}`, }, - }); return response.data; } catch (error) { diff --git a/src/Services/organService.js b/src/Services/organService.js index a4259c33..eec7013f 100644 --- a/src/Services/organService.js +++ b/src/Services/organService.js @@ -30,7 +30,6 @@ export async function createOrgan(orgao, lotacao) { headers: { Authorization: `Bearer ${getToken()}`, }, - } ); return response.status; @@ -42,13 +41,11 @@ export async function createOrgan(orgao, lotacao) { export async function listOrgans() { try { - const response = await APIUsers.get("organ/list", - { - headers: { - Authorization: `Bearer ${getToken()}`, - }, - } - ); + const response = await APIUsers.get("organ/list", { + headers: { + Authorization: `Bearer ${getToken()}`, + }, + }); return response.data; } catch (error) { return error.response.data.error; @@ -82,7 +79,6 @@ export async function updateOrgan(id, updatedData) { headers: { Authorization: `Bearer ${getToken()}`, }, - } ); return response.status; @@ -96,13 +92,11 @@ export async function updateOrgan(id, updatedData) { export async function getOrganById(id) { try { - const response = await APIUsers.get(`organ/get/${id}`, - { - headers: { - Authorization: `Bearer ${getToken()}`, - }, - } - ); + const response = await APIUsers.get(`organ/get/${id}`, { + headers: { + Authorization: `Bearer ${getToken()}`, + }, + }); return response.data; } catch (error) { return error.response.data.error; @@ -135,7 +129,6 @@ export async function deleteOrganById(id) { headers: { Authorization: `Bearer ${getToken()}`, }, - }); return response.status; } catch (error) { diff --git a/src/Utils/permission.jsx b/src/Utils/permission.jsx index 0386b1d9..b345585e 100644 --- a/src/Utils/permission.jsx +++ b/src/Utils/permission.jsx @@ -14,15 +14,15 @@ export const checkModule = (permissions, module) => { return modulePermissions ? modulePermissions.access.length > 0 : false; }; -export const checkAction = (action) => { +export const checkAction = (action) => { const permissionsString = localStorage.getItem("@App:permissions"); const permissions = JSON.parse(permissionsString); const modulePermissions = permissions.find( (permission) => permission === action ); - - return (modulePermissions) ? true : false ; + + return modulePermissions ? true : false; }; export const usePermissions = () => { diff --git a/src/Utils/permissions.test.jsx b/src/Utils/permissions.test.jsx index cfc6e097..68f0e5e5 100644 --- a/src/Utils/permissions.test.jsx +++ b/src/Utils/permissions.test.jsx @@ -38,30 +38,30 @@ describe("checkModule", () => { describe("checkAction", () => { it('should return true for action "read" in module "users"', () => { - expect(checkAction( "read")).toBe(true); + expect(checkAction("read")).toBe(true); }); it('should return true for action "write" in module "users"', () => { - expect(checkAction( "write")).toBe(true); + expect(checkAction("write")).toBe(true); }); it('should return true for action "read" in module "settings"', () => { - expect(checkAction( "read")).toBe(true); + expect(checkAction("read")).toBe(true); }); it('should return false for action "write" in module "settings"', () => { - expect(checkAction( "write")).toBe(false); + expect(checkAction("write")).toBe(false); }); it('should return true for action "view" in module "dashboard"', () => { - expect(checkAction( "view")).toBe(true); + expect(checkAction("view")).toBe(true); }); it('should return true for action "edit" in module "dashboard"', () => { - expect(checkAction( "edit")).toBe(true); + expect(checkAction("edit")).toBe(true); }); it('should return false for action "delete" in module "dashboard"', () => { - expect(checkAction( "delete")).toBe(false); + expect(checkAction("delete")).toBe(false); }); }); From a115169047ed2850a55f8e4856523a5276c9f288 Mon Sep 17 00:00:00 2001 From: Clara Ribeiro Date: Sun, 19 Jan 2025 10:42:23 -0300 Subject: [PATCH 5/5] fix: import --- src/Pages/Protected/Benefit/BenefitsValue/index.jsx | 2 +- src/Pages/Protected/Carteirinha/index.jsx | 2 +- src/Pages/Protected/Finance/BankAccountCreate/index.jsx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Pages/Protected/Benefit/BenefitsValue/index.jsx b/src/Pages/Protected/Benefit/BenefitsValue/index.jsx index 74782699..fa2e79b4 100644 --- a/src/Pages/Protected/Benefit/BenefitsValue/index.jsx +++ b/src/Pages/Protected/Benefit/BenefitsValue/index.jsx @@ -1,6 +1,6 @@ import { useState, useEffect } from "react"; import { getBenefitsForm } from "../../../../Services/benefitsService"; -import { checkAction } from "../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; import { FaWhatsapp } from "react-icons/fa"; import List from "@mui/material/List"; diff --git a/src/Pages/Protected/Carteirinha/index.jsx b/src/Pages/Protected/Carteirinha/index.jsx index 85d02ac1..9caf8456 100644 --- a/src/Pages/Protected/Carteirinha/index.jsx +++ b/src/Pages/Protected/Carteirinha/index.jsx @@ -1,7 +1,7 @@ import { useRef, useState, useEffect } from "react"; import QRCode from "react-qr-code"; import "./index.css"; -import { checkAction } from "../../Utils/permission"; +import { checkAction } from "../../../Utils/permission"; import { jsPDF } from "jspdf"; import html2canvas from "html2canvas"; diff --git a/src/Pages/Protected/Finance/BankAccountCreate/index.jsx b/src/Pages/Protected/Finance/BankAccountCreate/index.jsx index 7e5dc511..01e0c046 100644 --- a/src/Pages/Protected/Finance/BankAccountCreate/index.jsx +++ b/src/Pages/Protected/Finance/BankAccountCreate/index.jsx @@ -9,7 +9,7 @@ import { Snackbar } from "@mui/material"; import Alert from "@mui/material/Alert"; import { createBankAccount } from "../../../../Services/bankAccountService"; import Modal from "../../../../Components/Modal"; -import { checkAction } from "../../Utils/permission"; +import { checkAction } from "../../../../Utils/permission"; const BankAccount = () => { const [name, setName] = useState("");