fix(vad-ska-vi-ata): ratta 400-bugg (limit 30 > max 20) + kategorier filtrerar in-place
- KRITISKT: what-to-eat-anropet hade limit=30 men schemat tillater max 20 -> 400 Bad Request -> tom sida med 'nagot gick fel'. Det var alltsa INTE uppkopplingen. Andrat till limit=20. - Kategori-flikarna (Frukost/Lunch/Middag/Mellanmal/Efterratt/Baka) filtrerar nu recepten PA SAMMA sida i stallet for att navigera till bladdra-vyn. 'Rekommenderat' visar de personliga forslagen som forut. - ErrorView visar nu riktig HTTP-status (t.ex. [400]) sa fel gar att diagnosa. - '/recipes' finns kvar via 'Alla recept & sok' for full bladdring + sok. Mobil typecheck gron.
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
import { router } from "expo-router";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { api } from "@/lib/api";
|
||||
import { keepPreviousData, useQuery } from "@tanstack/react-query";
|
||||
import { api, ApiError } from "@/lib/api";
|
||||
import { useAnalytics } from "@/lib/analytics";
|
||||
import { recommendationsViewed } from "@app/analytics";
|
||||
import { t } from "@/lib/i18n";
|
||||
@@ -49,42 +49,71 @@ interface WhatToEatResponse {
|
||||
mealBoxSuggestions: MealBoxSuggestion[];
|
||||
context: { activeHolidays: string[]; remainingKcal: number; remainingProteinG: number };
|
||||
}
|
||||
interface BrowseRecipe {
|
||||
id: string;
|
||||
titleSv: string;
|
||||
title?: string;
|
||||
totalTimeMinutes: number | null;
|
||||
nutritionPerPortion: { kcal?: number } | null;
|
||||
ratingAverage: number | null;
|
||||
ratingCount: number;
|
||||
}
|
||||
|
||||
// Bläddra-genvägar direkt på förstasidan (öppnar recept-bläddraren förvald på
|
||||
// kategorin). Etiketter återanvänder myday.mealType.* där de finns.
|
||||
const BROWSE_CATS: ReadonlyArray<{
|
||||
// Kategori-flikar direkt på förstasidan. null = personliga rekommendationer;
|
||||
// annars filtreras recepten IN-PLACE på samma sida (ingen navigering bort).
|
||||
// De flesta filtrerar på måltidstyp; "Baka" på taggen "baking".
|
||||
const CATS: ReadonlyArray<{
|
||||
key: string;
|
||||
labelKey: string | null;
|
||||
label?: string;
|
||||
mealType?: string;
|
||||
tag?: string;
|
||||
glyph: string;
|
||||
}> = [
|
||||
{ key: "breakfast", labelKey: "myday.mealType.breakfast", glyph: "🥣" },
|
||||
{ key: "lunch", labelKey: "myday.mealType.lunch", glyph: "🥗" },
|
||||
{ key: "dinner", labelKey: "myday.mealType.dinner", glyph: "🍽️" },
|
||||
{ key: "snack", labelKey: "myday.mealType.snack", glyph: "🍎" },
|
||||
{ key: "dessert", labelKey: "myday.mealType.dessert", glyph: "🍰" },
|
||||
{ key: "baking", labelKey: null, label: "Baka", glyph: "🥐" },
|
||||
{ key: "breakfast", labelKey: "myday.mealType.breakfast", mealType: "breakfast", glyph: "🥣" },
|
||||
{ key: "lunch", labelKey: "myday.mealType.lunch", mealType: "lunch", glyph: "🥗" },
|
||||
{ key: "dinner", labelKey: "myday.mealType.dinner", mealType: "dinner", glyph: "🍽️" },
|
||||
{ key: "snack", labelKey: "myday.mealType.snack", mealType: "snack", glyph: "🍎" },
|
||||
{ key: "dessert", labelKey: "myday.mealType.dessert", mealType: "dessert", glyph: "🍰" },
|
||||
{ key: "baking", labelKey: null, label: "Baka", tag: "baking", glyph: "🥐" },
|
||||
];
|
||||
|
||||
const errText = (e: unknown): string | undefined =>
|
||||
e instanceof ApiError ? `[${e.status}] ${e.message}` : e instanceof Error ? e.message : undefined;
|
||||
|
||||
export default function WhatToEatScreen() {
|
||||
const [craving, setCraving] = useState("");
|
||||
const [submittedCraving, setSubmittedCraving] = useState("");
|
||||
const [page, setPage] = useState(0);
|
||||
const [cat, setCat] = useState<string | null>(null); // null = Rekommenderat
|
||||
const { track } = useAnalytics();
|
||||
|
||||
const hour = new Date().getHours();
|
||||
const currentMeal = hour < 10 ? "breakfast" : hour < 14 ? "lunch" : "dinner";
|
||||
|
||||
// view=default ger en balanserad rankning (täckning väger tungt men inte
|
||||
// allenarådande som i pantry-vyn) → mer varierade, relevanta förslag i stället
|
||||
// för samma triviala högtäckningsrätter. Större pool (30) så "Visa fler"
|
||||
// bläddrar längre innan den upprepar.
|
||||
// Personliga rekommendationer (bara i "Rekommenderat"-läget). view=default ger
|
||||
// en balanserad rankning; limit=20 är schemats maxgräns.
|
||||
const query = useQuery({
|
||||
queryKey: ["what-to-eat", submittedCraving, currentMeal],
|
||||
queryFn: () =>
|
||||
api<WhatToEatResponse>(
|
||||
`/v1/recommendations/what-to-eat?limit=30&view=default&mealType=${currentMeal}${submittedCraving ? `&craving=${encodeURIComponent(submittedCraving)}` : ""}`,
|
||||
`/v1/recommendations/what-to-eat?limit=20&view=default&mealType=${currentMeal}${submittedCraving ? `&craving=${encodeURIComponent(submittedCraving)}` : ""}`,
|
||||
),
|
||||
enabled: cat === null,
|
||||
});
|
||||
|
||||
// Kategori-bläddring in-place (när en flik är vald).
|
||||
const browse = useQuery({
|
||||
queryKey: ["wte-browse", cat],
|
||||
queryFn: () => {
|
||||
const c = CATS.find((x) => x.key === cat);
|
||||
let path = "/v1/recipes?limit=50";
|
||||
if (c?.mealType) path += `&mealType=${c.mealType}`;
|
||||
if (c?.tag) path += `&tags=${c.tag}`;
|
||||
return api<{ recipes: BrowseRecipe[] }>(path);
|
||||
},
|
||||
enabled: cat !== null,
|
||||
placeholderData: keepPreviousData,
|
||||
});
|
||||
|
||||
const allRecs = query.data?.recommendations ?? [];
|
||||
@@ -115,125 +144,174 @@ export default function WhatToEatScreen() {
|
||||
<Small>{t("wte.subtitle")}</Small>
|
||||
<Spacer size={spacing.sm} />
|
||||
|
||||
<Row>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Input
|
||||
placeholder={t("wte.cravingPlaceholder")}
|
||||
value={craving}
|
||||
onChangeText={setCraving}
|
||||
onSubmitEditing={() => {
|
||||
setSubmittedCraving(craving);
|
||||
setPage(0);
|
||||
}}
|
||||
returnKeyType="search"
|
||||
/>
|
||||
</View>
|
||||
</Row>
|
||||
<Spacer size={spacing.sm} />
|
||||
|
||||
{/* Bläddra bland recept per kategori direkt från förstasidan. */}
|
||||
{/* Kategori-flikar – filtrerar på DENNA sida, ingen navigering bort. */}
|
||||
<Row style={{ flexWrap: "wrap" }}>
|
||||
{BROWSE_CATS.map((c) => (
|
||||
<Button
|
||||
label="🍽️ Rekommenderat"
|
||||
variant={cat === null ? "secondary" : "ghost"}
|
||||
onPress={() => setCat(null)}
|
||||
/>
|
||||
{CATS.map((c) => (
|
||||
<Button
|
||||
key={c.key}
|
||||
label={`${c.glyph} ${c.labelKey ? t(c.labelKey as never) : (c.label ?? "")}`}
|
||||
variant="ghost"
|
||||
onPress={() => router.push(`/recipes?cat=${c.key}`)}
|
||||
variant={cat === c.key ? "secondary" : "ghost"}
|
||||
onPress={() => setCat(c.key)}
|
||||
/>
|
||||
))}
|
||||
<Button label="Alla recept" variant="secondary" onPress={() => router.push("/recipes")} />
|
||||
</Row>
|
||||
<Pressable onPress={() => router.push("/recipes")}>
|
||||
<Small style={{ color: colors.primary }}>🔍 Alla recept & sök</Small>
|
||||
</Pressable>
|
||||
<Spacer size={spacing.sm} />
|
||||
|
||||
{query.isLoading && <LoadingView />}
|
||||
{query.isError && <ErrorView onRetry={() => void query.refetch()} />}
|
||||
|
||||
{query.data && (
|
||||
{cat === null ? (
|
||||
// --- Rekommenderat-läge ---
|
||||
<>
|
||||
{query.data.context.activeHolidays.length > 0 && (
|
||||
<Row style={{ flexWrap: "wrap" }}>
|
||||
{query.data.context.activeHolidays.map((holiday) => (
|
||||
<Pressable
|
||||
key={holiday}
|
||||
onPress={() => {
|
||||
setCraving(holiday);
|
||||
setSubmittedCraving(holiday);
|
||||
setPage(0);
|
||||
}}
|
||||
>
|
||||
<Tag label={`🎉 ${holiday}`} tone="accent" />
|
||||
</Pressable>
|
||||
))}
|
||||
</Row>
|
||||
<Row>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Input
|
||||
placeholder={t("wte.cravingPlaceholder")}
|
||||
value={craving}
|
||||
onChangeText={setCraving}
|
||||
onSubmitEditing={() => {
|
||||
setSubmittedCraving(craving);
|
||||
setPage(0);
|
||||
}}
|
||||
returnKeyType="search"
|
||||
/>
|
||||
</View>
|
||||
</Row>
|
||||
<Spacer size={spacing.sm} />
|
||||
|
||||
{query.isLoading && <LoadingView />}
|
||||
{query.isError && (
|
||||
<ErrorView message={errText(query.error)} onRetry={() => void query.refetch()} />
|
||||
)}
|
||||
|
||||
{query.data.mealBoxSuggestions.length > 0 && (
|
||||
{query.data && (
|
||||
<>
|
||||
<Heading>{t("wte.mealBoxFirst")}</Heading>
|
||||
{query.data.mealBoxSuggestions.map((box) => (
|
||||
<Card key={box.mealBoxId} onPress={() => router.push("/meal-boxes")}>
|
||||
<Row style={{ justifyContent: "space-between" }}>
|
||||
<Body>🍱 {box.titleSv}</Body>
|
||||
<Tag
|
||||
label={t("mealbox.portionsLeft", { count: box.portionsRemaining })}
|
||||
tone="success"
|
||||
/>
|
||||
{query.data.context.activeHolidays.length > 0 && (
|
||||
<Row style={{ flexWrap: "wrap" }}>
|
||||
{query.data.context.activeHolidays.map((holiday) => (
|
||||
<Pressable
|
||||
key={holiday}
|
||||
onPress={() => {
|
||||
setCraving(holiday);
|
||||
setSubmittedCraving(holiday);
|
||||
setPage(0);
|
||||
}}
|
||||
>
|
||||
<Tag label={`🎉 ${holiday}`} tone="accent" />
|
||||
</Pressable>
|
||||
))}
|
||||
</Row>
|
||||
)}
|
||||
|
||||
{query.data.mealBoxSuggestions.length > 0 && (
|
||||
<>
|
||||
<Heading>{t("wte.mealBoxFirst")}</Heading>
|
||||
{query.data.mealBoxSuggestions.map((box) => (
|
||||
<Card key={box.mealBoxId} onPress={() => router.push("/meal-boxes")}>
|
||||
<Row style={{ justifyContent: "space-between" }}>
|
||||
<Body>🍱 {box.titleSv}</Body>
|
||||
<Tag
|
||||
label={t("mealbox.portionsLeft", { count: box.portionsRemaining })}
|
||||
tone="success"
|
||||
/>
|
||||
</Row>
|
||||
<Small>{box.whySv}</Small>
|
||||
</Card>
|
||||
))}
|
||||
<Spacer size={spacing.sm} />
|
||||
</>
|
||||
)}
|
||||
|
||||
{allRecs.length === 0 && <EmptyState text={t("wte.empty")} />}
|
||||
|
||||
{shownRecs.map((rec, index) => (
|
||||
<Card key={rec.recipeId} onPress={() => router.push(`/recipe/${rec.recipeId}`)}>
|
||||
<Row style={{ justifyContent: "space-between", alignItems: "center" }}>
|
||||
<Heading>{rec.titleSv}</Heading>
|
||||
{index === 0 && <Tag label="Toppval" tone="accent" />}
|
||||
</Row>
|
||||
<Small>{box.whySv}</Small>
|
||||
<Row>
|
||||
{rec.ratingCount > 0 && rec.ratingAverage != null && (
|
||||
<Tag
|
||||
label={`★ ${rec.ratingAverage.toFixed(1).replace(".", ",")} · ${rec.ratingCount}`}
|
||||
tone="accent"
|
||||
/>
|
||||
)}
|
||||
<Tag
|
||||
label={t("wte.coverage", { pct: rec.coveragePercent })}
|
||||
tone={rec.coveragePercent >= 80 ? "success" : "neutral"}
|
||||
/>
|
||||
{rec.usesExpiring.slice(0, 2).map((item) => (
|
||||
<Tag key={item.nameSv} label={`⏳ ${item.nameSv}`} tone="warning" />
|
||||
))}
|
||||
</Row>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: colors.surfaceAlt,
|
||||
borderRadius: 10,
|
||||
padding: spacing.sm,
|
||||
marginTop: spacing.xs,
|
||||
}}
|
||||
>
|
||||
<Small>💡 {rec.whySv}</Small>
|
||||
</View>
|
||||
{rec.missingIngredients.length > 0 && (
|
||||
<Small>
|
||||
{t("wte.missing", { items: rec.missingIngredients.slice(0, 4).join(", ") })}
|
||||
</Small>
|
||||
)}
|
||||
</Card>
|
||||
))}
|
||||
|
||||
<Spacer size={spacing.sm} />
|
||||
<Button
|
||||
label={t("wte.refresh")}
|
||||
variant="secondary"
|
||||
loading={query.isFetching}
|
||||
onPress={() => setPage((p) => p + 1)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{allRecs.length === 0 && <EmptyState text={t("wte.empty")} />}
|
||||
|
||||
{shownRecs.map((rec, index) => (
|
||||
<Card key={rec.recipeId} onPress={() => router.push(`/recipe/${rec.recipeId}`)}>
|
||||
<Row style={{ justifyContent: "space-between", alignItems: "center" }}>
|
||||
<Heading>{rec.titleSv}</Heading>
|
||||
{index === 0 && <Tag label="Toppval" tone="accent" />}
|
||||
</Row>
|
||||
<Row>
|
||||
{rec.ratingCount > 0 && rec.ratingAverage != null && (
|
||||
<Tag
|
||||
label={`★ ${rec.ratingAverage.toFixed(1).replace(".", ",")} · ${rec.ratingCount}`}
|
||||
tone="accent"
|
||||
/>
|
||||
)}
|
||||
<Tag
|
||||
label={t("wte.coverage", { pct: rec.coveragePercent })}
|
||||
tone={rec.coveragePercent >= 80 ? "success" : "neutral"}
|
||||
/>
|
||||
{rec.usesExpiring.slice(0, 2).map((item) => (
|
||||
<Tag key={item.nameSv} label={`⏳ ${item.nameSv}`} tone="warning" />
|
||||
))}
|
||||
</Row>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: colors.surfaceAlt,
|
||||
borderRadius: 10,
|
||||
padding: spacing.sm,
|
||||
marginTop: spacing.xs,
|
||||
}}
|
||||
>
|
||||
<Small>💡 {rec.whySv}</Small>
|
||||
</View>
|
||||
{rec.missingIngredients.length > 0 && (
|
||||
<Small>
|
||||
{t("wte.missing", { items: rec.missingIngredients.slice(0, 4).join(", ") })}
|
||||
</Small>
|
||||
)}
|
||||
</Card>
|
||||
))}
|
||||
|
||||
<Spacer size={spacing.sm} />
|
||||
<Button
|
||||
label={t("wte.refresh")}
|
||||
variant="secondary"
|
||||
loading={query.isFetching}
|
||||
onPress={() => setPage((p) => p + 1)}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
// --- Kategori-läge (recept filtrerade in-place) ---
|
||||
<>
|
||||
{browse.isLoading && <LoadingView />}
|
||||
{browse.isError && (
|
||||
<ErrorView message={errText(browse.error)} onRetry={() => void browse.refetch()} />
|
||||
)}
|
||||
{browse.data &&
|
||||
(browse.data.recipes.length === 0 ? (
|
||||
<EmptyState text="Inga recept i den här kategorin än." />
|
||||
) : (
|
||||
browse.data.recipes.map((r) => (
|
||||
<Card
|
||||
key={r.id}
|
||||
onPress={() => router.push(`/recipe/${r.id}`)}
|
||||
style={{ gap: spacing.xs }}
|
||||
>
|
||||
<Heading>{r.title ?? r.titleSv}</Heading>
|
||||
<Small>
|
||||
{[
|
||||
r.totalTimeMinutes != null ? `${r.totalTimeMinutes} min` : null,
|
||||
r.nutritionPerPortion?.kcal != null
|
||||
? `${Math.round(r.nutritionPerPortion.kcal)} kcal`
|
||||
: null,
|
||||
r.ratingCount > 0 && r.ratingAverage != null
|
||||
? `★ ${r.ratingAverage.toFixed(1).replace(".", ",")}`
|
||||
: null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
</Small>
|
||||
</Card>
|
||||
))
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</Screen>
|
||||
|
||||
Reference in New Issue
Block a user