Skip to content

Commit

Permalink
Merge pull request #12 from marcuscastelo/improvement/#11-supabase-se…
Browse files Browse the repository at this point in the history
…arch

Improvement/#11 supabase search
  • Loading branch information
marcuscastelo committed Jul 29, 2023
2 parents 82fbe66 + 326c1af commit 03255fa
Show file tree
Hide file tree
Showing 29 changed files with 84 additions and 77 deletions.
2 changes: 1 addition & 1 deletion app/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { listUsers } from '@/controllers/users';
import { User } from '@/model/userModel';

export default function App({ children }: { children: React.ReactNode }) {
//TODO: useUser hook (all over the entire app. Search for useAppDispatch, useAppSelector and dispatch)
//TODO: retriggered: useUser hook (all over the entire app. Search for useAppDispatch, useAppSelector and dispatch)
const dispatch = useAppDispatch();
const onChangeUser = (user: User) => dispatch(setUserJson(JSON.stringify(user)));
listUsers().then(users => {
Expand Down
4 changes: 2 additions & 2 deletions app/BarCodeInsertModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ export default function BarCodeInsertModal({ modalId, show, onSelect }: BarCodeI
<BarCodeSearch onFoodChange={setFood} />

<div className="modal-action">
{/* //TODO: make buttons work */}
{/* //TODO: retriggered: make buttons work */}
{/* if there is a button in form, it will close the modal */}
<button className="btn" onClick={(e) => {
e.preventDefault();
hideModal(window, modalId); // TODO: remove this and use state/modal component
hideModal(window, modalId); // TODO: retriggered: remove this and use state/modal component
}} >
Cancelar
</button>
Expand Down
2 changes: 1 addition & 1 deletion app/BarCodeSearch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export default function BarCodeSearch(
<p className="text-sm">

<MealItem mealItem={{
id: Math.round(Math.random() * 1000000), // TODO: properly generate id
id: Math.round(Math.random() * 1000000), // TODO: retriggered: properly generate id
food: currentFood,
quantity: 100,
}}
Expand Down
6 changes: 3 additions & 3 deletions app/MacroTargets.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export type MacroRepresentation = {
calorieMultiplier: number,
}

//TODO: should not be exported (move to other module)
//TODO: retriggered: should not be exported (move to other module)
export const calculateMacroTarget = (
weight: number,
savedMacroTarget: MacroProfile
Expand All @@ -36,7 +36,7 @@ export const calculateMacroTarget = (
fat: weight * savedMacroTarget.gramsPerKgFat,
});

//TODO: should not be exported (move to other module)
//TODO: retriggered: should not be exported (move to other module)
export const calculateCalories = (targetGrams: TargetGrams): number => (
targetGrams.carbs * 4 + targetGrams.protein * 4 + targetGrams.fat * 9
);
Expand Down Expand Up @@ -135,7 +135,7 @@ export default function MacroTarget({
id="default-search"
className="block text-center w-full p-2 pl-10 text-md bg-gray-700 border-gray-600 placeholder-gray-400 text-white focus:ring-blue-500 focus:border-blue-500 italic font-thin"
placeholder="Insira a meta de calorias diárias"
disabled={true} // TODO: future feature
disabled={true} // TODO: retriggered: future feature
required
/>

Expand Down
2 changes: 1 addition & 1 deletion app/Meal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export type MealProps = {
locked?: boolean,
};

//TODO: move this function
//TODO: retriggered: move this function
// a little function to help us with reordering the result
const reorder = (list: unknown[], startIndex: number, endIndex: number) => {
const result = Array.from(list);
Expand Down
4 changes: 2 additions & 2 deletions app/MealItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,14 @@ export default function MealItem(props: MealItemProps) {
mealItem.classList.add('bg-gray-700');
});

//TODO: reorder meal items (and move across meals)
//TODO: retriggered: reorder meal items (and move across meals)
e.dataTransfer.setData("text/plain", JSON.stringify(props.mealItem));
}}
>
<div className={`meal-item block p-3 bg-gray-700 border border-gray-700 rounded-lg shadow hover:bg-gray-700 hover:cursor-pointer ${props.className ?? ''}`} onClick={onClick}>
<div className="flex">
<div className="">
{/* //TODO: mealItem id is random, but it should be an entry on the database (meal too) */}
{/* //TODO: retriggered: mealItem id is random, but it should be an entry on the database (meal too) */}
{/* <h5 className="mb-2 text-lg font-bold tracking-tight text-white">ID: [{props.mealItem.id}]</h5> */}
<h5 className="mb-2 text-lg font-bold tracking-tight text-white">{props.mealItem.food.name} </h5>
</div>
Expand Down
2 changes: 1 addition & 1 deletion app/MealItemAddModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ export default function MealItemAddModal({
<button className="btn" onClick={(e) => {
e.preventDefault();
setShow(false);
hideModal(window, modalId); //TODO: remove this and use react state
hideModal(window, modalId); //TODO: retriggered: remove this and use react state
onCancel?.()
}} >
Cancelar
Expand Down
2 changes: 1 addition & 1 deletion app/api/barcode/[ean]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const searchBarCodeInternal = async (barcode: string) => {
console.log(response.data);
console.dir(response.data);
return apiFoodSchema.parse(response.data);
//TODO cache this
//TODO: retriggered cache this
}

export async function GET(request: NextRequest, {params} : {params: {ean: string}}) {
Expand Down
2 changes: 0 additions & 2 deletions app/api/food/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ export const searchFoodNameInternal = async (food: string) => {
search: food
}
});
console.log(response.data);
console.dir(response.data);

return response.data;
}
8 changes: 4 additions & 4 deletions app/day/[day]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export default function Page(context: any) {

const currentUser = useUser();

const selectedDay = context.params.day as string; // TODO: type-safe this
const selectedDay = context.params.day as string; // TODO: retriggered: type-safe this
const today = getToday();
const showingToday = today === selectedDay;

Expand Down Expand Up @@ -58,7 +58,7 @@ export default function Page(context: any) {

const dateString = newValue.startDate;
const date = stringToDate(dateString)
const dayString = date.toISOString().split('T')[0]; //TODO: use dateUtils when this is understood
const dayString = date.toISOString().split('T')[0]; //TODO: retriggered: use dateUtils when this is understood
router.push(`/day/${dayString}`);
}

Expand Down Expand Up @@ -148,7 +148,7 @@ export default function Page(context: any) {
});

function CopyLastDayButton() {
//TODO: improve this code
//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));
Expand Down Expand Up @@ -188,7 +188,7 @@ export default function Page(context: any) {
});
}}
>
{/* //TODO: copiar qualquer dia */}
{/* //TODO: retriggered: copiar qualquer dia */}
Copiar dia anterior ({days.data[lastDayIdx].target_day})
</button>
}
Expand Down
28 changes: 16 additions & 12 deletions app/newItem/[date]/[mealId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export default function Page(context: any) {
const FOOD_LIMIT = 100;
const TYPE_TIMEOUT = 1000;

const dayParam = context.params.date as string; // TODO: type-safe this
const dayParam = context.params.date as string; // TODO: retriggered: type-safe this

const dispatch = useAppDispatch();
const currentUser = useUser();
Expand All @@ -38,7 +38,8 @@ export default function Page(context: any) {
const [foods, setFoods] = useState<Loadable<(Food)[]>>({ loading: true });
const [days, setDays] = useState<Loadable<Day[]>>({ loading: true });
const [selectedFood, setSelectedFood] = useState(mockFood({ name: 'BUG: SELECTED FOOD NOT SET' }));
const [searchingFoods, setSearchingFoods] = useState(false);
// const [searchingFoods, setSearchingFoods] = useState(false);
const searchingFoods = false;
const [typing, setTyping] = useState(false);

const [isClient, setIsClient] = useState(false)
Expand All @@ -48,17 +49,19 @@ export default function Page(context: any) {
const isFoodFavorite = useIsFoodFavorite();

const fetchFoods = async (search: string | '', favoriteFoods: number[]) => {
if (!(await isCached(search))) {
setSearchingFoods(true);
}
// if (!(await isCached(search))) {
// setSearchingFoods(true);
// }

let foods: Food[] = [];
if (search == '') {
foods = await listFoods(); // TODO: add limit when search is made on backend
} else {
foods = await searchFoods(search); // TODO: add limit when search is made on backend
}
setSearchingFoods(false);
// if (search == '') {
// foods = await listFoods(); // TODO: retriggered: add limit when search is made on backend
// } else {
// foods = await searchFoods(search); // TODO: retriggered: add limit when search is made on backend
// }
foods = await searchFoods(search); // TODO: retriggered: add limit when search is made on backend

// setSearchingFoods(false);

const isFavorite = (favoriteFoods: number[], food: Food) => {
return favoriteFoods.includes(food.id);
Expand Down Expand Up @@ -234,7 +237,8 @@ export default function Page(context: any) {
required
/>
</div>


{/* TODO: fix 'Nenhum alimento encontrado para a busca' being showed while still searching */}
{!searchingFoods && !typing && filteredFoods.length == 0 && <Alert color="warning" className="mt-2">Nenhum alimento encontrado para a busca &quot;{search}&quot;.</Alert>}

<MealItemAddModal modalId={MEAL_ITEM_ADD_MODAL_ID} meal={meal} itemData={{
Expand Down
2 changes: 1 addition & 1 deletion app/profile/edit/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ function UserField({
value={user.data[fieldName].toString()}
onChange={
(e) => setUser((old: Loadable<User>) => {
//TODO: favoritedFoods will error string cannot be assigned to number
//TODO: retriggered: favoritedFoods will error string cannot be assigned to number
return old.loading ? old : {
loading: false,
data: {
Expand Down
4 changes: 2 additions & 2 deletions app/test/api/daymealswithpicker/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import Datepicker from "react-tailwindcss-datepicker";
import { DateValueType } from "react-tailwindcss-datepicker/dist/types";

export default function Page() {
const [days, setDays] = useState<Day[]>([]); // TODO: remove Record when id is not optional
const [days, setDays] = useState<Day[]>([]); // TODO: retriggered: remove Record when id is not optional
const [mealProps, setMealProps] = useState<MealProps[][]>([]);

const [selectedDay, setSelectedDay] = useState('');
Expand Down Expand Up @@ -46,7 +46,7 @@ export default function Page() {

const dateString = newValue?.startDate;
const date = stringToDate(dateString);
setSelectedDay(date.toISOString().split('T')[0]); // TODO: use dateUtils when this is understood
setSelectedDay(date.toISOString().split('T')[0]); // TODO: retriggered: use dateUtils when this is understood
}

useEffect(() => {
Expand Down
2 changes: 1 addition & 1 deletion app/test/api/foods/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export default function Page() {
food: food,
quantity: 100,
}}
favorite={false} // TODO: implement favorite
favorite={false} // TODO: retriggered: implement favorite
/>
</div>
)
Expand Down
2 changes: 1 addition & 1 deletion app/test/api/newmealitemsearch/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export default function Page() {
food: food,
quantity: 100,
}}
favorite={false} // TODO: implement favorite
favorite={false} // TODO: retriggered: implement favorite
/>
</div>
)
Expand Down
2 changes: 1 addition & 1 deletion app/test/unit/macrotarget/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export default function Page() {
id="default-search"
className="block text-center w-full p-2 pl-10 text-md bg-gray-700 border-gray-600 placeholder-gray-400 text-white focus:ring-blue-500 focus:border-blue-500 italic font-thin"
placeholder="Insira a meta de calorias diárias"
disabled={true} // TODO: future feature
disabled={true} // TODO: retriggered: future feature
required
/>

Expand Down
2 changes: 1 addition & 1 deletion app/test/unit/mealitem/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { mockItem } from "../(mock)/mockData";
export default function MealItemPage() {
return (
<MealItem mealItem={mockItem()}
favorite='hide' // TODO: implement favorite?
favorite='hide' // TODO: retriggered: implement favorite?
/>
)
}
2 changes: 1 addition & 1 deletion app/test/unit/newmealitemsearch/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export default function Page() {
food: food,
quantity: 100,
}}
favorite='hide' // TODO: implement favorite?
favorite='hide' // TODO: retriggered: implement favorite?

/>
</div>
Expand Down
2 changes: 1 addition & 1 deletion controllers/barcodes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ import { apiFoodSchema } from '@/model/apiFoodModel';
import { INTERNAL_API } from '@/utils/api';

export const searchBarCode = async (barcode: string) => {
//TODO: this url should not be hardcoded
//TODO: retriggered: this url should not be hardcoded
return apiFoodSchema.parse((await INTERNAL_API.get(`barcode/${barcode}`)).data);
}
12 changes: 6 additions & 6 deletions controllers/days.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import supabase from '@/utils/supabase';

const TABLE = 'days';

//TODO: tratar erros (também no resto dos controllers)
//TODO: retriggered: tratar erros (também no resto dos controllers)
export const listDays = async (userId: User['id']): Promise<Day[]> =>
((await supabase.from(TABLE).select('*')).data ?? [])
((await supabase.from(TABLE).select()).data ?? [])
.map(day => daySchema.parse(day))
.filter((day) => day.owner === userId)
.map((day): Day => ({
Expand All @@ -20,7 +20,7 @@ export const upsertDay = async (day: Partial<Day> & Omit<Day, 'id'>): Promise<Da
const { data: days, error } = await supabase.
from(TABLE)
.upsert(day)
.select('*');
.select();
if (error) {
throw error;
}
Expand All @@ -32,7 +32,7 @@ export const updateDay = async (id: Day['id'], day: Day): Promise<Day> => {
.from(TABLE)
.update(day)
.eq('id', id)
.select('*');
.select();

if (error) {
throw error;
Expand All @@ -41,13 +41,13 @@ export const updateDay = async (id: Day['id'], day: Day): Promise<Day> => {
return daySchema.parse(data?.[0] ?? null)
}

//TODO: add boolean to check on usages of this function
//TODO: retriggered: add boolean to check on usages of this function
export const deleteDay = async (id: Day['id']): Promise<void> => {
const { error } = await supabase
.from(TABLE)
.delete()
.eq('id', id)
.select('*');
.select();

if (error) {
throw error;
Expand Down
Loading

0 comments on commit 03255fa

Please sign in to comment.