merge master
continuous-integration/drone/push Build is passing Details

WORK-RRE
Rémi REGNAULT 1 year ago
commit 4b4a113ba9

@ -1,30 +1,41 @@
export default class Profile { export default class Profile {
private _name: string; public name: string;
private _avatar: string; public avatar: string;
private _allergy: string[]; public allergies: string[];
private _diets: string[]; public diets: string[];
public isActive: string;
public isWaiting: string
constructor( name: string, avatar: string, allergy: string[], diets: string[]) { constructor( name: string, avatar: string, allergies: string[], diets: string[], isActive: string, isWaiting: string) {
this._name = name; this.name = name;
this._avatar = avatar; this.avatar = avatar;
this._allergy = allergy; this.diets = diets;
this._diets = diets; this.allergies = allergies;
this.isActive = isActive;
this.isWaiting = isWaiting
} }
get name(): string { // get name(): string {
return this._name; // return this._name;
} // }
// get avatar(): string{
// return this._avatar;
// }
get avatar(): string{ // get allergies(): string[]{
return this._avatar; // return this._allergies;
} // }
get allergy(): string[]{ // get diets(): string[]{
return this._allergy; // return this._diets;
} // }
get diets(): string[]{ // get isActive(): string{
return this._diets; // return this._isActive;
} // }
}
// get isWaiting(): string{
// return this._isWaiting;
// }
}

@ -5,4 +5,7 @@ export default interface IIngredientService {
getIngredientById(id: number): Promise<Ingredient | null>; getIngredientById(id: number): Promise<Ingredient | null>;
getIngredientByLetter(id: string): Promise<Ingredient[]>; getIngredientByLetter(id: string): Promise<Ingredient[]>;
getfilteredIngredient(prompt: string): Promise<Ingredient[]>; getfilteredIngredient(prompt: string): Promise<Ingredient[]>;
getAvailableIngredient(): Promise<Ingredient[]>,
addIngredient(newIngredient: Ingredient): Promise<boolean>,
delIngredient(idIngredient: number): Promise<boolean>
} }

@ -1,6 +1,8 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import Ingredient from "../../Models/Ingredient"; import Ingredient from "../../Models/Ingredient";
import IIngredientService from "./IIngredientService"; import IIngredientService from "./IIngredientService";
import axios from 'axios'; import axios from 'axios';
import eventEmitter from "../../screens/EventEmitter";
export default class IngredientService implements IIngredientService { export default class IngredientService implements IIngredientService {
private readonly API_URL = "http://leftovers.alwaysdata.net/ingredients"; private readonly API_URL = "http://leftovers.alwaysdata.net/ingredients";
@ -41,4 +43,36 @@ export default class IngredientService implements IIngredientService {
throw new Error('Erreur lors de la récupération des ingrédients : ' + error.message); throw new Error('Erreur lors de la récupération des ingrédients : ' + error.message);
} }
} }
async getAvailableIngredient(): Promise<Ingredient[]> {
const results = await AsyncStorage.getItem('ingredient')
const availableIngredient = JSON.parse(results)
if(availableIngredient.length == 0){
availableIngredient.push(new Ingredient(-1, "None"))
}
console.log("AvailableIngredient:", availableIngredient)
return availableIngredient;
}
async addIngredient(newIngredient: Ingredient): Promise<boolean> {
let selectedIngredients = await this.getAvailableIngredient()
const exists = selectedIngredients.find((ingredient) => ingredient.id === newIngredient.id);
if (!exists) {
let existingAvailableIngredient = await AsyncStorage.getItem('ingredient');
existingAvailableIngredient = existingAvailableIngredient ? JSON.parse(existingAvailableIngredient) : [];
const updatedAvailableIngredient = [...existingAvailableIngredient, newIngredient];
await AsyncStorage.setItem('ingredient', JSON.stringify(updatedAvailableIngredient));
eventEmitter.emit('ingredientAdded');
return true
}
return false
}
async delIngredient(idIngredient: number): Promise<boolean> {
let selectedIngredients = await this.getAvailableIngredient()
const updatedIngredients = selectedIngredients.filter((ingredient) => ingredient.id !== idIngredient);
await AsyncStorage.setItem('ingredient', JSON.stringify(updatedIngredients));
eventEmitter.emit('ingredientDeleted');
return true
}
} }

@ -1,7 +1,7 @@
import Profil from "../../Models/Profil"; import Profile from "../../Models/Profile";
export default interface IProfileService { export default interface IProfileService {
getProfiles(): Promise<Profil[]>, getProfiles(): Promise<Profile[]>,
addProfile(new_profile: Profil): Promise<boolean>, addProfile(newProfile: Profile): Promise<boolean>,
delProfile(profile_name_to_del: string): Promise<boolean> delProfile(index: number): Promise<boolean>
} }

