Skip to content

Feat: show top 5 incredients as options#152

Open
EdenBernhard wants to merge 16 commits intoblatt17from
feat/show-top-5-incredients-as-options
Open

Feat: show top 5 incredients as options#152
EdenBernhard wants to merge 16 commits intoblatt17from
feat/show-top-5-incredients-as-options

Conversation

@EdenBernhard
Copy link
Copy Markdown
Collaborator

No description provided.

EdenBernhard and others added 14 commits May 5, 2026 16:25
# Conflicts:
#	project/backend/Database.py
#	project/backend/EmailService.py
#	project/backend/Routes.py
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
# Conflicts:
#	project/backend/Routes.py
#	project/frontend/app/components/fields.tsx
#	project/frontend/app/homepage/forgotPassword.tsx
#	project/frontend/app/profile/changePasswordPopup.tsx
#	project/frontend/app/profile/page.tsx
#	project/frontend/lib/auth.tsx
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds “top 5 ingredients” suggestions to the RecipeFinder ingredient popup by introducing backend usage tracking + endpoints, and wiring the frontend to fetch/cache and render suggestion badges. It also includes a few auth/network UX improvements (more specific login/forgot-password errors) and some auth/DB-related adjustments.

Changes:

  • Frontend: show “Häufig verwendet” suggestion badges in the ingredient popup and persist suggestions in localStorage.
  • Backend: track per-user ingredient usage, expose /ingredients/top, and return updated topIngredients from /recipes/search.
  • UX: improved error messaging for sign-in and forgot-password; small accessibility improvements in password input.

Reviewed changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
project/frontend/lib/auth.tsx Clears suggestion cache on logout and changes fetchWithAuth URL handling.
project/frontend/app/recipeFinder/style.css Adds styling for the suggestion badge list.
project/frontend/app/recipeFinder/popup.tsx Renders clickable suggestion badges and focuses amount input after selection.
project/frontend/app/recipeFinder/page.tsx Fetches/caches suggestions and passes them into the popup; updates suggestions from search response.
project/frontend/app/profile/page.tsx Minor cleanup and small UI handler edit.
project/frontend/app/profile/changePasswordPopup.tsx Adds aria attributes and strengthens required-field validation.
project/frontend/app/homepage/signin.tsx Improves error classification for login failures.
project/frontend/app/homepage/forgotPassword.tsx Adds proper non-OK response handling and displays server/network errors.
project/backend/Routes.py Adds /recipes/search usage tracking + /ingredients/top endpoint with no-cache headers.
project/backend/Models.py Adds request models for recipe search payload.
project/backend/Database.py Adds IngredientUsage table + read/write helpers; removes WAL pragma.
project/backend/Auth.py Introduces duplicate imports/constants (needs cleanup).
Comments suppressed due to low confidence (1)

project/frontend/lib/auth.tsx:139

  • fetchWithAuth now prefixes API_URL only for the first request, but the 401 retry still calls fetch(url, ...) without the prefix. This will break token-refresh flows for relative paths (it will hit the Next.js origin) and also breaks existing callers that pass absolute URLs (they’ll get API_URL + 'http…'). Consider normalizing the request URL once (support both absolute and relative inputs) and reusing it for both the initial request and the retry.
async function fetchWithAuth(url: string, options: RequestInit = {}): Promise<Response> {
    const accessToken = getAccessToken();
    if (!accessToken) throw new Error("Nicht eingeloggt");

    // Erster Versuch mit aktuellem Access Token
    let res = await fetch(`${API_URL}`+url, {
        ...options,
        headers: {
            ...options.headers,
            Authorization: `Bearer ${accessToken}`,
        },
    });

    // Bei 401: Access Token erneuern und erneut versuchen
    if (res.status === 401) {
        const refreshToken = getRefreshToken();
        if (!refreshToken) throw new Error("Nicht eingeloggt");

        let tokens;
        try {
            tokens = await apiRefreshTokens(refreshToken);
        } catch {
            clearTokens();
            throw new Error("Session abgelaufen");
        }
        saveTokens(tokens.access_token, tokens.refresh_token);

        res = await fetch(url, {
            ...options,
            headers: {
                ...options.headers,
                Authorization: `Bearer ${tokens.access_token}`,
            },
        });

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +72 to +91
// Top 5 Zutaten vom Backend laden – als wiederverwendbare Funktion,
// damit wir sie sowohl beim Page-Load als auch beim Popup-Öffnen aufrufen können.
// cache: "no-store" + Cache-Buster, damit wir wirklich frische Daten bekommen
// und nicht eine vom Browser gecachte Antwort.
const fetchSuggestions = useCallback(async () => {
try {
const res = await fetchWithAuth(`/ingredients/top?limit=5&_=${Date.now()}`, {
cache: "no-store",
headers: { "Cache-Control": "no-cache" },
});
if (!res.ok) return;
const data = await res.json();
if (Array.isArray(data.ingredients)) {
setSuggestions(data.ingredients);
localStorage.setItem("ingredientSuggestions", JSON.stringify(data.ingredients));
}
} catch {
// bei Fehler den localStorage-Wert behalten
}
}, []);
Comment thread project/backend/Auth.py Outdated
Comment thread project/backend/Database.py
Comment on lines +284 to +330
# ── Ingredient-Usage-Operationen ───────────────────────────────

def incrementIngredientUsage(AccountID: int, name: str, unit: str | None) -> None:
"""Erhöht den Usage-Counter für eine Zutat um 1, aktualisiert lastUnit und lastUsedAt.
Legt einen neuen Eintrag an, falls die Zutat für diesen Account noch nicht existiert.
Der Name wird normalisiert (trim + lowercase) für den Primary Key, displayName behält
die Originalschreibweise der letzten Eingabe.
"""
displayName = (name or "").strip()
if not displayName:
return
normalizedName = displayName.lower()
with getDB() as con:
cur = con.cursor()
cur.execute(
"""
INSERT INTO IngredientUsage (AccountID, name, displayName, count, lastUnit, lastUsedAt)
VALUES (?, ?, ?, 1, ?, CURRENT_TIMESTAMP)
ON CONFLICT(AccountID, name) DO UPDATE SET
count = count + 1,
displayName = excluded.displayName,
lastUnit = excluded.lastUnit,
lastUsedAt = CURRENT_TIMESTAMP
""",
(AccountID, normalizedName, displayName, unit),
)


def getTopIngredients(AccountID: int, limit: int = 5) -> list[dict]:
"""Liefert die meistgenutzten Zutaten des Users.
Sortierung Hybrid: erst nach count DESC, dann nach lastUsedAt DESC als Tie-Breaker.
"""
con = getConnection()
try:
cur = con.cursor()
cur.execute(
"""
SELECT displayName, lastUnit, count, lastUsedAt
FROM IngredientUsage
WHERE AccountID = ?
ORDER BY count DESC, lastUsedAt DESC
LIMIT ?
""",
(AccountID, limit),
)
return [dict(row) for row in cur.fetchall()]
finally:
EdenBernhard and others added 2 commits May 10, 2026 21:40
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants