Skip to content

Commit

Permalink
Merge pull request #2 from vitorrsousaa/fix/GODIET-22-create-planning…
Browse files Browse the repository at this point in the history
…-fixes-create-planning-meal

[GODIET-22] create planning fixes create planning meal
  • Loading branch information
vitorrsousaa authored Feb 14, 2024
2 parents aa39986 + d8fe877 commit bad2e62
Show file tree
Hide file tree
Showing 13 changed files with 248 additions and 54 deletions.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
"lint:fix": "prettier --write ./src && eslint ./src --ext .ts --fix",
"preview": "vite preview",
"prepare": "husky",
"test": "vitest --coverage",
"test:ci": "vitest --no-watch --passWithNoTests",
"test:ui": "vitest --ui",
"test": "vitest run --coverage",
"test:ci": "vitest run --no-watch --passWithNoTests ",
"test:ui": "vitest run --ui",
"typecheck": "tsc --noEmit"
},
"dependencies": {
Expand Down
1 change: 1 addition & 0 deletions src/app/config/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const ROUTES = {
PATIENTS: '/pacientes',
PATIENTS_BY_ID: '/pacientes/:id',
PLANNING_MEAL_BY_PATIENT: '/pacientes/:id/plano',
PLANNING_MEAL_BY_PATIENT_SHOW: '/pacientes/:id/plano/:planningId',
CREATE_PLANNING_CONVENTIONAL: '/pacientes/:id/plano/convencional',
CREATE_PLANNING_GODIET: '/pacientes/:id/plano/godiet',
SETTINGS: '/configuracoes',
Expand Down
38 changes: 36 additions & 2 deletions src/app/hooks/planningMeal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,20 @@ export function useCreatePlanningMeal() {
};
}

export function useGetAllByPatient(patientId?: string) {
interface queryGetAllByPatientParams {
planningId?: string;
patientId?: string;
}

export function useGetAllByPatient(params: queryGetAllByPatientParams) {
const { patientId } = params;

const { data, isFetching, isPending } = useQuery({
queryKey: [QUERY_CACHE_KEYS.PLANNING_MEAL, patientId],
queryFn: () => planningMealServices.getAllByPatient(patientId || ''),
queryFn: () =>
planningMealServices.getAllByPatient<false>({
patientId: patientId || '',
}),
enabled: !!patientId,
});

Expand All @@ -26,3 +36,27 @@ export function useGetAllByPatient(patientId?: string) {
isFetchingPlanningMeals: isFetching || isPending,
};
}

export function useGetByPlanningId(params: queryGetAllByPatientParams) {
const { patientId, planningId } = params;

const { data, isFetching, isPending, isError } = useQuery({
queryKey: [
QUERY_CACHE_KEYS.PLANNING_MEAL,
patientId,
planningId && planningId,
],
queryFn: () =>
planningMealServices.getAllByPatient<true>({
patientId: patientId || '',
planningId,
}),
enabled: !!patientId && !!planningId,
});

return {
planningMeal: data,
isFetchingPlanningMeal: isFetching || isPending,
isErrorPlanningMeal: isError,
};
}
30 changes: 2 additions & 28 deletions src/app/services/planningMeal/create.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,10 @@
import { TCreatePlanningMealDTO } from '@godiet-pages/CreatePlanningEquivalent/CreatePlanningEquivalent.hook';
import { httpClient } from '@godiet-services/httpClient';

import { mapperPlanningMeal } from './mapper';

interface FoodOption {
baseQty: number;
foodId: string;
}

interface Food {
id: string;
portion: string;
categoryId: string;
options: FoodOption[];
}

interface Categories {
qty: number;
id: string;
}

interface Meal {
categories: Categories[];
foods: Food[];
}

interface PlanningMeal {
name: string;
meals: Meal[];
}

export interface CreatePlanningMealInput {
planningMeal: PlanningMeal;
planningMeal: TCreatePlanningMealDTO;
patientId: string;
}

Expand Down
17 changes: 14 additions & 3 deletions src/app/services/planningMeal/getAllByPatient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,20 @@ interface TPlanningMeal {
createdAt: string;
}

export async function getAllByPatient(patientId: string) {
const { data } = await httpClient.get<TPlanningMeal[]>(
`/planningMeal/${patientId}`
interface getAllByPatientParams {
patientId: string;
planningId?: string;
}

type TPlanningMealResponse<HasPlanningId extends boolean> =
HasPlanningId extends true ? TPlanningMeal : TPlanningMeal[];

export async function getAllByPatient<T extends boolean>(
params: getAllByPatientParams
) {
const { patientId, planningId } = params;
const { data } = await httpClient.get<TPlanningMealResponse<T>>(
`/planningMeal/${patientId}${planningId ? `?planningId=${planningId}` : ''}`
);

return data;
Expand Down
16 changes: 10 additions & 6 deletions src/app/services/planningMeal/mapper.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { CreatePlanningMealInput } from './create';
import { TCreatePlanningMealDTO } from '@godiet-pages/CreatePlanningEquivalent/CreatePlanningEquivalent.hook';

interface FoodToDatabase {
portion: number;
options: string[];
categoryNameId: string;
}

interface MealToDatabase {
foods: FoodToDatabase[];
name: string;
time: string;
}

interface PlanningMealToDatabase {
Expand All @@ -15,26 +18,27 @@ interface PlanningMealToDatabase {
}

export function mapperPlanningMeal(
planningMeal: CreatePlanningMealInput['planningMeal']
planningMeal: TCreatePlanningMealDTO
): PlanningMealToDatabase {
return {
meals: planningMeal.meals.map(mapperMeals),
name: planningMeal.name,
};
}

function mapperMeals(
meal: CreatePlanningMealInput['planningMeal']['meals'][0]
): MealToDatabase {
function mapperMeals(meal: TCreatePlanningMealDTO['meals'][0]): MealToDatabase {
return {
foods: meal.foods.map(foodToDatabase),
name: meal.name,
time: meal.time,
};
}

function foodToDatabase(
food: CreatePlanningMealInput['planningMeal']['meals'][0]['foods'][0]
food: TCreatePlanningMealDTO['meals'][0]['foods'][0]
): FoodToDatabase {
return {
categoryNameId: food.categoryId,
portion: Number(food.portion),
options: food.options.map((option) => option.foodId),
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { useCallback, useEffect, useMemo, useState } from 'react';

import { useGetAllCategoryName } from '@godiet-hooks/categoryName';
import { useGetByPatientId } from '@godiet-hooks/patient';
import { useCreatePlanningMeal } from '@godiet-hooks/planningMeal';
import { useNavigate } from '@godiet-hooks/routes';

import { zodResolver } from '@hookform/resolvers/zod';
import { useFieldArray, useForm, useWatch } from 'react-hook-form';
Expand Down Expand Up @@ -62,7 +64,12 @@ export function useCreatePlanningEquivalenteHook() {

const { id } = useParams<{ id: string }>();

const { isFetchingPatient, isErrorPatient } = useGetByPatientId(id);
const { isFetchingPatient, isErrorPatient, patient } = useGetByPatientId(id);

const { createPlanningMeal, isCreatingPlanningMeal } =
useCreatePlanningMeal();

const { navigate } = useNavigate();

const methods = useForm<TCreatePlanningMealDTO>({
resolver: zodResolver(CreatePlanningMealSchema),
Expand Down Expand Up @@ -99,9 +106,20 @@ export function useCreatePlanningEquivalenteHook() {
const { categoriesName, isFetchingCategories, isErrorCategories } =
useGetAllCategoryName();

const handleSubmit = hookFormSubmit((data) => {
const handleSubmit = hookFormSubmit(async (data) => {
// Remover o local storage
console.log('submit', data);
try {
await createPlanningMeal({
planningMeal: data,
patientId: patient?.id || '',
});

toast.success('Plano alimentar criado com sucesso');

navigate('PLANNING_MEAL_BY_PATIENT', { id: patient?.id || '' });
} catch {
toast.error('Erro ao criar o plano alimentar');
}
});

const handleAddNewMeal = useCallback(() => {
Expand Down Expand Up @@ -204,6 +222,7 @@ export function useCreatePlanningEquivalenteHook() {
formIsValid,
isFetchingPatient,
isErrorPatient,
isCreatingPlanningMeal,
hasCategories,
handleSubmit,
toggleIncreaseFoodModal,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export function CreatePlanningEquivalent() {
formIsValid,
isFetchingPatient,
isErrorPatient,
isCreatingPlanningMeal,
hasCategories,
toggleIncreaseFoodModal,
register,
Expand Down Expand Up @@ -110,11 +111,16 @@ export function CreatePlanningEquivalent() {
<Card.Footer>
<Button
onClick={toggleIncreaseFoodModal}
disabled={!hasCategories(index)}
disabled={
!hasCategories(index) ||
isCreatingPlanningMeal
}
>
Selecionar alimentos
</Button>
<Button>Adicionar observações</Button>
<Button disabled={isCreatingPlanningMeal}>
Adicionar observações
</Button>
</Card.Footer>
</Card.Root>
<IncreaseFoodModal
Expand All @@ -129,13 +135,18 @@ export function CreatePlanningEquivalent() {
</div>

<div className="mt-8 space-x-4">
<Button type="button" onClick={handleAddNewMeal}>
<Button
type="button"
onClick={handleAddNewMeal}
disabled={isCreatingPlanningMeal}
>
Adicionar nova refeição
</Button>
<Button
type="submit"
onClick={handleSubmit}
disabled={!formIsValid}
isLoading={isCreatingPlanningMeal}
>
Criar plano alimentar
</Button>
Expand Down
Loading

0 comments on commit bad2e62

Please sign in to comment.