From c600563f1b46531c7cfdb5ec464d844a3e308513 Mon Sep 17 00:00:00 2001 From: Vinicius Oliveira Date: Fri, 17 Jan 2025 14:21:15 -0300 Subject: [PATCH] Revert "Bug idoso" --- src/app/private/pages/cadastrarIdoso.tsx | 69 +-- src/app/private/pages/listarIdosos.tsx | 563 ++++++++++++----------- 2 files changed, 297 insertions(+), 335 deletions(-) diff --git a/src/app/private/pages/cadastrarIdoso.tsx b/src/app/private/pages/cadastrarIdoso.tsx index f6d8ae6e..1a88309c 100644 --- a/src/app/private/pages/cadastrarIdoso.tsx +++ b/src/app/private/pages/cadastrarIdoso.tsx @@ -27,11 +27,11 @@ import Metrica from "../../model/Metrica"; import { getTipoSanguineoOptions } from "../../shared/helpers/useNotification"; import styles from "../../components/style/styles"; interface IErrors { - nome?: string; - dataNascimento?: string; - tipoSanguineo?: string; - telefoneResponsavel?: string; - descricao?: string; + nome?: string; + dataNascimento?: string; + tipoSanguineo?: string; + telefoneResponsavel?: string; + descricao?: string; } export default function CadastrarIdoso() { @@ -41,16 +41,14 @@ export default function CadastrarIdoso() { const [telefoneResponsavel, setTelefoneResponsavel] = useState(""); const [dataNascimento, setDataNascimento] = useState(""); const [descricao, setDescricao] = useState(""); + const [token, setToken] = useState(""); const [erros, setErros] = useState({}); const [showErrors, setShowErrors] = useState(false); const [showLoading, setShowLoading] = useState(false); const [idUsuario, setIdUsuario] = useState(null); const [maskedTelefoneResponsavel, setMaskedTelefoneResponsavel] = useState(""); - const router = useRouter(); - const API_URL = process.env.EXPO_PUBLIC_API_URL; - const API_PORT = process.env.EXPO_PUBLIC_API_USUARIO_PORT; - const BASE_URL = `${API_URL}:${API_PORT}/api/saude/idoso`; + const router = useRouter(); useEffect(() => { const getIdUsuario = async () => { @@ -59,7 +57,7 @@ export default function CadastrarIdoso() { if (response) { const usuario = JSON.parse(response) as IUser; setIdUsuario(usuario.id); - // console.log("Usuário logado:", usuario); + console.log("Usuário logado:", usuario); } else { console.log("Usuário não encontrado no AsyncStorage."); } @@ -68,11 +66,14 @@ export default function CadastrarIdoso() { } }; + getIdUsuario(); }, []); + useEffect(() => handleErrors(), [nome, telefoneResponsavel, dataNascimento]); + const getDateIsoString = (value: string) => { const dateArray = value.split("/"); return `${dateArray[2]}-${dateArray[1]}-${dateArray[0]}T12:00:00.000Z`; @@ -176,52 +177,10 @@ export default function CadastrarIdoso() { } try { - const token = await AsyncStorage.getItem('token') - - if (!token) { - console.error('Token não encontrado.'); - return; - } - setShowLoading(true); - // await salvarNoBancoLocal(); - - if (idUsuario === null) { - return - } - - const body = { - nome: nome, - dataNascimento: getDateIsoString(dataNascimento), - telefoneResponsavel: telefoneResponsavel, - descricao: descricao, - tipoSanguineo: tipoSanguineo, - idUsuario: idUsuario, - foto: foto || '' - }; - - const response = await fetch(BASE_URL, - { - method: "POST", - headers: { - Accept: "application/json", - "Content-Type": "application/json", - Authorization: `Bearer ${token}`, - }, - body: JSON.stringify(body) - } - ) - - const data = await response.json() - - console.log('response', data) - - if (data.message == "Salvo com sucesso!") { - ToastAndroid.show("Idoso salvo com sucesso!", ToastAndroid.SHORT); - router.replace("/private/pages/listarIdosos"); - } else { - throw new Error("Erro ao salvar idoso") - } + await salvarNoBancoLocal(); + ToastAndroid.show("Idoso salvo no banco local com sucesso!", ToastAndroid.SHORT); + router.replace("/private/pages/listarIdosos"); } catch (err) { const error = err as { message: string }; ToastAndroid.show(`Erro: ${error.message}`, ToastAndroid.SHORT); diff --git a/src/app/private/pages/listarIdosos.tsx b/src/app/private/pages/listarIdosos.tsx index cbe5df40..c4c4f26a 100644 --- a/src/app/private/pages/listarIdosos.tsx +++ b/src/app/private/pages/listarIdosos.tsx @@ -1,16 +1,16 @@ import React, { useEffect, useState } from "react"; import { - View, - Text, - StyleSheet, - Pressable, - ActivityIndicator, + View, + Text, + StyleSheet, + Pressable, + ActivityIndicator, } from "react-native"; import { FlatList } from "react-native"; import { AntDesign } from "@expo/vector-icons"; import BackButton from "../../components/BackButton"; import CardIdoso from "../../components/CardIdoso"; -import { router, useRouter } from "expo-router"; +import { useRouter } from "expo-router"; import { IIdoso, IOrder } from "../../interfaces/idoso.interface"; import Toast from "react-native-toast-message"; import { SelectList } from "react-native-dropdown-select-list"; @@ -21,289 +21,292 @@ import Idoso from "../../model/Idoso"; import { Collection, Q } from "@nozbe/watermelondb"; import { getImageUri } from "../../shared/helpers/image.helper"; + interface IOrderOption { - key: IOrder; - value: string; + key: IOrder; + value: string; } + const data: IOrderOption[] = [ - { - key: { - column: "nome", - dir: "ASC", - }, - value: "A-Z", - }, - { - key: { - column: "nome", - dir: "DESC", - }, - value: "Z-A", - }, - { - key: { - column: "dataNascimento", - dir: "DESC", - }, - value: "Mais atual", - }, - { - key: { - column: "dataNascimento", - dir: "ASC", - }, - value: "Mais antigo", - }, + { + key: { + column: "nome", + dir: "ASC", + }, + value: "A-Z", + }, + { + key: { + column: "nome", + dir: "DESC", + }, + value: "Z-A", + }, + { + key: { + column: "dataNascimento", + dir: "DESC", + }, + value: "Mais atual", + }, + { + key: { + column: "dataNascimento", + dir: "ASC", + }, + value: "Mais antigo", + }, ]; export default function ListarIdosos() { - const [idosos, setIdosos] = useState([]); - const [loading, setLoading] = useState(true); - const [orderOption, setOrderOption] = useState(data[0].key); - const [idUsuario, setIdUsuario] = useState(null); - const router = useRouter(); - - const API_URL = process.env.EXPO_PUBLIC_API_URL; - const API_PORT = process.env.EXPO_PUBLIC_API_USUARIO_PORT; - const BASE_URL = `${API_URL}:${API_PORT}/api/saude/idoso`; - - useEffect(() => { - const getIdUsuario = async () => { - try { - const response = await AsyncStorage.getItem("usuario"); - if (response) { - const usuario = JSON.parse(response) as IUser; - setIdUsuario(usuario.id); - // console.log("Usuário logado:", usuario); - } - } catch (error) { - console.error("Erro ao obter usuário:", error); - } - }; - - getIdUsuario(); - }, []); - - const getIdosos = async () => { - if (!idUsuario) return; - - setLoading(true); - - try { - // const idosoCollection = database.get('idoso') as Collection; - - // const query = Q.sortBy( - // orderOption.column, - // orderOption.dir.toLowerCase() as 'asc' | 'desc' - // ); - - // const idosoRecords = await idosoCollection.query(query).fetch(); - - const response = await fetch(BASE_URL, { - method: "GET", - headers: { - Accept: "application/json", - "Content-Type": "application/json", - }, - }); - - const data = await response.json(); - - console.log("Dados recebidos:", data); - - const idosoRecords: any[] = data.data - - const mappedIdoso = idosoRecords.map((item: any) => ({ - ...item, - foto: getImageUri(item.foto), - })); - - setIdosos(mappedIdoso); - console.log("Idosos carregados:", mappedIdoso); - } catch (err) { - const error = err as { message: string }; - Toast.show({ - type: "error", - text1: "Erro!", - text2: error.message, - }); - } finally { - setLoading(false); - } - }; - - const navigateCadastrar = () => { - router.push("/private/pages/cadastrarIdoso"); - }; - - useEffect(() => { - if (idUsuario) { - getIdosos(); - } - }, [orderOption, idUsuario]); - - return ( - - - - - - De quem está cuidando agora? - - - { - setOrderOption(item); - }} - search={false} - boxStyles={styles.boxDropDown} - inputStyles={styles.boxInputDropDown} - dropdownStyles={styles.dropDown} - placeholder="selecione" - /> - - - {loading && ( - - - - )} - - {!loading && ( - - } - /> - - )} - - - - Cadastrar um idoso - - - - ); + const [idosos, setIdosos] = useState([]); + const [loading, setLoading] = useState(true); + const [orderOption, setOrderOption] = useState(data[0].key); + const [idUsuario, setIdUsuario] = useState(null); + + + const router = useRouter(); + + + useEffect(() => { + const getIdUsuario = async () => { + try { + const response = await AsyncStorage.getItem("usuario"); + if (response) { + const usuario = JSON.parse(response) as IUser; + setIdUsuario(usuario.id); + console.log("Usuário logado:", usuario); + } + } catch (error) { + console.error("Erro ao obter usuário:", error); + } + }; + + + getIdUsuario(); + }, []); + + + const getIdosos = async () => { + if (!idUsuario) return; + + + setLoading(true); + + + try { + const idosoCollection = database.get('idoso') as Collection; + + + const query = Q.sortBy( + orderOption.column, + orderOption.dir.toLowerCase() as 'asc' | 'desc' + ); + + + const idosoRecords = await idosoCollection.query(query).fetch(); + + + const mappedIdoso = idosoRecords.map((item) => ({ + ...item._raw, + foto: getImageUri(item.foto), + })); + + + setIdosos(mappedIdoso); + console.log("Idosos carregados:", mappedIdoso); + } catch (err) { + const error = err as { message: string }; + Toast.show({ + type: "error", + text1: "Erro!", + text2: error.message, + }); + } finally { + setLoading(false); + } + }; + + + const navigateCadastrar = () => { + router.push("/private/pages/cadastrarIdoso"); + }; + + + useEffect(() => { + if (idUsuario) { + getIdosos(); + } + }, [orderOption, idUsuario]); + + + return ( + + + + + + + De quem está cuidando agora? + + + + { + setOrderOption(item); + }} + search={false} + boxStyles={styles.boxDropDown} + inputStyles={styles.boxInputDropDown} + dropdownStyles={styles.dropDown} + placeholder="selecione" + /> + + + + {loading && ( + + + + )} + + + {!loading && ( + + } + /> + + )} + + + + Cadastrar um idoso + + + + ); } + const styles = StyleSheet.create({ - screen: { - backgroundColor: "#FFFFFF", - height: "100%", - }, - backButton: { - height: 60, - flexDirection: "row", - alignItems: "center", - }, - header: { - alignSelf: "center", - fontSize: 25, - fontWeight: "bold", - color: "#3d3d3d", - marginBottom: 20, - textAlign: "center", - }, - cadastroContainer: { - flexDirection: "column", - alignItems: "center", - justifyContent: "center", - position: "absolute", - bottom: 0, - right: 0, - left: 0, - backgroundColor: "white", - paddingTop: 10, - paddingBottom: 10, - }, - cadastroBtn: { - flexDirection: "column", - alignItems: "center", - justifyContent: "center", - width: "100%", - }, - cadastroText: { - marginTop: 8, - fontWeight: "500", - }, - cardIdoso: { - alignItems: "center", - justifyContent: "space-between", - marginBottom: 250, - }, - idosoSelecionado: { - marginLeft: 16, - marginRight: 16, - marginBottom: 32, - borderWidth: 3, - borderColor: "#2CCDB5", - }, - actionButton: { - flexDirection: "row", - alignItems: "center", - justifyContent: "center", - padding: 5, - borderRadius: 5, - width: 110, - shadowColor: "#333", - shadowOffset: { width: 0, height: 1 }, - shadowOpacity: 0.5, - shadowRadius: 2, - }, - editButton: { - backgroundColor: "#2CCDB5", - }, - actionButtonText: { - color: "white", - fontSize: 13, - fontWeight: "700", - marginRight: 5, - }, - actions: { - alignItems: "center", - width: "100%", - padding: 10, - paddingBottom: 15, - }, - loading: { - flexDirection: "row", - alignItems: "center", - justifyContent: "center", - backgroundColor: "white", - marginVertical: 50, - }, - boxDropDownDefault: { - borderWidth: 0, - backgroundColor: "#2CCDB5", - }, - boxDropDown: { - borderWidth: 0, - width: 149, - backgroundColor: "#2CCDB5", - shadowRadius: 1, - shadowColor: "#3d3d3d", - marginLeft: 5, - }, - boxInputDropDown: { - color: "#FFFFFF", - fontSize: 16, - paddingRight: 6, - }, - dropDown: { - borderColor: "#2CCDB5", - width: 150, - marginTop: 3, - marginLeft: 5, - }, - list: { - width: "24%", - marginLeft: 10, - marginBottom: 20, - }, + screen: { + backgroundColor: "#FFFFFF", + height: "100%", + }, + backButton: { + height: 60, + flexDirection: "row", + alignItems: "center", + }, + header: { + alignSelf: "center", + fontSize: 25, + fontWeight: "bold", + color: "#3d3d3d", + marginBottom: 20, + textAlign: "center", + }, + cadastroContainer: { + flexDirection: "column", + alignItems: "center", + justifyContent: "center", + position: "absolute", + bottom: 0, + right: 0, + left: 0, + backgroundColor: "white", + paddingTop: 10, + paddingBottom: 10, + }, + cadastroBtn: { + flexDirection: "column", + alignItems: "center", + justifyContent: "center", + width: "100%", + }, + cadastroText: { + marginTop: 8, + fontWeight: "500", + }, + cardIdoso: { + alignItems: "center", + justifyContent: "space-between", + marginBottom: 250, + }, + idosoSelecionado: { + marginLeft: 16, + marginRight: 16, + marginBottom: 32, + borderWidth: 3, + borderColor: "#2CCDB5", + }, + actionButton: { + flexDirection: "row", + alignItems: "center", + justifyContent: "center", + padding: 5, + borderRadius: 5, + width: 110, + shadowColor: "#333", + shadowOffset: { width: 0, height: 1 }, + shadowOpacity: 0.5, + shadowRadius: 2, + }, + editButton: { + backgroundColor: "#2CCDB5", + }, + actionButtonText: { + color: "white", + fontSize: 13, + fontWeight: "700", + marginRight: 5, + }, + actions: { + alignItems: "center", + width: "100%", + padding: 10, + paddingBottom: 15, + }, + loading: { + flexDirection: "row", + alignItems: "center", + justifyContent: "center", + backgroundColor: "white", + marginVertical: 50, + }, + boxDropDownDefault: { + borderWidth: 0, + backgroundColor: "#2CCDB5", + }, + boxDropDown: { + borderWidth: 0, + width: 149, + backgroundColor: "#2CCDB5", + shadowRadius: 1, + shadowColor: "#3d3d3d", + marginLeft: 5, + }, + boxInputDropDown: { + color: "#FFFFFF", + fontSize: 16, + paddingRight: 6, + }, + dropDown: { + borderColor: "#2CCDB5", + width: 150, + marginTop: 3, + marginLeft: 5, + }, + list: { + width: "24%", + marginLeft: 10, + marginBottom: 20, + }, });