Skip to content

Commit

Permalink
Incluindo contexto e resolvendo bugs de sessao, autenticacao e dashboard
Browse files Browse the repository at this point in the history
  • Loading branch information
itsmorais committed Oct 28, 2024
1 parent 702697d commit 30dc494
Show file tree
Hide file tree
Showing 29 changed files with 465 additions and 244 deletions.
37 changes: 26 additions & 11 deletions backend/src/controllers/MetricasController.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import User from "../models/mongo/User";
import pg from "../databases/postgres";

export interface MetricasProps {
calorias: number;
proteinas: number;
gordura: number;
carboidrato: number;
acucar: number;
IMC: number;
TMB: number;
aguaIdeal: number;
}
class MetricasController {
// Criar um novo usuário
async calculateMetricas(idUsuario: string) {
Expand Down Expand Up @@ -30,25 +39,31 @@ class MetricasController {
const carboidrato = parseFloat((peso * 4.25).toFixed(2));
const acucar = parseFloat((peso / 0.66).toFixed(2));

for (const users of userMongo) {
users.macroIdeal.Caloria = calorias;
users.macroIdeal.Proteina = proteinas;
users.macroIdeal.gordura = gordura;
users.macroIdeal.Carboidrato = carboidrato;
users.macroIdeal.acucar = acucar;
users.metrica.ImcIdeal = IMC;
users.metrica.TmbIdeal = TMB;
users.ingestaoAgua.ingestaoIdeal = aguaIdeal;
users.save();
const MetricasValues: MetricasProps = {
calorias,
proteinas,
gordura,
carboidrato,
acucar,
IMC,
TMB,
aguaIdeal

}


return MetricasValues

} catch (error) {
console.error("Erro ao calcular as métricas do usuário:", error);
return
}
}





}

export default new MetricasController();
22 changes: 21 additions & 1 deletion backend/src/controllers/alimentosController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,29 @@ class AlimentosController {
}

async findAlimento(req: Request, res: Response): Promise<Response> {
try {
console.log("RECEBIDO");
const { barcode } = req.params;
console.log(barcode, "BARCODE BACK");

const alimentos = await pg.query(
`SELECT * FROM "Alimentos" WHERE "barcode" = $1`,
[barcode]
);
console.log(alimentos.rows);
if (alimentos.rows.length > 0) {
return res.status(201).json(alimentos.rows[0]);
} else {
return res.status(204).json({ message: "Alimento não encontrado" });
}
} catch (error: any) {
return res.status(500).json(error.message);
}
}

async searchAlimentoByName(req: Request, res: Response): Promise<Response> {
try {
const { id,nomeProduto } = req.params;
console.log(nomeProduto, "BUSCANDO ESSE ALIMENTO NO BANCO");

const alimentos = await pg.query(
` SELECT DISTINCT A."nomeProduto", A."idProduto" ,A.barcode,A."Proteina",A."Caloria", A."Carboidrato", A.gordura, A.sodio, A.acucar,
Expand Down
4 changes: 2 additions & 2 deletions backend/src/controllers/cadastroController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ class CadastroController {
return res
.status(201)
.json({ message: "Usuário criado com sucesso!", idUserPostgres });
} catch (error) {
console.error("Erro ao criar usuário:", error);
} catch (error:any) {
console.error("Erro ao criar usuário:", error.message);
return res.status(500).json({ message: "Erro ao criar usuário", error });
}
}
Expand Down
5 changes: 3 additions & 2 deletions backend/src/controllers/dashboardController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class DashboardController {
const { data } = req.body;
const { userId } = req.params;


const data_atual = moment(data).format("YYYY-MM-DD");
const userPG = await User.find({ idUser: userId });

Expand All @@ -27,6 +28,7 @@ class DashboardController {
data_atual: data_atual,
usuario: usersPG?.id,
});

if (buscandoUsuario) {
usuarioEncontrado = buscandoUsuario;
}
Expand All @@ -40,8 +42,7 @@ class DashboardController {

const userMongo = await User.findById(usuarioEncontrado.usuario);
const userPotsgres = await pg.query(
`select "nomeUsuario",peso,altura,genero,meta,"TMB" FROM "User" WHERE "idUsuario" = $1`,
[userMongo?.idUser]
`select "nomeUsuario",peso,altura,genero,meta,"TMB" FROM "User" WHERE "idUsuario" = ${userId}`,
);

return res
Expand Down
22 changes: 12 additions & 10 deletions backend/src/controllers/dataController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import pg from '../databases/postgres'
import Data from "../models/mongo/Data";
import User from "../models/mongo/User";
import moment from 'moment';

import MetricasController, { MetricasProps } from "./MetricasController";
class DataController {

public dayOfTheWeek = (day: number): string => {
Expand Down Expand Up @@ -41,24 +41,26 @@ class DataController {
const { userId } = req.params;
const { data } = req.body
const data_atual = moment(data).format("YYYY-MM-DD")
console.log("RECEBIDO!",data_atual,userId)
console.log("RECEBIDO!", data_atual, userId)

// VERIFICA SE O USUÁRIO EXISTE NA TABELA POSTGRESQL
const users = await pg.query(`SELECT * FROM "User" WHERE "idUsuario" = $1`, [userId]);
if (users.rows.length === 0) {
return res.status(404).json({ message: "Usuário não encontrado" });
}

const metricasData: MetricasProps | undefined = await MetricasController.calculateMetricas(userId);

const userData = await new User({
idUser: userId,
consumoAlimentos: [],
macroIdeal: {
Proteina: 300,
Caloria: 300,
Carboidrato: 300,
gordura: 300,
Proteina: metricasData?.proteinas,
Caloria: metricasData?.calorias,
Carboidrato: metricasData?.carboidrato,
gordura: metricasData?.gordura,
sodio: 300,
acucar: 300,
acucar: metricasData?.acucar,
},
macroReal: {
Proteina: 0,
Expand All @@ -71,11 +73,11 @@ class DataController {
metrica: {
ImcAtual: 0,
TmbAtual: 0,
ImcIdeal: 0,
TmbIdeal: 0,
ImcIdeal: metricasData?.IMC,
TmbIdeal: metricasData?.TMB,
},
ingestaoAgua: {
ingestaoIdeal: 3000,
ingestaoIdeal: metricasData?.aguaIdeal,
ingestaoAtual: 0,
},
}).save();
Expand Down
6 changes: 0 additions & 6 deletions backend/src/controllers/editProfileController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,6 @@ class EditProfileController {
return res.status(404).json({ message: "Usuário não encontrado" });
}

try {
MetricasController.calculateMetricas(idUsuario);
} catch (error: any) {
console.log("Erro ao calcular métricas do usuário");
}

return res.status(200).json({
message: "Usuário atualizado com sucesso!",
user: updatedUser.rows[0],
Expand Down
4 changes: 4 additions & 0 deletions backend/src/controllers/loginController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class LoginController {

// Verificar se o usuário existe
if (user.rows.length === 0) {
console.log("USUÁRIO NÃO ENCONTRADO!")
return res.status(404).json({ message: "Usuário não encontrado" });
}

Expand All @@ -37,6 +38,9 @@ class LoginController {
id: foundUser.idUsuario,
nomeUsuario: foundUser.nomeUsuario,
email: foundUser.email,
peso: foundUser.peso,
altura:foundUser.altura,
genero:foundUser.genero
},
});
} catch (error) {
Expand Down
4 changes: 2 additions & 2 deletions backend/src/databases/postgres.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ const password = process.env.PG_PASS || 'your_pg_password';
console.log(password)

const connectionString = `postgresql://postgres.wnvipfgsewkkjiiwsoic:${password}@aws-0-us-west-1.pooler.supabase.com:6543/postgres`
const postgresLocal = `postgresql://postgres:2202@localhost:5432/Dnutri`
const postgresLocal = `postgresql://postgres:123@localhost:5432/Dnutri`

const pool = new Pool({
connectionString: connectionString,
connectionString: postgresLocal,
});

async function connectToPostgres() {
Expand Down
3 changes: 2 additions & 1 deletion backend/src/models/mongo/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ export interface IAgua {
}

// Interface para User
interface IUser {
export interface IUser {
id:Schema.Types.ObjectId
idUser:number;
consumoAlimentos: IAlimento[];
macroIdeal: IMacroNutrientes;
Expand Down
3 changes: 2 additions & 1 deletion backend/src/routes/alimento.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ const FoodRouter = Router();

FoodRouter.post("/alimentos", AlimentoController.createAlimento);
FoodRouter.get("/alimentos/:id/:quantity", AlimentoController.buscarAlimentos);
FoodRouter.get("/findAlimento/:id/:nomeProduto", AlimentoController.findAlimento);
FoodRouter.get("/searchAlimentoByName/:id/:nomeProduto", AlimentoController.searchAlimentoByName);
FoodRouter.get("/findAlimento/:barcode", AlimentoController.findAlimento);
FoodRouter.post("/addAlimento/", AlimentoController.addAlimento);
FoodRouter.post("/consumidos", AlimentoController.alimentosConsumidos);
FoodRouter.get("/favoritos/:id", AlimentoController.favoritosAlimentos);
Expand Down
5 changes: 1 addition & 4 deletions backend/src/routes/dashboardRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,7 @@ const DashboardRouter = express.Router();

// Rotas para dados diários
//DashboardRouter.get("/data/:userId/", DataController.getDataById);
DashboardRouter.post(
"/dashboard/:userId",
dashboardController.getUserDataByDate
);
DashboardRouter.post("/dashboard/:userId",dashboardController.getUserDataByDate);
//DashboardRouter.delete("/data/:userId", DataController.deleteData);

export default DashboardRouter;
12 changes: 10 additions & 2 deletions frontend/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import Routes from "./src/routes";
import React, { useEffect } from "react";
import * as SplashScreen from "expo-splash-screen";
import { useFonts, Signika_400Regular } from "@expo-google-fonts/signika";

import { UserProvider } from "./src/context/userContext";
import { DateProvider } from "./src/context/dateContext";
SplashScreen.preventAutoHideAsync(); // Manter a splash screen até as fontes serem carregadas

export default function App() {
Expand All @@ -21,5 +22,12 @@ export default function App() {
if (!fontsLoaded) {
return null; // Retorna null enquanto as fontes estão carregando
}
return <Routes />;
return (
<UserProvider>
<DateProvider>
<Routes />
</DateProvider>
</UserProvider>

)
}
2 changes: 1 addition & 1 deletion frontend/src/components/AguaConsumo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { View, Text, Dimensions, StyleSheet, SafeAreaView, Image, TouchableOpaci
import { IUser } from '../../types/userDiary';
import { StackNavigationProp } from "@react-navigation/stack";
import { RootStackParamList } from "../../../types";
import AsyncStorage from '@react-native-async-storage/async-storage';
type AguaComponentNavigationProp = StackNavigationProp<RootStackParamList, "AguaComponent">;

interface UserProps {
Expand All @@ -15,7 +16,6 @@ const screenWidth = Dimensions.get('window').width;
const logo = require("../../../assets/add.png");

export default function AguaConsumo({ userMG, navigation }: UserProps) {

let aguaIdeal = userMG?.ingestaoAgua?.ingestaoIdeal || 0
let aguaReal = userMG?.ingestaoAgua?.ingestaoAtual || 0
let idealMetrica = "ml"
Expand Down
24 changes: 24 additions & 0 deletions frontend/src/context/dateContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// src/context/DateContext.tsx
import React, { createContext, useState, ReactNode } from 'react';
import moment from 'moment';

interface DateContextData {
date: string;
setDate: React.Dispatch<React.SetStateAction<string>>;
}

export const DateContext = createContext<DateContextData | undefined>(undefined);

interface DateProviderProps {
children: ReactNode;
}

export const DateProvider = ({ children }: DateProviderProps) => {
const [date, setDate] = useState(moment.utc().format("YYYY-MM-DD"));

return (
<DateContext.Provider value={{ date, setDate }}>
{children}
</DateContext.Provider>
);
};
36 changes: 36 additions & 0 deletions frontend/src/context/userContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// src/context/UserContext.tsx
import React, { createContext, useState, ReactNode, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { IuserLogin } from '../types/user';

interface UserContextData {
user: IuserLogin | null;
setUser: React.Dispatch<React.SetStateAction<IuserLogin | null>>;
}

export const UserContext = createContext<UserContextData | undefined>(undefined);

interface UserProviderProps {
children: ReactNode;
}

export const UserProvider = ({ children }: UserProviderProps) => {
const [user, setUser] = useState<IuserLogin | null>(null);

useEffect(() => {
// Verifica se há um usuário salvo no AsyncStorage ao iniciar a aplicação
const loadUser = async () => {
const storedUser = await AsyncStorage.getItem('user');
if (storedUser) {
setUser(JSON.parse(storedUser));
}
};
loadUser();
}, []);

return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
};
Loading

0 comments on commit 30dc494

Please sign in to comment.