@ -1,44 +1,32 @@
import Profile from "../../Models/Profile"; import Profile from "../../Models/Profile";
import IProfileService from "./IProfileService"; import IProfileService from "./IProfileService";
import AsyncStorage from "@react-native-async-storage/async-storage"; import AsyncStorage from "@react-native-async-storage/async-storage";
import eventEmitter from "../../screens/EventEmitter";
export default class ProfileService implements IProfileService { export default class ProfileService implements IProfileService {
async getProfiles(): Promise<Profile[]> { async getProfiles(): Promise<Profile[]> {
const results = await AsyncStorage.getItem('profiles'); const results = await AsyncStorage.getItem('profiles')
if (results == null) { const existingProfiles = JSON.parse(results)
return [] if(existingProfiles.length == 0){
} existingProfiles.push(new Profile("None", "logo.png", [], [], "none", "none"))
const tmp = JSON.parse(results)
let existingProfiles: Profile[] = []
for (let item of tmp) {
existingProfiles.push(new Profile(item._name, item._avatar, item._allergy, item._diets))
} }
return existingProfiles; return existingProfiles;
} }
async addProfile(new_profile : Profile): Promise<boolean> { async addProfile(newProfile : Profile): Promise<boolean> {
const existingProfiles = await this.getProfiles() let existingProfiles = await AsyncStorage.getItem('profiles')
for (let current_profile of existingProfiles) { existingProfiles = existingProfiles ? JSON.parse(existingProfiles) : [];
if (current_profile.name == new_profile.name) { const updatedProfiles = [...existingProfiles, newProfile];
console.log("Tried to create a profil already existing !") await AsyncStorage.setItem('profiles', JSON.stringify(updatedProfiles));
return false eventEmitter.emit("profileAdded")
}
}
await AsyncStorage.setItem('profiles', JSON.stringify([...existingProfiles, new_profile]))
return true return true
} }
async delProfile(profile_name_to_del: string): Promise<boolean> { async delProfile(index: number): Promise<boolean> {
const existing_profiles = await this.getProfiles() const existingProfiles = await this.getProfiles()
let key: number = -1 const updatedProfiles = existingProfiles.filter((profile, i) => i !== index);
for (let current_profile of existing_profiles) { await AsyncStorage.setItem('profiles', JSON.stringify(updatedProfiles));
if (current_profile.name == profile_name_to_del) { eventEmitter.emit('profileDeleted');
let updated_profile = existing_profiles.splice(key, 1) return true
await AsyncStorage.setItem('profiles', JSON.stringify(updated_profile))
return true
}
key ++
}
return false
} }
} }

