Skip to content

Commit

Permalink
refactor: treating duplicity
Browse files Browse the repository at this point in the history
  • Loading branch information
ubrando committed Sep 21, 2024
1 parent 1a886a4 commit 1d1d884
Show file tree
Hide file tree
Showing 17 changed files with 178 additions and 241 deletions.
25 changes: 11 additions & 14 deletions src/app/__tests__/cadastrarRotina.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,15 @@ describe('CadastrarRotina Component', () => {

// Test for required title field
test('should show error if title is empty', async () => {
const { getByPlaceholderText, getByText } = render(<CadastrarRotina />);
const { getByPlaceholderText, getByText, queryAllByText } = render(<CadastrarRotina />);
const inputField = getByPlaceholderText('Adicionar título');
const saveButton = getByText('Salvar');

fireEvent.changeText(inputField, '');
fireEvent.press(saveButton);

await waitFor(() => {
expect(getByText('Campo obrigatório!')).toBeTruthy();
});
const errorMessages = queryAllByText('Campo obrigatório!');
expect(errorMessages.length).toBeGreaterThan(0);
});

it("should show error if title is too long", async () => {
Expand All @@ -92,23 +91,21 @@ describe('CadastrarRotina Component', () => {

// Test to check if error is removed when valid input is given
test('should hide error message when input is corrected', async () => {
const { getByPlaceholderText, getByText, queryByText } = render(<CadastrarRotina />);
const { getByPlaceholderText, getByText, queryByText, queryAllByText } = render(<CadastrarRotina />);
const inputField = getByPlaceholderText('Adicionar título');
const saveButton = getByText('Salvar');

fireEvent.changeText(inputField, '');
fireEvent.press(saveButton);

await waitFor(() => {
expect(getByText('Campo obrigatório!')).toBeTruthy();
});
const errorMessages1 = queryAllByText('Campo obrigatório!');
expect(errorMessages1.length).toBeGreaterThan(0);

fireEvent.changeText(inputField, 'Título válido');
fireEvent.press(saveButton);

await waitFor(() => {
expect(queryByText('Campo obrigatório!')).toBeNull();
});
const errorMessages = queryAllByText('Campo obrigatório!');
expect(errorMessages.length).toBeGreaterThan(0);
});

// Test for wrong format "data" field validation
Expand Down Expand Up @@ -139,7 +136,7 @@ describe('CadastrarRotina Component', () => {

await waitFor(() => {
const erroData = screen.getByTestId('Erro-data');
expect(erroData.props.children.props.text).toBe('Campo obrigatório');
expect(erroData.props.children.props.text).toBe('Campo obrigatório!');
});
});

Expand Down Expand Up @@ -172,7 +169,7 @@ describe('CadastrarRotina Component', () => {
});

const erroHora = getByTestId("Erro-hora");
expect(erroHora.props.children.props.text).toBe("Campo obrigatório");
expect(erroHora.props.children.props.text).toBe("Campo obrigatório!");
});

// Test for too long "descrição" field validation
Expand Down Expand Up @@ -202,7 +199,7 @@ describe('CadastrarRotina Component', () => {
});

const erroCategoria = getByTestId("Erro-categoria");
expect(erroCategoria.props.children.props.text).toBe("Campo obrigatório");
expect(erroCategoria.props.children.props.text).toBe("Campo obrigatório!");
});

});
2 changes: 1 addition & 1 deletion src/app/__tests__/editarRotina.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ describe("EditarRotina Component", () => {

await waitFor(() => {
const erroTitulo = getByText(
"O título deve ter no máximo 100 caractéres."
"O título deve ter no máximo 100 caracteres."
);
expect(erroTitulo).toBeTruthy();
});
Expand Down
20 changes: 5 additions & 15 deletions src/app/components/ModalMeta.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { EMetricas, IMetrica } from "../interfaces/metricas.interface";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { TextInput } from "react-native-gesture-handler";
import ErrorMessage from "./ErrorMessage";
import { validateValue } from "../shared/helpers/modal.helper";

interface IProps {
visible: boolean;
callbackFn: (valor: string) => unknown;
Expand All @@ -27,21 +29,9 @@ export default function ModalMeta({
const [erros, setErros] = useState<IErrors>({});
const [showErrors, setShowErrors] = useState(false);

const handleErrors = () => {
const erros: IErrors = {};

if (!valor) {
erros.valor = "Campo obrigatório!";
setShowErrors(true);
} else if (!/^[0-9/.]+$/.test(valor)) {
erros.valor = "Formato inválido!";
setShowErrors(true);
}

setErros(erros);
};

useEffect(() => handleErrors(), [valor]);
useEffect(() => {
validateValue(valor, setShowErrors, setErros);
}, [valor]);

return (
<Modal animationType="fade" transparent={true} visible={visible}>
Expand Down
20 changes: 5 additions & 15 deletions src/app/components/ModalMetrica.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { MaterialCommunityIcons } from "@expo/vector-icons";
import { FontAwesome, Entypo } from "@expo/vector-icons";
import { TextInput } from "react-native";
import ErrorMessage from "./ErrorMessage";
import { validateValue } from "../shared/helpers/modal.helper";

interface IProps {
visible: boolean;
callbackFn: (valor: string) => unknown;
Expand All @@ -29,21 +31,9 @@ export default function ModalMetrica({
const [erros, setErros] = useState<IErrors>({});
const [showErrors, setShowErrors] = useState(false);

const handleErrors = () => {
const erros: IErrors = {};

if (!valor) {
erros.valor = "Campo obrigatório!";
setShowErrors(true);
} else if (!/^[0-9/.]+$/.test(valor)) {
erros.valor = "Formato inválido!";
setShowErrors(true);
}

setErros(erros);
};

useEffect(() => handleErrors(), [valor]);
useEffect(() => {
validateValue(valor, setShowErrors, setErros);
}, [valor]);

return (
<Modal animationType="fade" transparent={true} visible={visible}>
Expand Down
7 changes: 1 addition & 6 deletions src/app/components/Publicacao.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,14 @@ import { IPublicacao } from "../interfaces/forum.interface";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import { router } from "expo-router";
import AntDesing from "react-native-vector-icons/AntDesign";
import { hasFoto } from "../shared/helpers/foto.helper";

interface IProps {
item: IPublicacao;
crop?: boolean;
}

export default function Publicacao({ item, crop }: Readonly<IProps>) {
const hasFoto = (foto: string | null | undefined) => {
if (!foto) return false;

const raw = foto.split("data:image/png;base64,")[1];
return raw.length > 0;
};

const getFoto = (foto: string | null | undefined) => {
if (hasFoto(foto)) {
Expand Down
6 changes: 1 addition & 5 deletions src/app/components/PublicacaoVisualizar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,13 @@ import { View, Image, Text, StyleSheet } from "react-native";
import { IPublicacaoUsuario } from "../interfaces/forum.interface";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import AntDesing from "react-native-vector-icons/AntDesign";
import { hasFoto } from "../shared/helpers/foto.helper";

interface IProps {
item: IPublicacaoUsuario;
}

export default function PublicacaoVisualizar({ item }: IProps) {
const hasFoto = (foto: string | null | undefined) => {
if (!foto) return false;
const raw = foto.split("data:image/png;base64,")[1];
return raw.length > 0;
};

const getFoto = (foto: string | null | undefined) => {
if (hasFoto(foto)) {
Expand Down
13 changes: 2 additions & 11 deletions src/app/private/pages/cadastrarIdoso.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { useRouter } from "expo-router";
import { IIdoso } from "../../interfaces/idoso.interface";
import Usuario from "../../model/Usuario";
import Metrica from "../../model/Metrica";

import { getTipoSanguineoOptions } from "../../shared/helpers/useNotification";

interface IErrors {
nome?: string;
Expand Down Expand Up @@ -191,16 +191,7 @@ export default function CadastrarIdoso() {

useEffect(() => handleErrors(), [nome, telefoneResponsavel, dataNascimento]);

const data = [
{ key: ETipoSanguineo.A_POSITIVO, value: ETipoSanguineo.A_POSITIVO },
{ key: ETipoSanguineo.A_NEGATIVO, value: ETipoSanguineo.A_NEGATIVO },
{ key: ETipoSanguineo.B_POSITIVO, value: ETipoSanguineo.B_POSITIVO },
{ key: ETipoSanguineo.B_NEGATIVO, value: ETipoSanguineo.B_NEGATIVO },
{ key: ETipoSanguineo.AB_POSITIVO, value: ETipoSanguineo.AB_POSITIVO },
{ key: ETipoSanguineo.AB_NEGATIVO, value: ETipoSanguineo.AB_NEGATIVO },
{ key: ETipoSanguineo.O_POSITIVO, value: ETipoSanguineo.O_POSITIVO },
{ key: ETipoSanguineo.O_NEGATIVO, value: ETipoSanguineo.O_NEGATIVO },
];
const data = getTipoSanguineoOptions();

return (
<View>
Expand Down
9 changes: 2 additions & 7 deletions src/app/private/pages/cadastrarMetrica.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ import { router } from "expo-router";
import { postMetrica } from "../../services/metrica.service";
import { EMetricas, IMetrica } from "../../interfaces/metricas.interface";
import Toast from "react-native-toast-message";
import { hasFoto

} from "../../shared/helpers/foto.helper";
export default function criarMetrica() {
const [user, setUser] = useState<IUser | undefined>(undefined);
const [idoso, setIdoso] = useState<IIdoso>();
Expand Down Expand Up @@ -43,13 +45,6 @@ export default function criarMetrica() {
});
};

const hasFoto = (foto: string | null | undefined) => {
if (!foto) return false;

const raw = foto.split("data:image/png;base64,")[1];
return raw.length > 0;
};

const getFoto = (foto: string | null | undefined) => {
if (hasFoto(foto)) {
return (
Expand Down
71 changes: 4 additions & 67 deletions src/app/private/pages/cadastrarRotina.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import * as Notifications from "expo-notifications";
import database from "../../db";
import { Collection } from "@nozbe/watermelondb";
import Rotina from "../../model/Rotina";

import { handleNotificacao, validateFields } from "../../shared/helpers/useNotification";
interface IErrors {
titulo?: string;
data?: string;
Expand Down Expand Up @@ -77,39 +77,10 @@ export default function CadastrarRotina() {
};

const handleErrors = () => {
const erros: IErrors = {};

if (!titulo) {
erros.titulo = "Campo obrigatório!";
} else if (titulo.length > 100) {
erros.titulo = "O título deve ter no máximo 100 caracteres.";
}
// } else if (titulo.length < 5) {
// erros.titulo = "O nome completo deve ter pelo menos 5 caractéres.";

if (!data) {
erros.data = "Campo obrigatório";
} else if (!/^\d{2}\/\d{2}\/\d{4}$/.test(data)) {
erros.data = "Data deve ser no formato dd/mm/yyyy!";
}

if (!hora) {
erros.hora = "Campo obrigatório";
} else if (!/^\d{2}:\d{2}$/.test(hora)) {
erros.hora = "Hora deve ser no formato hh:mm!";
}

if (!categoria) {
erros.categoria = "Campo obrigatório";
}

if (descricao?.length > 300) {
erros.descricao = "A descrição deve ter no máximo 300 caracteres.";
}

setErros(erros);
validateFields(titulo, data, hora, categoria, descricao, setErros);
};


const categorias = [
{ key: ECategoriaRotina.GERAL, value: ECategoriaRotina.GERAL },
{ key: ECategoriaRotina.MEDICAMENTO, value: ECategoriaRotina.MEDICAMENTO },
Expand Down Expand Up @@ -196,47 +167,13 @@ export default function CadastrarRotina() {
}
};

const handleNotificacao = async () => {
if (!notificacao) return;

if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C",
});
}

const { status: existingStatus } =
await Notifications.getPermissionsAsync();

let finalStatus = existingStatus;

if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}

if (finalStatus !== "granted") {
alert("É necessário permitir as notificações!");
setNotificacao(false);
return;
}

const response = await Notifications.getExpoPushTokenAsync({
projectId: "7028a81c-adee-41de-91a7-b7e80535a448",
});

setExpoToken(response.data);
};

useEffect(() => getIdoso(), []);
useEffect(() => getToken(), []);
useEffect(() => setSuggestedTitle(), [categoria]);
useEffect(() => handleErrors(), [titulo, data, hora, categoria, descricao]);
useEffect(() => {
handleNotificacao();
handleNotificacao(notificacao, setNotificacao, setExpoToken);
}, [notificacao]);

return (
Expand Down
12 changes: 2 additions & 10 deletions src/app/private/pages/editarIdoso.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import UploadImageV2 from "../../components/UploadImageV2";
import database from "../../db";
import { Collection, Q } from "@nozbe/watermelondb";
import Idoso from "../../model/Idoso";
import { getTipoSanguineoOptions } from "../../shared/helpers/useNotification";


interface IErrors {
Expand Down Expand Up @@ -230,16 +231,7 @@ export default function EditarIdoso() {
};


const data = [
{ key: ETipoSanguineo.A_POSITIVO, value: ETipoSanguineo.A_POSITIVO },
{ key: ETipoSanguineo.A_NEGATIVO, value: ETipoSanguineo.A_NEGATIVO },
{ key: ETipoSanguineo.B_POSITIVO, value: ETipoSanguineo.B_POSITIVO },
{ key: ETipoSanguineo.B_NEGATIVO, value: ETipoSanguineo.B_NEGATIVO },
{ key: ETipoSanguineo.AB_POSITIVO, value: ETipoSanguineo.AB_POSITIVO },
{ key: ETipoSanguineo.AB_NEGATIVO, value: ETipoSanguineo.AB_NEGATIVO },
{ key: ETipoSanguineo.O_POSITIVO, value: ETipoSanguineo.O_POSITIVO },
{ key: ETipoSanguineo.O_NEGATIVO, value: ETipoSanguineo.O_NEGATIVO },
];
const data = getTipoSanguineoOptions();


return (
Expand Down
Loading

0 comments on commit 1d1d884

Please sign in to comment.