Skip to content

Commit

Permalink
fix: no-conso calculations
Browse files Browse the repository at this point in the history
  • Loading branch information
arnaudambro committed Dec 5, 2024
1 parent 6507d02 commit 50faaa4
Show file tree
Hide file tree
Showing 11 changed files with 104 additions and 109 deletions.
4 changes: 2 additions & 2 deletions expo/app.versions.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"buildNumber": 316,
"buildName": "1.26.7"
"buildNumber": 317,
"buildName": "1.27.0"
}
2 changes: 1 addition & 1 deletion expo/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "oz-ensemble",
"version": "1.26.7",
"version": "1.27.0",
"scripts": {
"get-ip": "./get-ip.sh && echo \"this script updates the API IP to your own IP, because that's what Android Emulator needs to work. It's based on your wifi IP, if you need ethernet it won't work (needs en1 instead of en0)\"",
"start": "expo start --dev-client",
Expand Down
85 changes: 47 additions & 38 deletions expo/src/components/CocktailPersonalisation.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import React, { useRef, useState } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { View, Text, TouchableOpacity, TextInput, Alert, Animated } from 'react-native';
import { useRoute } from '@react-navigation/native';
import { useRecoilState, useSetRecoilState } from 'recoil';
import TextStyled from './TextStyled';
import ArrowDown from './ArrowDown';
import { QuantitySetter } from './DrinkQuantitySetter';
import ButtonPrimary from './ButtonPrimary';
import { drinksState, ownDrinksCatalogState } from '../recoil/consos';
import ModalUpdateSuppressionCocktail from './ModalUpdateSuppressionCocktail';
import { storage } from '../services/storage';
import API from '../services/api';
import AddCocktail from '../scenes/AddDrink/AddCocktail';
import { logEvent } from '../services/logEventsWithMatomo';
import React, { useRef, useState } from "react";
import { v4 as uuidv4 } from "uuid";
import { View, Text, TouchableOpacity, TextInput, Alert, Animated } from "react-native";
import { useRoute } from "@react-navigation/native";
import { useRecoilState, useSetRecoilState } from "recoil";
import TextStyled from "./TextStyled";
import ArrowDown from "./ArrowDown";
import { QuantitySetter } from "./DrinkQuantitySetter";
import ButtonPrimary from "./ButtonPrimary";
import { drinksState, ownDrinksCatalogState } from "../recoil/consos";
import ModalUpdateSuppressionCocktail from "./ModalUpdateSuppressionCocktail";
import { storage } from "../services/storage";
import API from "../services/api";
import AddCocktail from "../scenes/AddDrink/AddCocktail";
import { logEvent } from "../services/logEventsWithMatomo";
import { NO_CONSO } from "../scenes/ConsoFollowUp/drinksCatalog";

const CocktailPersonalisation = ({
updateDrinkKey,
Expand All @@ -34,11 +35,11 @@ const CocktailPersonalisation = ({
(catalogdrink) =>
catalogdrink.drinkKey === updateDrinkKey &&
catalogdrink.isDeleted === false &&
catalogdrink.categoryKey === 'ownCocktail'
catalogdrink.categoryKey === "ownCocktail"
);
const drinkName = cocktailSelected?.name ?? drink?.drinkKey;
const [drinkPrice, setDrinkPrice] = useState(drink?.price ? String(drink?.price) : '');
const drinkVolume = cocktailSelected?.volume ? cocktailSelected?.volume + ' cl' : drink?.volume;
const [drinkPrice, setDrinkPrice] = useState(drink?.price ? String(drink?.price) : "");
const drinkVolume = cocktailSelected?.volume ? cocktailSelected?.volume + " cl" : drink?.volume;
const drinkDoses = cocktailSelected?.doses ?? drink?.doses;
const drinkKcal = cocktailSelected?.kCal ?? drink?.kcal;
const [isUpdateWanted, setIsUpdateWanted] = useState(true);
Expand All @@ -63,26 +64,30 @@ const CocktailPersonalisation = ({
};

const saveDrink = async () => {
const formatedPrice = drinkPrice.replace(',', '.');
const formatedPrice = drinkPrice.replace(",", ".");
const oldDrink =
drink ??
ownDrinksCatalog.find(
(catalogDrink) => catalogDrink.drinkKey === cocktailSelected?.name && catalogDrink.isDeleted === false
(catalogDrink) =>
catalogDrink.drinkKey === cocktailSelected?.name &&
catalogDrink.isDeleted === false &&
drink.drinkKey !== NO_CONSO
) ??
ownDrinksCatalog.find(
(catalogDrink) => catalogDrink.drinkKey === updateDrinkKey && catalogDrink.isDeleted === false
(catalogDrink) =>
catalogDrink.drinkKey === updateDrinkKey && catalogDrink.isDeleted === false && drink.drinkKey !== NO_CONSO
);
if (oldDrink) {
if (!isUpdateWanted) {
const keepGoing = await new Promise((resolve) => {
Alert.alert('Vous avez déjà enregistré ce verre', 'Voulez-vous le remplacer ?', [
Alert.alert("Vous avez déjà enregistré ce verre", "Voulez-vous le remplacer ?", [
{
text: 'Annuler',
text: "Annuler",
onPress: () => resolve(false),
style: 'cancel',
style: "cancel",
},
{
text: 'Remplacer',
text: "Remplacer",
onPress: () => resolve(true),
},
]);
Expand All @@ -93,13 +98,13 @@ const CocktailPersonalisation = ({
return oldState.map((oldStateDrink) =>
oldStateDrink.drinkKey === oldDrink.drinkKey
? {
categoryKey: 'ownCocktail',
categoryKey: "ownCocktail",
drinkKey: drinkName,
displayFeed: drinkName,
displayDrinkModal: drinkName,
volume: drinkVolume,
doses: drinkDoses,
icon: 'CocktailGlass',
icon: "CocktailGlass",
price: Number(formatedPrice),
kcal: drinkKcal,
custom: true,
Expand All @@ -113,9 +118,9 @@ const CocktailPersonalisation = ({
oldStateDrink.drinkKey === oldDrink.drinkKey ? { ...oldStateDrink, drinkKey: drinkName } : oldStateDrink
);
});
const matomoId = storage.getString('@UserIdv2');
const matomoId = storage.getString("@UserIdv2");
await API.post({
path: '/consommation/update-own-conso',
path: "/consommation/update-own-conso",
body: {
matomoId: matomoId,
oldDrinkKey: oldDrink.drinkKey,
Expand All @@ -139,17 +144,17 @@ const CocktailPersonalisation = ({
]);
return;
}
logEvent({ category: 'OWN_CONSO', action: 'CREATE_OWN_COCKTAIL', name: drinkName, value: drinkDoses });
logEvent({ category: "OWN_CONSO", action: "CREATE_OWN_COCKTAIL", name: drinkName, value: drinkDoses });
setOwnDrinksCatalog((oldState) => {
return [
{
categoryKey: 'ownCocktail',
categoryKey: "ownCocktail",
drinkKey: drinkName,
displayFeed: drinkName,
displayDrinkModal: drinkName,
volume: drinkVolume,
doses: drinkDoses,
icon: 'CocktailGlass',
icon: "CocktailGlass",
price: Number(drinkPrice),
kcal: drinkKcal,
custom: true,
Expand Down Expand Up @@ -187,14 +192,16 @@ const CocktailPersonalisation = ({
{!cocktailSelected?.name && !drink ? (
<TouchableOpacity
className="bg-[#f3f3f6] h-14 rounded-lg border border-[#dbdbe9] px-4 my-2 flex flex-row justify-between items-center"
onPress={() => setShowModalAddCocktail(true)}>
onPress={() => setShowModalAddCocktail(true)}
>
<Text className="text-[#CACACD] flex">Sélectionnez un cocktail</Text>
<ArrowDown color="#000000" size={30} strokeWidth={2} />
</TouchableOpacity>
) : (
<TouchableOpacity
className="bg-[#f3f3f6] h-14 rounded-lg border border-[#dbdbe9] px-4 my-2 flex flex-row justify-between items-center"
onPress={() => setShowModalAddCocktail(true)}>
onPress={() => setShowModalAddCocktail(true)}
>
<Text className="text-[#4030A5] flex">{cocktailSelected?.name ?? updateDrinkKey}</Text>
</TouchableOpacity>
)}
Expand Down Expand Up @@ -224,7 +231,7 @@ const CocktailPersonalisation = ({
onPress={() => {
saveDrink();
setCocktailSelected(null);
setSwitchPosition('non');
setSwitchPosition("non");
hide();
}}
disabled={!drinkPrice || !cocktailSelected}
Expand All @@ -243,7 +250,8 @@ const CocktailPersonalisation = ({
onPress={() => {
setIsUpdateWanted(false);
setShowModalUpdate(true);
}}>
}}
>
<Text className="text-[#4030A5] text-center underline text-base mt-4">Supprimer mon cocktail</Text>
</TouchableOpacity>
</View>
Expand All @@ -270,9 +278,10 @@ const CocktailPersonalisation = ({
<Animated.View
style={{ opacity: fadeAnim }}
className="flex flex-row w-screen justify-center absolute -bottom-2"
pointerEvents={'box-none'}>
pointerEvents={"box-none"}
>
<View className="bg-[#4030a5] grow-0 rounded-full mb-4 flex w-min px-4 ">
<TextStyled maxFontSizeMultiplier={2} color={'#FFF'} testID="toast" className="text-center py-2">
<TextStyled maxFontSizeMultiplier={2} color={"#FFF"} testID="toast" className="text-center py-2">
Nouveau cocktail demandé
</TextStyled>
</View>
Expand Down
7 changes: 5 additions & 2 deletions expo/src/components/DrinkPersonalisation.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import API from "../services/api";
import { storage } from "../services/storage";
import AddAlcoolQuantity from "../scenes/AddDrink/AddAlcoolQuantity";
import { logEvent } from "../services/logEventsWithMatomo";
import { NO_CONSO } from "../scenes/ConsoFollowUp/drinksCatalog";

const DrinkPersonalisation = ({ updateDrinkKey, hide, quantitySelected, setQuantitySelected, setLocalDrinksState }) => {
const route = useRoute();
Expand Down Expand Up @@ -50,10 +51,12 @@ const DrinkPersonalisation = ({ updateDrinkKey, hide, quantitySelected, setQuant
const oldDrink =
drink ??
ownDrinksCatalog.find(
(catalogDrink) => catalogDrink.drinkKey === drinkName && catalogDrink.isDeleted === false
(catalogDrink) =>
catalogDrink.drinkKey === drinkName && catalogDrink.isDeleted === false && drink.drinkKey !== NO_CONSO
) ??
ownDrinksCatalog.find(
(catalogDrink) => catalogDrink.drinkKey === updateDrinkKey && catalogDrink.isDeleted === false
(catalogDrink) =>
catalogDrink.drinkKey === updateDrinkKey && catalogDrink.isDeleted === false && drink.drinkKey !== NO_CONSO
);
const kCal = ((formatedAlcoolPercentage * 0.8 * formatedVolume) / 10) * 7;
const doses = Math.round((formatedAlcoolPercentage * 0.8 * formatedVolume) / 10) / 10;
Expand Down
29 changes: 15 additions & 14 deletions expo/src/components/GainsSinceTheBeginning.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@ import { Spacer } from "./Articles";
import H2 from "./H2";
import EuroIcon from "./illustrations/icons/EuroIcon";
import KcalIcon from "./illustrations/icons/KcalIcon";
import {
drinksState,
derivedDataFromDrinksState,
consolidatedCatalogObjectSelector,
} from "../recoil/consos";
import { drinksState, derivedDataFromDrinksState, consolidatedCatalogObjectSelector } from "../recoil/consos";
import dayjs from "dayjs";

const GainSinceTheBeginning = ({ isOnboarded }) => {
Expand All @@ -23,8 +19,7 @@ const GainSinceTheBeginning = ({ isOnboarded }) => {
return dayjs(drinks[drinks.length - 1].timestamp);
}, [drinks]);

const numberOfWeeksSinceBeginning =
Math.abs(dayjs(beginDateOfOz).startOf("week").diff(dayjs(), "weeks")) + 1;
const numberOfWeeksSinceBeginning = Math.abs(dayjs(beginDateOfOz).startOf("week").diff(dayjs(), "weeks")) + 1;
let weeksWithDrinks = 0;
for (let i = 0; i < numberOfWeeksSinceBeginning; i++) {
const startDay = dayjs(beginDateOfOz)
Expand Down Expand Up @@ -62,13 +57,21 @@ const GainSinceTheBeginning = ({ isOnboarded }) => {
);
const mySavingsSinceBeginning = useMemo(() => {
if (!drinks.length) return null;
const myExpensesSinceBegnining = drinks.reduce(
(sum, drink) => sum + drink.quantity * (catalogObject[drink.drinkKey]?.price || 0),
0
);
const myExpensesSinceBegnining = drinks.reduce((sum, drink) => {
console.log({ price: catalogObject[drink.drinkKey]?.price, sum, drink });
return sum + drink.quantity * (catalogObject[drink.drinkKey]?.price || 0);
}, 0);
const result = myWeeklyInitialExpenses * weeksWithDrinks - myExpensesSinceBegnining;
console.log({
myWeeklyInitialExpenses,
weeksWithDrinks,
myExpensesSinceBegnining,
result,
catalogObject: JSON.stringify(catalogObject, null, 2),
});
return Math.round(result * 10) / 10;
}, [drinks, myWeeklyInitialExpenses, weeksWithDrinks, catalogObject]);
console.log({ mySavingsSinceBeginning });

const myKcalSavingsSinceBeginning = useMemo(() => {
if (!drinks.length) return null;
Expand All @@ -91,9 +94,7 @@ const GainSinceTheBeginning = ({ isOnboarded }) => {
</View>
<Spacer size={5} />
{isOnboarded ? (
<Text className="font-bold text-2xl">
{mySavingsSinceBeginning > 0 ? mySavingsSinceBeginning : 0}
</Text>
<Text className="font-bold text-2xl">{mySavingsSinceBeginning > 0 ? mySavingsSinceBeginning : 0}</Text>
) : (
<Text className="font-bold text-2xl">-€</Text>
)}
Expand Down
1 change: 1 addition & 0 deletions expo/src/components/TextStyled.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export default function TextStyled({
.join(" ")}
style={[
styles.text,
color,
underline && {
textDecorationColor: color,
},
Expand Down
29 changes: 12 additions & 17 deletions expo/src/components/WeeklyGains.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ const WeeklyGains = ({ selectedMonth }) => {
[catalogObject, previousDrinksPerWeek]
);

console.log({ weeklyExpenses, myWeeklyInitialExpenses });

const weekInfos = useMemo(() => {
const _weekInfos = [];
const nbWeeks = nbDays / 7;
Expand All @@ -54,30 +56,24 @@ const WeeklyGains = ({ selectedMonth }) => {
}
}
const savedExpenses = hasEnteredDrinks
? Math.round(
Math.abs(
weeklyExpenses[dayjs(startDay).format("YYYY-MM-DD")] - myWeeklyInitialExpenses
) * 10
) / 10
? Math.round(Math.abs(weeklyExpenses[dayjs(startDay).format("YYYY-MM-DD")] - myWeeklyInitialExpenses) * 10) / 10
: 0;
const eurosColor =
weeklyExpenses[dayjs(startDay).format("YYYY-MM-DD")] > myWeeklyInitialExpenses
? "bg-[#FF7979]"
: hasEnteredDrinks
? "bg-[#3AD39D]"
: "bg-[#939EA6]";
? "bg-[#3AD39D]"
: "bg-[#939EA6]";

const savedKcals = hasEnteredDrinks
? Math.round(
Math.abs(weeklyKcals[dayjs(startDay).format("YYYY-MM-DD")] - myWeeklyInitialKCal)
)
? Math.round(Math.abs(weeklyKcals[dayjs(startDay).format("YYYY-MM-DD")] - myWeeklyInitialKCal))
: 0;
const kcalsColor =
weeklyKcals[dayjs(startDay).format("YYYY-MM-DD")] > myWeeklyInitialKCal
? "bg-[#FF7979]"
: hasEnteredDrinks
? "bg-[#3AD39D]"
: "bg-[#939EA6]";
? "bg-[#3AD39D]"
: "bg-[#939EA6]";

_weekInfos[i] = {
startDay: startDay,
Expand Down Expand Up @@ -136,16 +132,14 @@ const WeeklyGains = ({ selectedMonth }) => {
</Text>
</View>
<View className="flex flex-row grow justify-center items-center basis-16">
<View
className={`justify-center rounded-md flex flex-row my-1 py-1 mx-4 grow ${week.eurosColor}`}>
<View className={`justify-center rounded-md flex flex-row my-1 py-1 mx-4 grow ${week.eurosColor}`}>
<Text className=" text-white font-semibold" style={{ fontSize: fontSize }}>
{week.savedExpenses}
</Text>
</View>
</View>
<View className="flex flex-row grow justify-center items-center basis-16">
<View
className={`justify-center rounded-md flex flex-row my-1 py-1 mx-1 grow ${week.kcalsColor}`}>
<View className={`justify-center rounded-md flex flex-row my-1 py-1 mx-1 grow ${week.kcalsColor}`}>
<Text className="text-white font-semibold" style={{ fontSize: fontSize }}>
{week.savedKcals} KCAL
</Text>
Expand All @@ -169,7 +163,8 @@ const WeeklyGains = ({ selectedMonth }) => {
eurosColor: week.eurosColor,
kcalsColor: week.kcalsColor,
});
}}>
}}
>
<Text className="text-white font-semibold" style={{ fontSize: fontSize }}>
Détails
</Text>
Expand Down
4 changes: 3 additions & 1 deletion expo/src/recoil/consos.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import dayjs from "dayjs";
import { atom, selector } from "recoil";
import * as Sentry from "@sentry/react-native";
import { differenceOfDays } from "../helpers/dateHelpers";
import { drinksCatalogObject } from "../scenes/ConsoFollowUp/drinksCatalog";
import { drinksCatalogObject, NO_CONSO } from "../scenes/ConsoFollowUp/drinksCatalog";
import { storage } from "../services/storage";
import { getInitValueFromStorage } from "./utils";
import { goalsByWeekSelector, goalsState } from "./gains";
Expand Down Expand Up @@ -39,6 +39,7 @@ export const ownDrinksCatalogObjectSelector = selector({
const ownDrinks = get(ownDrinksCatalogState);
const ownDrinksCatalogObject = {};
for (const drink of ownDrinks) {
if (drink.drinkKey === NO_CONSO) continue; // bug fix
ownDrinksCatalogObject[drink.drinkKey] = drink;
}
return ownDrinksCatalogObject;
Expand All @@ -51,6 +52,7 @@ export const consolidatedCatalogObjectSelector = selector({
key: "consolidatedCatalogObjectSelector",
get: ({ get }) => {
const ownDrinksObject = get(ownDrinksCatalogObjectSelector);
console.log({ ownDrinksObject: JSON.stringify(ownDrinksObject, null, 2) });
return { ...ownDrinksObject, ...drinksCatalogObject };
},
});
Expand Down
Loading

0 comments on commit 50faaa4

Please sign in to comment.