@ -12,6 +12,11 @@ export default function ListWithoutSelect(props: ListProps) {
const [selected, setSelected] = React.useState([]); const [selected, setSelected] = React.useState([]);
const colors = useContext(ColorContext).colors; const colors = useContext(ColorContext).colors;
let listContent = []
props.content.forEach((val) => {
listContent.push({value: val, disabled: true})
})
const styles = StyleSheet.create({ const styles = StyleSheet.create({
titleBar: { titleBar: {
flexDirection: "row", flexDirection: "row",
@ -80,7 +85,7 @@ export default function ListWithoutSelect(props: ListProps) {
return ( return (
<MultipleSelectList <MultipleSelectList
setSelected={(val) => setSelected(val)} setSelected={(val) => setSelected(val)}
data={props.content} data={listContent}
save="value" save="value"
search={false} search={false}
arrowicon={<Image source={require("../assets/images/arrow.png")} style={styles.arrow}></Image>} arrowicon={<Image source={require("../assets/images/arrow.png")} style={styles.arrow}></Image>}
@ -97,5 +102,4 @@ export default function ListWithoutSelect(props: ListProps) {
placeholder={props.title} placeholder={props.title}
label={props.title}/> label={props.title}/>
); );
} }

@ -40,7 +40,7 @@ export default function BottomBar({ state, descriptors, navigation }) {
bottom: 0, bottom: 0,
right: 0, right: 0,
left: 0, left: 0,
height: "8%", height: 60,
backgroundColor: theme === 'dark' ? "#3F3C42" : "transparent" backgroundColor: theme === 'dark' ? "#3F3C42" : "transparent"
}, },
BottomBarBlurContainer: { BottomBarBlurContainer: {

@ -37,7 +37,7 @@ export default function ProfilesStackScreen({ navigation }) {
const _handleSearch = () => { const _handleSearch = () => {
console.log('Searching'); console.log('Searching');
} }
const _handleHeaderAdd = () => navigation.navigate('ProfileCreation', { name: String }); const _handleHeaderAdd = () => navigation.navigate('ProfileCreation');
return ( return (
<ProfilesStack.Navigator> <ProfilesStack.Navigator>

@ -6,9 +6,8 @@ import ValidateButton from '../components/ValidateButton';
import ColorContext from '../theme/ColorContext'; import ColorContext from '../theme/ColorContext';
import ListWithoutSelect from '../components/ListWithoutSelect'; import ListWithoutSelect from '../components/ListWithoutSelect';
import ListSelect from '../components/ListSelect'; import ListSelect from '../components/ListSelect';
import EventEmitter from './EventEmitter';
import * as ImagePicker from 'expo-image-picker'; import * as ImagePicker from 'expo-image-picker';
import AsyncStorage from '@react-native-async-storage/async-storage'; import ProfileService from '../Services/Profiles/ProfileService';
export default function CreateProfile(props) { export default function CreateProfile(props) {
@ -19,6 +18,7 @@ export default function CreateProfile(props) {
const [avatar, setAvatar] = useState<string>(''); const [avatar, setAvatar] = useState<string>('');
const [selectedDiets, setSelectedDiets] = useState([]); const [selectedDiets, setSelectedDiets] = useState([]);
const [selectedAllergies] = useState([]) const [selectedAllergies] = useState([])
const profileService = new ProfileService()
const handleSelectedDiets = (selectedValues) => { const handleSelectedDiets = (selectedValues) => {
setSelectedDiets(selectedValues); setSelectedDiets(selectedValues);
@ -48,7 +48,6 @@ export default function CreateProfile(props) {
const handleCreateProfile = async () => { const handleCreateProfile = async () => {
try { try {
// Ton code pour récupérer les profils existants et ajouter un nouveau profil
const newProfile = { const newProfile = {
name: name, name: name,
avatar: avatar, avatar: avatar,
@ -57,14 +56,7 @@ export default function CreateProfile(props) {
isActive: "flex", isActive: "flex",
isWaiting: "none", isWaiting: "none",
}; };
profileService.addProfile(newProfile)
// Mettre à jour AsyncStorage avec le nouveau profil
let existingProfiles = await AsyncStorage.getItem('profiles');
existingProfiles = existingProfiles ? JSON.parse(existingProfiles) : [];
const updatedProfiles = [...existingProfiles, newProfile];
await AsyncStorage.setItem('profiles', JSON.stringify(updatedProfiles));
EventEmitter.emit('profileAdded');
console.log('Profil créé :', newProfile);
props.navigation.goBack(); props.navigation.goBack();
} catch (error) { } catch (error) {
console.error('Erreur lors de la création du profil :', error); console.error('Erreur lors de la création du profil :', error);

@ -2,14 +2,14 @@ import React, {useContext, useState, useEffect} from 'react';
import {StyleSheet, View, Text, ScrollView, useWindowDimensions} from 'react-native'; import {StyleSheet, View, Text, ScrollView, useWindowDimensions} from 'react-native';
import {LinearGradient} from 'expo-linear-gradient'; import {LinearGradient} from 'expo-linear-gradient';
import {SafeAreaProvider} from 'react-native-safe-area-context'; import {SafeAreaProvider} from 'react-native-safe-area-context';
import ValidateButton from '../components/ValidateButton'; import ValidateButton from '../components/ValidateButton';
import ListSelect from '../components/ListSelect'; import ListSelect from '../components/ListSelect';
import ListWithoutSelect from '../components/ListWithoutSelect'; import ListWithoutSelect from '../components/ListWithoutSelect';
import ProfileSelection from '../components/ProfileSelection'; import ProfileSelection from '../components/ProfileSelection';
import ColorContext from '../theme/ColorContext'; import ColorContext from '../theme/ColorContext';
import EventEmitter from './EventEmitter'; import eventEmitter from './EventEmitter';
import AsyncStorage from '@react-native-async-storage/async-storage'; import AsyncStorage from '@react-native-async-storage/async-storage';
import ProfileService from '../Services/Profiles/ProfileService';
export default function FiltersSelection(props) { export default function FiltersSelection(props) {
const {colors} = useContext(ColorContext); const {colors} = useContext(ColorContext);
@ -17,7 +17,7 @@ export default function FiltersSelection(props) {
{name: "None", avatar: "logo.png", diets: [], allergies: [], isActive: "none", isWaiting: "none"}, {name: "None", avatar: "logo.png", diets: [], allergies: [], isActive: "none", isWaiting: "none"},
] ]
const die = [{value: "Dairy free"}, {value: "Gluten free"}, {value: "Porkless"}, {value: "Vegan"}, {value: "Vegetarian"}, {value: "Pescatarian"}] const die = [{value: "Dairy free"}, {value: "Gluten free"}, {value: "Porkless"}, {value: "Vegan"}, {value: "Vegetarian"}, {value: "Pescatarian"}]
const profileService = new ProfileService()
const [profiles, setProfiles] = useState(profilesHand); const [profiles, setProfiles] = useState(profilesHand);
const [dieProfiles, setDieProfiles] = useState([]) const [dieProfiles, setDieProfiles] = useState([])
const [allProfiles, setAllProfiles] = useState([]) const [allProfiles, setAllProfiles] = useState([])
@ -25,45 +25,31 @@ export default function FiltersSelection(props) {
const [allAdd, setAllAdd] = useState([]) const [allAdd, setAllAdd] = useState([])
const [selectedDiets, setSelectedDiets] = useState([]) const [selectedDiets, setSelectedDiets] = useState([])
const handleGetProfiles = async () => {
try {
const existingProfiles = await AsyncStorage.getItem('profiles');
return JSON.parse(existingProfiles) || [];
} catch (error) {
console.log("Error occured during GetProfiles", error);
return [];
}
}
const fetchProfiles = async () => { const fetchProfiles = async () => {
const existingProfiles = await handleGetProfiles() setProfiles(await profileService.getProfiles())
setProfiles(existingProfiles) }
};
const subscription = EventEmitter.addListener('profileAdded', async () => { const subscriptionAddProfile = eventEmitter.addListener('profileAdded', async () => {
fetchProfiles() fetchProfiles()
subscriptionAddProfile.remove()
eventEmitter.removeAllListeners('profileAdded')
eventEmitter.removeAllListeners('updateDietsAllergies')
eventEmitter.removeAllListeners('selectedProfilesUpdated')
}); });
let cptSubscription = 1 const subscriptionUpdateDietsAllergies = eventEmitter.addListener('updateDietsAllergies', async() => {
setDieAdd(die.filter(isInProfileDiets))
const subscriptionUpdateDietsAllergies = EventEmitter.addListener('updateDietsAllergies', async () => { setAllAdd([])
updateDiets() subscriptionUpdateDietsAllergies.remove()
setDieAdd(die.filter(isInProfileDiets)) subscriptionUpdateProfiles.remove();
console.log("Passage Subsciption:", cptSubscription) eventEmitter.removeAllListeners('updateDietsAllergies')
}); })
let cptSubscriptionDiets = 1
const subscriptionUpdateDiets = EventEmitter.addListener('updateDiets', async () => {
setDieAdd(die.filter(isInProfileDiets))
console.log("Passage SubsciptionDiets:", cptSubscriptionDiets)
});
useEffect(() => { useEffect(() => {
fetchProfiles() fetchProfiles()
}, []); }, []);
const handleSaveSelectedProfiles = async () => { async function handleSaveSelectedProfiles(){
try { try {
profiles.forEach((val) => { profiles.forEach((val) => {
if(val.isWaiting == "flex"){ if(val.isWaiting == "flex"){
@ -78,19 +64,20 @@ export default function FiltersSelection(props) {
}) })
await AsyncStorage.setItem('profiles', JSON.stringify(profiles)); await AsyncStorage.setItem('profiles', JSON.stringify(profiles));
fetchProfiles() fetchProfiles()
updateDiets() eventEmitter.emit("selectedProfilesUpdated")
setDieAdd(die.filter(isInProfileDiets))
updateAllergies()
setAllAdd([])
} catch (error) { } catch (error) {
console.error('Error occured when updating active profiles:', error); console.error('Error occured when updating active profiles:', error, selectedDiets);
} }
}; };
const subscriptionUpdateSelectedProfiles = EventEmitter.addListener('selectedProfilesUpdated', async () => { const subscriptionUpdateProfiles = eventEmitter.addListener('selectedProfilesUpdated', async () => {
fetchProfiles()
updateDiets() updateDiets()
setDieAdd(die.filter(isInProfileDiets)) updateAllergies()
eventEmitter.emit("updateDietsAllergies")
subscriptionUpdateProfiles.remove();
eventEmitter.removeAllListeners('profileAdded')
eventEmitter.removeAllListeners('updateDietsAllergies')
eventEmitter.removeAllListeners('selectedProfilesUpdated')
}); });
const updateDiets = () => { const updateDiets = () => {
@ -101,13 +88,12 @@ export default function FiltersSelection(props) {
profile.diets.forEach((diet) => { profile.diets.forEach((diet) => {
retType = true retType = true
dieTemp.forEach((val) => { dieTemp.forEach((val) => {
console.log("Value DieTemp:",val) if(val == diet){
if(val.value == diet){
retType = false retType = false
} }
}) })
if(retType){ if(retType){
dieTemp.push({value: diet}) dieTemp.push(diet)
} }
}) })
} }
@ -123,18 +109,17 @@ export default function FiltersSelection(props) {
profile.allergies.forEach((allergy) => { profile.allergies.forEach((allergy) => {
retType = true retType = true
allTemp.forEach((val) => { allTemp.forEach((val) => {
if(val.value == allergy){ if(val == allergy){
retType = false retType = false
} }
}) })
if(retType){ if(retType){
allTemp.push({value: allergy}) allTemp.push(allergy)
} }
}) })
} }
}) })
setAllProfiles(allTemp) setAllProfiles(allTemp)
console.log("Technique de Shinobi Anti-CodeSmell", selectedDiets)
} }
const changeStatusWaiting = (cpt) => { const changeStatusWaiting = (cpt) => {
@ -177,8 +162,8 @@ export default function FiltersSelection(props) {
function isInProfileDiets(element) { function isInProfileDiets(element) {
let retType = true let retType = true
dieProfiles.forEach(function (diet) { dieProfiles.forEach((diet) => {
if(diet.value==element.value){ if(diet==element.value){
retType = false retType = false
} }
}) })
@ -281,9 +266,9 @@ export default function FiltersSelection(props) {
<Text style={styles.filters}>Additional Filters</Text> <Text style={styles.filters}>Additional Filters</Text>
<Text style={styles.nbSelected}>{dieAdd.length} available</Text> <Text style={styles.nbSelected}>{dieAdd.length} available</Text>
</View> </View>
<ListSelect title="Diets" content={dieAdd} setSelected={handleSelectedDiets}/> <ListSelect title="Additional Diets" content={dieAdd} setSelected={handleSelectedDiets}/>
<View style={{marginTop: "3%"}}/> <View style={{marginTop: "3%"}}/>
<ListWithoutSelect title="Allergies" content={allAdd}></ListWithoutSelect> <ListWithoutSelect title="Additional Allergies" content={allAdd}></ListWithoutSelect>
<View style={{marginTop: "3%"}}/> <View style={{marginTop: "3%"}}/>
<ValidateButton title="Add Allergy" image="plus.png" colour={colors.buttonDetail} backColour={colors.buttonBackground} todo={() => props.navigation.navigate("IngredientSelection")}></ValidateButton> <ValidateButton title="Add Allergy" image="plus.png" colour={colors.buttonDetail} backColour={colors.buttonBackground} todo={() => props.navigation.navigate("IngredientSelection")}></ValidateButton>
</View> </View>

@ -2,17 +2,15 @@ import React, { useContext, useState, useEffect } from 'react';
import { StyleSheet, View, Text, Pressable, Image, ScrollView } from 'react-native'; import { StyleSheet, View, Text, Pressable, Image, ScrollView } from 'react-native';
import {LinearGradient} from 'expo-linear-gradient'; import {LinearGradient} from 'expo-linear-gradient';
import {SafeAreaProvider} from 'react-native-safe-area-context'; import {SafeAreaProvider} from 'react-native-safe-area-context';
import ValidateButton from '../components/ValidateButton'; import ValidateButton from '../components/ValidateButton';
import ProfileSelection from '../components/ProfileSelection'; import ProfileSelection from '../components/ProfileSelection';
import FoodElementText from '../components/FoodElementText'; import FoodElementText from '../components/FoodElementText';
import ColorContext from '../theme/ColorContext'; import ColorContext from '../theme/ColorContext';
import bracketLeft from '../assets/images/angle_bracket_left.png'; import bracketLeft from '../assets/images/angle_bracket_left.png';
import bracketRight from '../assets/images/angle_bracket_right.png'; import bracketRight from '../assets/images/angle_bracket_right.png';
import AsyncStorage from '@react-native-async-storage/async-storage'; import AsyncStorage from '@react-native-async-storage/async-storage';
import EventEmitter from './EventEmitter'; import eventEmitter from './EventEmitter';
import ProfileService from '../Services/Profiles/ProfileService';
export default function HomePage({ navigation, props }) { export default function HomePage({ navigation, props }) {
const colors = useContext(ColorContext).colors const colors = useContext(ColorContext).colors
@ -25,35 +23,21 @@ export default function HomePage({ navigation, props }) {
const [profiles, setProfiles] = useState(profilesHand); const [profiles, setProfiles] = useState(profilesHand);
const [ingredientList, setIngredientList] = useState(ingredientListHand) const [ingredientList, setIngredientList] = useState(ingredientListHand)
const handleGetProfiles = async () => { const profileService = new ProfileService()
try {
const existingProfiles = await AsyncStorage.getItem('profiles');
return JSON.parse(existingProfiles) || [];
} catch (error) {
console.log(error);
return [];
}
}
const handleGetAvailableIngredient = async () => { const handleGetAvailableIngredient = async () => {
try { try {
const existingAvailableIngredient = await AsyncStorage.getItem('ingredient'); const existingAvailableIngredient = await AsyncStorage.getItem('ingredient');
return JSON.parse(existingAvailableIngredient) || []; return JSON.parse(existingAvailableIngredient) || [];
} catch (error) { } catch (error) {
console.log(error); console.error(error);
return []; return [];
} }
} }
const fetchProfiles = async () => { const fetchProfiles = async () => {
const existingProfiles = await handleGetProfiles(); setProfiles(await profileService.getProfiles())
if (existingProfiles.length != 0){ }
setProfiles(existingProfiles);
}
else{
setProfiles(profilesHand)
}
};
const fetchAvailableIngredient = async () => { const fetchAvailableIngredient = async () => {
const existingAvailableIngredient = await handleGetAvailableIngredient(); const existingAvailableIngredient = await handleGetAvailableIngredient();
@ -65,34 +49,64 @@ export default function HomePage({ navigation, props }) {
} }
}; };
const subscriptionAddProfile = EventEmitter.addListener('profileAdded', async () => { const subscriptionAddProfile = eventEmitter.addListener('profileAdded', async () => {
fetchProfiles(); fetchProfiles();
subscriptionAddProfile.remove();
eventEmitter.removeAllListeners('profileAdded')
eventEmitter.removeAllListeners('profileDeleted')
eventEmitter.removeAllListeners('ingredientAdded')
eventEmitter.removeAllListeners('ingredientDeleted')
eventEmitter.removeAllListeners('selectedProfilesUpdated')
}); });
const subscriptionDeleteProfile = EventEmitter.addListener('profileDeleted', async () => { const subscriptionDeleteProfile = eventEmitter.addListener('profileDeleted', async () => {
if (profiles.length == 1){ if (profiles.length == 1){
setProfiles(profilesHand) setProfiles(profilesHand)
} }
else{ else{
fetchProfiles(); fetchProfiles();
} }
subscriptionDeleteProfile.remove();
eventEmitter.removeAllListeners('profileAdded')
eventEmitter.removeAllListeners('profileDeleted')
eventEmitter.removeAllListeners('ingredientAdded')
eventEmitter.removeAllListeners('ingredientDeleted')
eventEmitter.removeAllListeners('selectedProfilesUpdated')
}); });
const subscriptionAddIngredient = EventEmitter.addListener('ingredientAdded', async () => { const subscriptionAddIngredient = eventEmitter.addListener('ingredientAdded', async () => {
fetchAvailableIngredient(); fetchAvailableIngredient();
subscriptionAddIngredient.remove();
eventEmitter.removeAllListeners('profileAdded')
eventEmitter.removeAllListeners('profileDeleted')
eventEmitter.removeAllListeners('ingredientAdded')
eventEmitter.removeAllListeners('ingredientDeleted')
eventEmitter.removeAllListeners('selectedProfilesUpdated')
}); });
const subscriptionDeleteIngredient = EventEmitter.addListener('ingredientDeleted', async () => { const subscriptionDeleteIngredient = eventEmitter.addListener('ingredientDeleted', async () => {
if (ingredientList.length == 1){ if (ingredientList.length == 1){
setIngredientList(ingredientListHand) setIngredientList(ingredientListHand)
} }
else{ else{
fetchAvailableIngredient(); fetchAvailableIngredient();
} }
subscriptionDeleteIngredient.remove();
eventEmitter.removeAllListeners('profileAdded')
eventEmitter.removeAllListeners('profileDeleted')
eventEmitter.removeAllListeners('ingredientAdded')
eventEmitter.removeAllListeners('ingredientDeleted')
eventEmitter.removeAllListeners('selectedProfilesUpdated')
}); });
const subscriptionUpdateSelectedProfile = EventEmitter.addListener('selectedProfilesUpdated', async () => { const subscriptionUpdateSelectedProfile = eventEmitter.addListener('selectedProfilesUpdated', async () => {
fetchProfiles(); fetchProfiles();
subscriptionUpdateSelectedProfile.remove();
eventEmitter.removeAllListeners('profileAdded')
eventEmitter.removeAllListeners('profileDeleted')
eventEmitter.removeAllListeners('ingredientAdded')
eventEmitter.removeAllListeners('ingredientDeleted')
eventEmitter.removeAllListeners('selectedProfilesUpdated')
}); });
useEffect(() => { useEffect(() => {
@ -233,7 +247,7 @@ export default function HomePage({ navigation, props }) {
<Text style={styles.nbSelected}>{nbActiveProfiles()} selected</Text> <Text style={styles.nbSelected}>{nbActiveProfiles()} selected</Text>
</View> </View>
<View style={{marginTop: "3%"}}/> <View style={{marginTop: "3%"}}/>
<ProfileSelection listProfile={profiles} disableSelection={true} changeStatusWaiting={(val) => console.log("Ignorer", val)}/> <ProfileSelection listProfile={profiles} disableSelection={true} changeStatusWaiting={(val) => val += 1}/>
<View style={{marginTop: "4%"}}/> <View style={{marginTop: "4%"}}/>
<ValidateButton title="Change Active Filters" image="update.png" colour={colors.buttonDetail} backColour={colors.buttonBackground} todo={() => navigation.navigate('FiltersSelection')}/> <ValidateButton title="Change Active Filters" image="update.png" colour={colors.buttonDetail} backColour={colors.buttonBackground} todo={() => navigation.navigate('FiltersSelection')}/>
<View style={{marginTop: "3%"}}/> <View style={{marginTop: "3%"}}/>

@ -9,7 +9,7 @@ import IngredientService from '../Services/Ingredients/IngredientsServices';
import ColorContext from '../theme/ColorContext'; import ColorContext from '../theme/ColorContext';
import ValidateButton from '../components/ValidateButton'; import ValidateButton from '../components/ValidateButton';
import AsyncStorage from '@react-native-async-storage/async-storage'; import AsyncStorage from '@react-native-async-storage/async-storage';
import EventEmitter from './EventEmitter'; import eventEmitter from './EventEmitter';
import plus from '../assets/images/plus.png'; import plus from '../assets/images/plus.png';
import moins from '../assets/images/minus.png'; import moins from '../assets/images/minus.png';
@ -37,7 +37,7 @@ export default function IngredientSelection(props) {
setResponse(filtered); setResponse(filtered);
} }
} catch (error) { } catch (error) {
console.log(error); console.error(error);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@ -50,10 +50,9 @@ export default function IngredientSelection(props) {
const loadIngredients = async () => { const loadIngredients = async () => {
try { try {
const ingredients = await ingredientService.getAllIngredient(); setResponse(await ingredientService.getAllIngredient());
setResponse(ingredients);
} catch (error) { } catch (error) {
console.log(error); console.error(error);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
@ -96,7 +95,7 @@ const loadIngredients = async () => {
const existingAvailableIngredient = await AsyncStorage.getItem('ingredient'); const existingAvailableIngredient = await AsyncStorage.getItem('ingredient');
return JSON.parse(existingAvailableIngredient) || []; return JSON.parse(existingAvailableIngredient) || [];
} catch (error) { } catch (error) {
console.log(error); console.error(error);
return []; return [];
} }
} }
@ -107,7 +106,7 @@ const fetchAvailableIngredient = async () => {
setSelectedIngredients(existingAvailableIngredient); setSelectedIngredients(existingAvailableIngredient);
} }
else{ else{
setSelectedIngredients([{value: "None"}]) setSelectedIngredients([new Ingredient(-1, "None")])
} }
}; };
@ -119,13 +118,14 @@ const fetchAvailableIngredient = async () => {
existingAvailableIngredient = existingAvailableIngredient ? JSON.parse(existingAvailableIngredient) : []; existingAvailableIngredient = existingAvailableIngredient ? JSON.parse(existingAvailableIngredient) : [];
const updatedAvailableIngredient = [...existingAvailableIngredient, newIngredient]; const updatedAvailableIngredient = [...existingAvailableIngredient, newIngredient];
await AsyncStorage.setItem('ingredient', JSON.stringify(updatedAvailableIngredient)); await AsyncStorage.setItem('ingredient', JSON.stringify(updatedAvailableIngredient));
EventEmitter.emit('ingredientAdded'); eventEmitter.emit('ingredientAdded');
fetchAvailableIngredient();
console.log('Ingredient Added:', newIngredient); console.log('Ingredient Added:', newIngredient);
ChangeAvailableSize(false) ChangeAvailableSize(false)
} }
} }
catch(error){ catch(error){
console.log("Error occured during the addition of Ingredient:", error) console.error("Error occured during the addition of Ingredient:", error)
} }
}; };
@ -133,28 +133,16 @@ const fetchAvailableIngredient = async () => {
try{ try{
const updatedIngredients = selectedIngredients.filter((ingredient) => ingredient.id !== idIngredient); const updatedIngredients = selectedIngredients.filter((ingredient) => ingredient.id !== idIngredient);
await AsyncStorage.setItem('ingredient', JSON.stringify(updatedIngredients)); await AsyncStorage.setItem('ingredient', JSON.stringify(updatedIngredients));
EventEmitter.emit('ingredientDeleted'); eventEmitter.emit('ingredientDeleted');
fetchAvailableIngredient(); fetchAvailableIngredient();
setSelectedIngredients(updatedIngredients); setSelectedIngredients(updatedIngredients);
ChangeAvailableSize(true) ChangeAvailableSize(true)
} }
catch (error){ catch (error){
console.log("Error occured during the suppression of Ingredient:", error) console.error("Error occured during the suppression of Ingredient:", error)
} }
}; };
const subscriptionAddIngredient = EventEmitter.addListener('ingredientAdded', async () => {
fetchAvailableIngredient();
});
const subscriptionDeleteIngredient = EventEmitter.addListener('ingredientDeleted', async () => {
if (selectedIngredients.length == 1){
setSelectedIngredients([{title: "None"}])
}
else{
fetchAvailableIngredient();
}
});
const ChangeAvailableSize = (remove: boolean) => { const ChangeAvailableSize = (remove: boolean) => {
if(remove){ if(remove){
if (selectedIngredients.length == 1){ if (selectedIngredients.length == 1){
@ -178,7 +166,7 @@ const fetchAvailableIngredient = async () => {
setAvailableSize(90) setAvailableSize(90)
} }
else if (selectedIngredients.length == 1){ else if (selectedIngredients.length == 1){
if(selectedIngredients[0].value == "None"){ if(selectedIngredients[0].name == "None"){
setAvailableSize(90) setAvailableSize(90)
} }
else{ else{
@ -199,7 +187,7 @@ const fetchAvailableIngredient = async () => {
const ingredientsByLetter = await ingredientService.getIngredientByLetter(letter); const ingredientsByLetter = await ingredientService.getIngredientByLetter(letter);
setResponse(ingredientsByLetter); setResponse(ingredientsByLetter);
} catch (error) { } catch (error) {
console.log(error); console.error(error);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }

@ -15,27 +15,23 @@ export default function ModifyProfile(props) {
const [profile, setProfile] = useState(null); const [profile, setProfile] = useState(null);
const route = useRoute(); const route = useRoute();
const handleGetProfileByName = async (profileName) => { const handleGetProfileByName = async (profileName) => {
try { try {
const existingProfiles = await AsyncStorage.getItem('profiles'); const existingProfiles = await AsyncStorage.getItem('profiles');
const profiles = JSON.parse(existingProfiles) || []; const profiles = JSON.parse(existingProfiles) || [];
const matchedProfile = profiles.find(profile => profile.name === profileName); const matchedProfile = profiles.find(profile => profile.name === profileName);
console.log("Le profil choisit : " + matchedProfile);
return matchedProfile || null; return matchedProfile || null;
} catch (error) { } catch (error) {
console.log("Erreur lors de la récupération du profil :", error); console.error("Erreur lors de la récupération du profil :", error);
return null; return null;
} }
}; };
const fetchProfiles = async () => { const fetchProfiles = async () => {
const selectedProfil = await handleGetProfileByName(route.params); const selectedProfil = await handleGetProfileByName(route.params);
setProfile(selectedProfil); setProfile(selectedProfil);
}; };
useEffect(() => { useEffect(() => {
fetchProfiles(); fetchProfiles();
@ -48,7 +44,7 @@ useEffect(() => {
<View style={{marginTop: "6%"}}/> <View style={{marginTop: "6%"}}/>
<ProfileModification name={profile.name} avatar={profile.avatar} diets={profile.diets} allergies={profile.allergies}></ProfileModification> <ProfileModification name={profile.name} avatar={profile.avatar} diets={profile.diets} allergies={profile.allergies}></ProfileModification>
<View style={{marginTop: "3%"}}/> <View style={{marginTop: "3%"}}/>
<ValidateButton title="Update Profile" image="update.png" colour={colors.buttonMain} backColour={colors.cardBackground} todo={() => (console.log("Profile Modified"))}></ValidateButton> <ValidateButton title="Update Profile" image="update.png" colour={colors.buttonMain} backColour={colors.cardBackground} todo={() => console.log("")}></ValidateButton>
<View style={{marginTop: "20%"}}/> <View style={{marginTop: "20%"}}/>
</LinearGradient> </LinearGradient>
</ScrollView> </ScrollView>

@ -3,23 +3,21 @@ import { StyleSheet, View, Modal, Pressable, Text, Image, ScrollView, useWindowD
import { LinearGradient } from 'expo-linear-gradient'; import { LinearGradient } from 'expo-linear-gradient';
import { SafeAreaProvider } from 'react-native-safe-area-context'; import { SafeAreaProvider } from 'react-native-safe-area-context';
import ProfileService from '../Services/Profiles/ProfileService';
import ProfileDetails from '../components/ProfileDetails'; import ProfileDetails from '../components/ProfileDetails';
import ColorContext from '../theme/ColorContext'; import ColorContext from '../theme/ColorContext';
import AsyncStorage from '@react-native-async-storage/async-storage'; import eventEmitter from './EventEmitter';
import EventEmitter from './EventEmitter';
import { PaperProvider, Portal } from 'react-native-paper'; import { PaperProvider, Portal } from 'react-native-paper';
export default function Profiles({navigation, props}) { export default function Profiles({navigation, props}) {
const colors = useContext(ColorContext).colors const colors = useContext(ColorContext).colors
const profileService = new ProfileService()
const [visible, setVisible] = useState(false); const [visible, setVisible] = useState(false);
const [profiles, setProfiles] = useState([]); const [profiles, setProfiles] = useState([]);
const [selectedProfileIndex, setSelectedProfileIndex] = useState(null); const [selectedProfileIndex, setSelectedProfileIndex] = useState(null);
const goDetails = (name: string) => navigation.navigate('ProfileCreation', name); const goDetails = (name: string) => navigation.navigate('ProfileCreation', name);
const raisePopUp = (index) => { const raisePopUp = (index) => {
setSelectedProfileIndex(index) setSelectedProfileIndex(index)
setVisible(true) setVisible(true)
@ -30,10 +28,7 @@ export default function Profiles({navigation, props}) {
const handleDeleteProfile = async (index) => { const handleDeleteProfile = async (index) => {
try { try {
const updatedProfiles = profiles.filter((profile, i) => i !== index); profileService.delProfile(index)
await AsyncStorage.setItem('profiles', JSON.stringify(updatedProfiles));
EventEmitter.emit('profileDeleted');
fetchProfiles();
setSelectedProfileIndex(index); setSelectedProfileIndex(index);
erasePopUp(); erasePopUp();
} catch (error) { } catch (error) {
@ -41,23 +36,22 @@ export default function Profiles({navigation, props}) {
} }
}; };
const handleGetProfiles = async () => { const fetchProfiles = async () => {
try { setProfiles(await profileService.getProfiles())
const existingProfiles = await AsyncStorage.getItem('profiles');
return JSON.parse(existingProfiles) || [];
} catch (error) {
console.log("Error occured during GetProfiles", error);
return [];
}
} }
const fetchProfiles = async () => { const subscription = eventEmitter.addListener('profileAdded', async () => {
const existingProfiles = await handleGetProfiles(); fetchProfiles();
setProfiles(existingProfiles); subscription.remove();
}; eventEmitter.removeAllListeners('profileAdded')
eventEmitter.removeAllListeners('profileDeleted')
});
const subscription = EventEmitter.addListener('profileAdded', async () => { const subscriptionDeletedProfile = eventEmitter.addListener('profileDeleted', async () => {
fetchProfiles(); fetchProfiles();
subscriptionDeletedProfile.remove();
eventEmitter.removeAllListeners('profileAdded')
eventEmitter.removeAllListeners('profileDeleted')
}); });
useEffect(() => { useEffect(() => {

@ -102,7 +102,6 @@ export default function RecipeDetails({ route }) {
return categories[0]; return categories[0];
} }
console.log("LA LISTE DES CATEGORY : " + categories)
let bestMatch = { category: '', similarity: 0 }; let bestMatch = { category: '', similarity: 0 };
for (const [name, categoriesList] of Object.entries(categoryMappings)) { for (const [name, categoriesList] of Object.entries(categoryMappings)) {
@ -119,20 +118,15 @@ export default function RecipeDetails({ route }) {
function getImageForRecipe(recipeName: string) { function getImageForRecipe(recipeName: string) {
const categories = []; const categories = [];
console.log("NAAAAAME : " + recipeName)
for (const [category, words] of Object.entries(imagesDictionary)) { for (const [category, words] of Object.entries(imagesDictionary)) {
const matchedWords = words.filter((word) => recipeName.toLowerCase().includes(word)); const matchedWords = words.filter((word) => recipeName.toLowerCase().includes(word));
console.log("Matched Word : " + matchedWords)
if (matchedWords.length > 0) { if (matchedWords.length > 0) {
categories.push(category); categories.push(category);
console.log(category)
} }
} }
console.log("ON ENTRE DANS LA 2EME FONCTION");
const categoryName = getCategoryFromList(categories); const categoryName = getCategoryFromList(categories);
console.log("CategoryName à la fin : " + categoryName);
switch (categoryName) { switch (categoryName) {
case 'meat': case 'meat':
@ -179,10 +173,9 @@ export default function RecipeDetails({ route }) {
const loadRecipe = async () => { const loadRecipe = async () => {
try { try {
const recipe = await recipesService.getRecipeById(recipeId); const recipe = await recipesService.getRecipeById(recipeId);
console.log("Recipe.name: "+recipe.name)
setResponse(recipe); setResponse(recipe);
} catch (error) { } catch (error) {
console.log(error); console.error(error);
} finally{ } finally{
setIsLoading(false) setIsLoading(false)
} }

@ -99,7 +99,7 @@ export default function RecipeSuggestion({ route, navigation }) {
} }
} catch (error) { } catch (error) {
console.log(error) console.error(error)
} }
}; };

Loading…
Cancel
Save