Feat: show top 5 incredients as options#152
Open
EdenBernhard wants to merge 16 commits intoblatt17from
Open
Conversation
… Konto deletion reactivation.
# 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
There was a problem hiding this comment.
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 updatedtopIngredientsfrom/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
fetchWithAuthnow prefixesAPI_URLonly for the first request, but the 401 retry still callsfetch(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 getAPI_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 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: |
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.