import { Injectable } from '@nestjs/common' import { isEmpty, isNil, sample } from 'lodash' import { FoodPlanRepository, MenuRepository, PatientRepository } from '../../../repositories' import { UserNotFoundError } from '../../../errors/user_not_found.error' import { FoodPlanAIService } from '../../../services' import { Menu, Patient } from '../../../models' @Injectable() export class Nutrition { constructor( private readonly patientRepository: PatientRepository, private readonly menuRepository: MenuRepository, private readonly foodPlanRepository: FoodPlanRepository, private readonly foodPlanAiService: FoodPlanAIService, ) {} async generateMenuToPatient(patientId: string): Promise { const patient = await this.patientRepository.get(patientId) if (!patient) throw new UserNotFoundError(`id: ${patientId}`) patient.menu_id = await this.getPatientNewMenuId(patient) await this.patientRepository.update(patient) return patient.menu_id } private async getPatientNewMenuId(patient: Patient): Promise { let menu = await this.getPredictedMenuFromPatientId(patient) if (!isNil(menu)) return await this.menuRepository.createWithRelationships(menu) menu = await this.getRandomMenu(patient) return menu?.id } private async getPredictedMenuFromPatientId(patient: Patient): Promise { const predictedMenu = await this.foodPlanAiService.getFromPatientId(patient.id) if (!predictedMenu?.food_plan_id) return null const originalFoodPlan = await this.foodPlanRepository.getWithRelationships(predictedMenu.food_plan_id) if (!originalFoodPlan) { console.warn("Predicted food plan doesn't exists", predictedMenu.food_plan_id) return null } const menu = originalFoodPlan.cloneToMenu(true) menu.changeMealGroupTimes(predictedMenu.meal_time_adjusted, true) return menu } private async getRandomMenu(patient: Patient): Promise { const menus = await this.menuRepository.findBy(patient.goal_id, patient.restriction_ids) if (isEmpty(menus)) return null return sample(menus) } }