-
Notifications
You must be signed in to change notification settings - Fork 0
/
page.tsx
355 lines (303 loc) · 13 KB
/
page.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
'use client';
import { useEffect, useState } from "react";
import DayMeals from "../../DayMeals";
import { Day } from "@/model/dayModel";
import { MealProps } from "../../Meal";
import PageLoading from "../../PageLoading";
import { upsertDay, deleteDay, listDays, updateDay } from "@/controllers/days";
import { DateValueType } from "react-tailwindcss-datepicker/dist/types";
import Datepicker from "react-tailwindcss-datepicker";
import { Alert } from "flowbite-react";
import Show from "../../Show";
import DayMacros from "../../DayMacros";
import { MealData } from "@/model/mealModel";
import { MealItemData } from "@/model/mealItemModel";
import { MacroNutrientsData } from "@/model/macroNutrientsModel";
import { useRouter } from "next/navigation";
import MealItemAddModal from "@/app/MealItemAddModal";
import { mockDay, mockFood, mockItem, mockMeal } from "@/app/test/unit/(mock)/mockData";
import { Record } from "pocketbase";
import { hideModal, showModal } from "@/utils/DOMModal";
import UserSelector from "@/app/UserSelector";
import { useUser } from "@/redux/features/userSlice";
import { Loadable } from "@/utils/loadable";
import { getToday, stringToDate } from "@/utils/dateUtils";
import { User } from "@/model/userModel";
export default function Page(context: any) {
const router = useRouter();
const currentUser = useUser();
const selectedDay = context.params.day as string; // TODO: retriggered: type-safe this
const today = getToday();
const showingToday = today === selectedDay;
const [days, setDays] = useState<Loadable<Day[]>>({ loading: true });
const [dayLocked, setDayLocked] = useState(!showingToday);
const [selectedMeal, setSelectedMeal] = useState(mockMeal({ name: 'BUG: selectedMeal not set' }));
const [selectedMealItem, setSelectedMealItem] = useState(mockItem({ quantity: 666 }));
const editModalId = 'edit-modal';
const fetchDays = async (userId: User['id']) => {
const days = await listDays(userId);
setDays({
loading: false,
data: days
});
}
const handleDayChange = (newValue: DateValueType) => {
if (!newValue?.startDate) {
router.push('/day');
return;
}
const dateString = newValue.startDate;
const date = stringToDate(dateString)
const dayString = date.toISOString().split('T')[0]; //TODO: retriggered: use dateUtils when this is understood
router.push(`/day/${dayString}`);
}
useEffect(() => {
if (currentUser.loading) {
return;
}
fetchDays(currentUser.data.id);
}, [currentUser]);
if (currentUser.loading) {
return <PageLoading message="Carregando usuário" />
}
if (days.loading) {
return <PageLoading message="Carregando dias" />
}
const hasData = days.data.some((day) => day.target_day === selectedDay);
const dayData = days.data.find((day) => day.target_day === selectedDay);
const mealProps = dayData?.meals.map((meal) => {
const mealProps: MealProps = {
mealData: meal,
locked: dayLocked,
onEditItem: (mealItem) => {
setSelectedMeal(meal);
setSelectedMealItem(mealItem);
showModal(window, editModalId);
},
onNewItem: () => {
router.push(`/newItem/${selectedDay}/${meal.id}`);
},
onUpdateMeal: async (meal) => {
await updateDay(dayData.id, {
...dayData,
meals: dayData.meals.map((m) => {
if (m.id !== meal.id) {
return m;
}
return meal;
})
});
await fetchDays(currentUser.data.id);
}
};
return mealProps;
});
const mealItemMacros = (mealItem: MealItemData): MacroNutrientsData => {
const macros = mealItem.food.macros;
return {
carbs: macros.carbs * mealItem.quantity / 100,
protein: macros.protein * mealItem.quantity / 100,
fat: macros.fat * mealItem.quantity / 100,
};
};
const mealMacros = (meal: MealData): MacroNutrientsData => {
return meal.items.reduce((acc, item) => {
const itemMacros = mealItemMacros(item);
acc.carbs += itemMacros.carbs;
acc.protein += itemMacros.protein;
acc.fat += itemMacros.fat;
return acc;
}, {
carbs: 0,
protein: 0,
fat: 0,
});
}
const dayMacros = dayData?.meals.reduce((acc, meal): MacroNutrientsData => {
const mm = mealMacros(meal);
acc.carbs += mm.carbs;
acc.protein += mm.protein;
acc.fat += mm.fat;
return acc;
}, {
carbs: 0,
protein: 0,
fat: 0,
});
function CopyLastDayButton() {
//TODO: retriggered: improve this code
if (days.loading || currentUser.loading) return <>LOADING</>
const lastDayIdx = days.data.findLastIndex((day) => Date.parse(day.target_day) < Date.parse(selectedDay));
if (lastDayIdx === -1) {
return (
<button
className="btn btn-error text-white font-bold py-2 px-4 min-w-full rounded mt-3"
onClick={() => alert(`Não foi possível encontrar um dia anterior a ${selectedDay}`)}
>
Copiar dia anterior: não encontrado!
</button>
)
return;
}
return <button
className="btn btn-primary text-white font-bold py-2 px-4 min-w-full rounded mt-3"
onClick={async () => {
if (hasData) {
if (confirm('Tem certeza que deseja excluir este dia e copiar o dia anterior?')) {
await deleteDay(dayData!.id);
}
}
const lastDayIdx = days.data.findLastIndex((day) => Date.parse(day.target_day) < Date.parse(selectedDay));
if (lastDayIdx === -1) {
alert('Não foi possível encontrar um dia anterior');
return;
}
upsertDay({
...days.data[lastDayIdx],
target_day: selectedDay,
id: dayData?.id,
}).then(() => {
fetchDays(currentUser.data.id);
});
}}
>
{/* //TODO: retriggered: copiar qualquer dia */}
Copiar dia anterior ({days.data[lastDayIdx].target_day})
</button>
}
return (
<div className="sm:w-3/4 md:w-4/5 lg:w-1/2 xl:w-1/3 mx-auto">
{/* Top bar with date picker and user icon */}
<div className="bg-slate-900 py-2 flex justify-between items-center gap-4 px-4">
<div className="flex-1">
<Datepicker
asSingle={true}
useRange={false}
readOnly={true}
value={{
startDate: selectedDay,
endDate: selectedDay,
}}
onChange={handleDayChange}
/>
</div>
<div className="flex justify-end">
<UserSelector />
</div>
</div>
<Show when={!selectedDay}>
<Alert className="mt-2" color="warning">Selecione um dia</Alert>
</Show>
<Show when={!!selectedDay && !hasData}>
<Alert className="mt-2" color="warning">Nenhum dado encontrado para o dia {selectedDay}</Alert>
<button
className="btn btn-primary text-white font-bold py-2 px-4 min-w-full rounded mt-3"
onClick={() => {
upsertDay(mockDay({ owner: currentUser.data.id, target_day: selectedDay }, { items: [] })).then(() => {
fetchDays(currentUser.data.id);
});
}}
>
Criar dia do zero
</button>
<CopyLastDayButton />
</Show>
<Show when={!!selectedDay && hasData && !dayData}>
<Alert className="mt-2" color="warning">Dia encontrado, mas sem dados {selectedDay}</Alert>;
</Show>
<Show when={!!selectedDay && hasData && !!dayData && !mealProps}>
<Alert className="mt-2" color="warning">Dia encontrado, mas sem dados de refeições {selectedDay}</Alert>;
</Show>
<Show when={!!selectedDay && hasData && !!dayData && !!mealProps && !dayMacros}>
<Alert className="mt-2" color="warning">Dia encontrado, mas sem dados de macros {selectedDay}</Alert>;
</Show>
<Show when={hasData}>
<MealItemAddModal
modalId={editModalId}
itemData={{
id: selectedMealItem.id,
food: selectedMealItem.food,
quantity: selectedMealItem.quantity,
}}
meal={selectedMeal}
show={false}
onApply={async (item) => {
await updateDay(dayData!.id, {
...dayData!,
meals: dayData!.meals.map((meal) => {
if (meal.id !== selectedMeal.id) {
return meal;
}
const items = meal.items;
const changePos = items.findIndex((i) => i.id === item.id);
items[changePos] = item;
return {
...meal,
items,
};
})
});
await fetchDays(currentUser.data.id);
hideModal(window, editModalId);
}}
onDelete={async (id: MealItemData['id']) => {
await updateDay(dayData!.id, {
...dayData!,
meals: dayData!.meals.map((meal) => {
if (meal.id !== selectedMeal.id) {
return meal;
}
const items = meal.items;
const changePos = items.findIndex((i) => i.id === id);
items.splice(changePos, 1);
return {
...meal,
items,
};
})
});
await fetchDays(currentUser.data.id);
hideModal(window, editModalId);
}}
/>
<DayMacros className="mt-3 border-b-2 border-gray-800 pb-4"
macros={dayMacros!}
/>
<Show when={!showingToday}>
<Alert className="mt-2" color="warning">Mostrando refeições do dia {selectedDay}!</Alert>
<Show when={dayLocked}>
<Alert className="mt-2 outline" color="info">
Hoje é dia <b>{today}</b> <a
className="text-blue-500 font-bold hover:cursor-pointer "
onClick={() => {
router.push('/day/' + today);
}}
>
Mostrar refeições de hoje
</a> ou <a
className="text-red-600 font-bold hover:cursor-pointer "
onClick={() => {
setDayLocked(false);
}}
> Desbloquear dia {selectedDay}</a>
</Alert>
</Show>
</Show>
<DayMeals className="mt-5" mealsProps={mealProps!} />
<CopyLastDayButton />
<button
className="hover:bg-red-400 text-white font-bold py-2 px-4 min-w-full rounded mt-3 btn btn-error"
onClick={async () => {
if (!confirm('Tem certeza que deseja excluir este dia?')) {
return;
}
await deleteDay(dayData!.id);
await fetchDays(currentUser.data.id);
}}
>
PERIGO: Excluir dia
</button>
</Show>
</div>
);
}