munch-ease-backend/main.py

414 lines
17 KiB
Python
Raw Normal View History

2024-01-08 00:45:22 +00:00
import sqlite3
2024-05-18 07:05:01 +00:00
import products, recipes, db, meals, persons, ingredients, shopping
2024-01-13 07:42:23 +00:00
import datetime
2024-01-08 00:45:22 +00:00
2024-01-13 01:54:04 +00:00
from pydantic import BaseModel
2025-07-28 10:51:40 +00:00
from typing import Dict, List, Annotated, Optional, Union
2024-04-25 02:03:30 +00:00
from fastapi import FastAPI, Depends, Query, Cookie
2024-01-13 05:40:10 +00:00
from fastapi.responses import JSONResponse
2024-04-25 02:03:30 +00:00
from fastapi.encoders import jsonable_encoder
2024-01-07 00:33:40 +00:00
app = FastAPI()
2024-09-21 01:22:30 +00:00
import os
DATABASE_PATH = os.environ.get('DOOF_DB', './data/doof.sqlite')
2024-01-07 00:33:40 +00:00
2024-01-08 00:38:17 +00:00
# Dependency to create SQLite connection
async def get_db():
2024-09-21 01:22:30 +00:00
sql_db = await db.connect(DATABASE_PATH)
2024-01-08 00:38:17 +00:00
try:
yield sql_db
finally:
2024-01-13 01:54:04 +00:00
await sql_db.close()
2024-01-08 00:38:17 +00:00
2024-04-25 02:03:30 +00:00
async def cookie_person(user_id: Annotated[int, Cookie(alias='user_id')], conn: sqlite3.Connection = Depends(get_db)) -> persons.Person:
2024-04-25 04:57:39 +00:00
return await persons.get_by_id(conn, user_id)
2024-04-25 02:03:30 +00:00
@app.get("/api/recipes/parse")
2024-05-19 11:22:30 +00:00
async def parse_recipe_handler(url: str, conn: sqlite3.Connection = Depends(get_db), person = Depends(cookie_person)) -> recipes.Recipe:
parsed = await recipes.parse_recipe(conn, person, url)
2024-01-13 05:40:10 +00:00
if not parsed:
return JSONResponse(status_code=400, content={'message': 'Recipe not found'})
return parsed
2024-01-08 00:45:22 +00:00
@app.get("/api/recipes/ingredients/parse")
2024-01-13 01:54:04 +00:00
async def parse_ingredients(lines: Annotated[
List[str],
Query(alias="ingredients",
title="Array of ingredients to parse")],
2024-01-17 07:21:16 +00:00
conn: sqlite3.Connection = Depends(get_db)) -> List[ingredients.Ingredient]:
2024-05-21 12:12:09 +00:00
had_links = False
result = []
for line in lines:
ingredient = await ingredients.parse_ingredient_from_link(conn, line)
if ingredient:
result.append(ingredient)
had_links = True
continue
ingredient = ingredients.parse_ingredient_from_nlp(line)
if ingredient:
result.append(ingredient)
continue
if had_links:
await conn.commit()
2024-01-17 08:36:54 +00:00
await ingredients.match_existing_products(conn, result)
return result
2024-01-08 00:38:17 +00:00
2024-01-13 01:54:04 +00:00
class ProductUrl(BaseModel):
url: str
tags: List[str] = []
@app.post("/api/products")
2024-01-13 07:44:48 +00:00
async def create_product(url: ProductUrl, conn: sqlite3.Connection = Depends(get_db)) -> products.Product:
return await products.get_or_create(conn, url.url, url.tags)
2024-01-13 05:40:10 +00:00
2024-01-13 07:44:48 +00:00
async def load_full_recipe(conn: sqlite3.Connection, id: int) -> recipes.Recipe:
r = await recipes.find_recipe_by_id(conn, id)
2024-01-13 06:59:35 +00:00
if not r:
2024-01-13 07:42:23 +00:00
return None
2024-01-13 06:59:35 +00:00
r.ingredients = []
2024-01-17 07:21:16 +00:00
async for ingredient in ingredients.find_ingredients_by_recipe_id(conn, id):
2024-01-13 06:59:35 +00:00
r.ingredients.append(ingredient)
2024-04-25 04:57:39 +00:00
r.created_by = await persons.get_by_id(conn, r.created_by_id)
2024-01-13 06:59:35 +00:00
return r
@app.get("/api/recipes")
async def get_recipes(q: str | None = None, conn: sqlite3.Connection = Depends(get_db)) -> List[recipes.Recipe]:
2024-01-13 08:44:07 +00:00
result = []
if q:
async for recipe in recipes.find_recipes_by_name(conn, q):
result.append(recipe)
else:
async for recipe in recipes.get_all(conn):
result.append(recipe)
2024-01-13 08:44:07 +00:00
for recipe in result:
recipe.ingredients = []
2024-01-17 07:21:16 +00:00
async for ingredient in ingredients.find_ingredients_by_recipe_id(conn, recipe.id):
recipe.ingredients.append(ingredient)
2024-01-13 08:44:07 +00:00
return result
@app.get("/api/recipes/{recipe_id}")
2024-01-13 07:44:48 +00:00
async def get_recipe(recipe_id: int, conn: sqlite3.Connection = Depends(get_db)) -> recipes.Recipe:
2024-01-13 07:42:23 +00:00
r = await load_full_recipe(conn, recipe_id)
if not r:
return JSONResponse(status_code=404, content={'message': 'Recipe not found'})
return r
2024-09-22 02:26:49 +00:00
@app.post('/api/recipes')
2024-05-20 10:09:57 +00:00
async def create_recipe(recipe: recipes.Recipe, conn: sqlite3.Connection = Depends(get_db), user: persons.Person = Depends(cookie_person)) -> recipes.Recipe:
if not recipe.ingredients:
2024-01-13 05:40:10 +00:00
return JSONResponse(status_code=400, content={'message': 'Recipe must have at least one ingredient'})
2024-05-20 10:09:57 +00:00
if recipe.id >= 0:
await recipes.hide_recipe(conn, recipe.id, user)
recipe.based_on_recipe = recipe.id
recipe.id = 0
2024-04-28 03:57:02 +00:00
2024-05-20 10:09:57 +00:00
recipe.created_by_id = user.id
await recipes.insert_recipe(conn, recipe)
for ingredient in recipe.ingredients:
ingredient.recipe_id = recipe.id
2025-07-27 01:58:28 +00:00
if ingredient.product:
ingredient.product_id = ingredient.product.id
2024-01-17 08:36:54 +00:00
await ingredients.insert_ingredient(conn, ingredient)
2024-04-28 03:57:02 +00:00
2024-01-13 05:40:10 +00:00
await conn.commit()
2024-05-20 10:09:57 +00:00
return recipe
2024-01-13 07:42:23 +00:00
2024-05-02 12:25:11 +00:00
@app.delete('/recipes/{recipe_id}')
async def delete_recipe(recipe_id: int, conn: sqlite3.Connection = Depends(get_db), user: persons.Person = Depends(cookie_person)) -> recipes.Recipe:
recipe = await recipes.find_recipe_by_id(conn, recipe_id)
if not recipe:
return JSONResponse(status_code=404, content={'message': 'Recipe not found'})
await recipes.hide_recipe(conn, recipe_id, user)
await conn.commit()
return recipe
@app.get("/api/meals/upcoming")
2024-05-25 02:33:41 +00:00
async def get_upcoming_meals(date_from: Annotated[datetime.datetime, Query(alias='from')], to: datetime.datetime, conn: sqlite3.Connection = Depends(get_db)) -> List[meals.Meal]:
2024-01-13 07:42:23 +00:00
result = []
2024-05-25 02:33:41 +00:00
async for meal in meals.find_upcoming_meals_by_date_range(conn, date_from, to):
2024-01-17 11:43:16 +00:00
await meals.load_recipes(conn, meal)
await meals.load_extra_ingredients(conn, meal)
2024-04-30 11:21:59 +00:00
await meals.load_participants(conn, meal)
2024-01-13 07:42:23 +00:00
result.append(meal)
return result
@app.get("/api/meals/{meal_id}")
2024-01-17 11:09:55 +00:00
async def get_meal(meal_id: int, conn: sqlite3.Connection = Depends(get_db)) -> meals.Meal:
2024-01-17 10:39:48 +00:00
meal = await meals.find_meal_by_id(conn, meal_id)
if not meal:
return JSONResponse(status_code=404, content={'message': 'Meal not found'})
return meal
2024-05-04 05:06:48 +00:00
def get_duplicates(items: List[meals.Person]) -> set[str]:
seen : set[int] = set()
duplicates : set[str] = set()
for item in items:
if item.id in seen:
duplicates.add(item.name)
seen.add(item.id)
return duplicates
def validate_meal(meal : meals.Meal) -> JSONResponse | None:
2024-04-25 04:57:39 +00:00
if not meal.chefs:
2024-01-13 07:42:23 +00:00
return JSONResponse(status_code=400, content={'message': 'Meal must have at least one chef'})
if not meal.cleanup:
return JSONResponse(status_code=400, content={'message': 'Meal must have at least one cleanup person'})
if not meal.consumers:
return JSONResponse(status_code=400, content={'message': 'Meal must have at least one consumer'})
2024-01-17 07:21:16 +00:00
if len(meal.recipes) == 0 and len(meal.extra_ingredients) == 0:
return JSONResponse(status_code=400, content={'message': 'Meal must have at least one recipe or ingredient'})
2024-05-04 05:06:48 +00:00
duplicates = get_duplicates(meal.chefs)
if duplicates:
return JSONResponse(status_code=400, content={'message': f'Duplicate chef: {", ".join(duplicates)}'})
duplicates = get_duplicates(meal.cleanup)
if duplicates:
return JSONResponse(status_code=400, content={'message': f'Duplicate cleanup person: {", ".join(duplicates)}'})
duplicates = get_duplicates(meal.consumers)
if duplicates:
return JSONResponse(status_code=400, content={'message': f'Duplicate consumer: {", ".join(duplicates)}'})
zero_servings = [r for r in meal.recipes if r.servings == 0]
if zero_servings:
return JSONResponse(status_code=400, content={'message': 'Recipe servings must be greater than 0'})
2024-05-04 05:06:48 +00:00
return None
@app.post("/api/meals")
2024-05-04 05:06:48 +00:00
async def create_meal(meal: meals.Meal, conn: sqlite3.Connection = Depends(get_db)) -> meals.Meal:
validation_response = validate_meal(meal)
if validation_response:
return validation_response
2024-01-17 07:21:16 +00:00
2024-01-13 07:42:23 +00:00
await meals.insert_meal(conn, meal)
await conn.commit()
2024-01-13 08:44:07 +00:00
return meal
@app.put("/api/meals/{meal_id}")
2024-05-02 11:20:52 +00:00
async def update_meal(meal_id: int, meal: meals.Meal, conn: sqlite3.Connection = Depends(get_db)) -> meals.Meal:
if meal.id != meal_id:
return JSONResponse(status_code=400, content={'message': 'Meal ID in URL does not match meal ID in body'})
existing = await meals.find_meal_by_id(conn, meal_id)
if not existing:
return JSONResponse(status_code=404, content={'message': 'Meal not found'})
2024-05-04 05:06:48 +00:00
validation_response = validate_meal(meal)
if validation_response:
return validation_response
2024-05-02 11:20:52 +00:00
await meals.update_meal(conn, meal)
await conn.commit()
return await get_meal(meal_id, conn)
@app.post("/api/meals/{meal_id}/consumed")
2024-05-27 11:55:47 +00:00
async def mark_consumed(meal_id: int, consumed_date: Optional[datetime.datetime] = None, conn: sqlite3.Connection = Depends(get_db), person: persons.Person = Depends(cookie_person)) -> meals.Meal:
2024-10-14 05:59:05 +00:00
if consumed_date and not consumed_date.tzinfo:
return JSONResponse(status_code=400, content={'message': 'Consumed date must include timezone'})
2024-05-27 11:55:47 +00:00
meal = await meals.find_meal_by_id(conn, meal_id)
2024-05-25 02:33:41 +00:00
if not meal:
return JSONResponse(status_code=404, content={'message': 'Meal not found'})
2024-10-14 05:59:05 +00:00
await meals.mark_consumed(conn, meal, consumed_date or datetime.datetime.now().astimezone())
2025-07-28 23:06:36 +00:00
await shopping.remove_request(conn, person, meal=meal)
2024-10-13 08:31:37 +00:00
2024-05-25 02:33:41 +00:00
await conn.commit()
return meal
@app.delete("/api/meals/{meal_id}")
2025-07-28 23:06:36 +00:00
async def delete_meal(meal_id: int, conn: sqlite3.Connection = Depends(get_db), person: persons.Person = Depends(cookie_person)) -> meals.Meal:
2024-01-17 11:43:16 +00:00
meal = await meals.find_meal_by_id(conn, meal_id)
if not meal:
return JSONResponse(status_code=404, content={'message': 'Meal not found'})
2025-07-28 23:06:36 +00:00
await shopping.remove_request(conn, person, meal=meal)
2024-01-17 11:43:16 +00:00
await meals.delete_meal(conn, meal.id)
2024-10-13 08:31:37 +00:00
2024-01-17 11:43:16 +00:00
await conn.commit()
return meal
2024-01-17 10:39:48 +00:00
class CurrentShoppingList(BaseModel):
2025-07-28 10:51:40 +00:00
outstanding_items: List[shopping.ShoppingListItem]
requested_meals: List[shopping.ShoppingListItem]
purchased_items: List[shopping.ShoppingListItem] = []
ingredients_lookup: Dict[int, ingredients.Ingredient] = {}
meals_lookup: Dict[int, meals.Meal] = {}
shopping_list_lookup: Dict[int, shopping.ShoppingList] = {}
recipes_lookup: Dict[int, recipes.Recipe] = {}
2024-05-18 07:05:01 +00:00
@app.get("/api/shopping/current")
async def get_current_shopping_list(conn: sqlite3.Connection = Depends(get_db)) -> CurrentShoppingList:
2025-07-28 10:51:40 +00:00
outstanding_requests, purchased_requests, meal_requests = await shopping.get_outstanding_requests(conn)
other_shopping_list_ids = {item.list_id for item in purchased_requests}
shopping_list_lookup = { list_id: await shopping.load_shopping_list(conn, list_id) for list_id in other_shopping_list_ids }
2024-10-14 05:01:47 +00:00
2025-07-28 10:51:40 +00:00
# Reduce the data structure to items and lookups
items = meal_requests + outstanding_requests + purchased_requests + [item for sl in shopping_list_lookup.values() for item in sl.items]
2025-07-28 12:36:56 +00:00
meals_lookup, recipes_lookup, ingredients_lookup = shopping.remove_references(items)
2025-07-28 10:51:40 +00:00
return CurrentShoppingList(
outstanding_items=outstanding_requests,
requested_meals=meal_requests,
purchased_items=purchased_requests,
meals_lookup=meals_lookup,
shopping_list_lookup=shopping_list_lookup,
ingredients_lookup=ingredients_lookup,
recipes_lookup=recipes_lookup
)
2024-05-19 03:43:06 +00:00
2025-07-28 12:36:56 +00:00
class PurchasedShoppingList(BaseModel):
list: shopping.ShoppingList
meals_lookup: Dict[int, meals.Meal] = {}
ingredients_lookup: Dict[int, ingredients.Ingredient] = {}
recipes_lookup: Dict[int, recipes.Recipe] = {}
@app.get("/api/shopping/{list_id}")
2025-07-28 12:36:56 +00:00
async def get_shopping_list(list_id: int, conn: sqlite3.Connection = Depends(get_db)) -> PurchasedShoppingList:
shopping_list = await shopping.load_shopping_list(conn, list_id)
2025-07-28 23:06:36 +00:00
meals_lookup, recipes_lookup, ingredients_lookup = shopping.remove_references(shopping_list.items)
return PurchasedShoppingList(list=shopping_list, meals_lookup=meals_lookup, recipes_lookup=recipes_lookup, ingredients_lookup=ingredients_lookup)
2024-05-19 03:43:06 +00:00
@app.post("/api/shopping/")
2025-07-28 12:36:56 +00:00
async def purchase_ingredients(shopping_list: shopping.ShoppingList, conn: sqlite3.Connection = Depends(get_db), person: persons.Person = Depends(cookie_person)) -> PurchasedShoppingList:
2025-07-27 05:24:54 +00:00
shopping_list = shopping.ShoppingList(purchased_by=person, items=shopping_list.items, store_name=shopping_list.store_name)
await shopping.purchase(conn, shopping_list)
2024-05-19 03:43:06 +00:00
await conn.commit()
2025-07-27 05:24:54 +00:00
2025-07-28 12:36:56 +00:00
result = PurchasedShoppingList(list=shopping_list)
shopping.remove_references(shopping_list.items, result.meals_lookup, result.recipes_lookup, result.ingredients_lookup)
return result
2025-07-27 05:24:54 +00:00
@app.get("/api/shopping/current/me/ingredients")
2025-07-27 05:24:54 +00:00
async def get_my_shopping_list(conn: sqlite3.Connection = Depends(get_db), person: persons.Person = Depends(cookie_person)) -> List[ingredients.Ingredient]:
return [r.ingredient async for r in shopping.get_persons_requests(conn, person.id)]
2024-05-18 07:05:01 +00:00
@app.post("/api/shopping/current/me/ingredients")
2025-07-27 05:24:54 +00:00
async def sync_my_shopping_list(requests: List[ingredients.Ingredient], conn: sqlite3.Connection = Depends(get_db), person: persons.Person = Depends(cookie_person)) -> List[ingredients.Ingredient]:
def isMatching(a: ingredients.Ingredient, b: ingredients.Ingredient) -> bool:
return a.id == b.id or a.line == b.line
my_shopping_list = [r.ingredient async for r in shopping.get_persons_requests(conn, person.id) if r.ingredient is not None]
to_remove = [r for r in my_shopping_list if not any(isMatching(r, req) for req in requests)]
to_add = [req for req in requests if not any(isMatching(req, r) for r in my_shopping_list)]
for r in to_remove:
await shopping.remove_request(conn, person, ingredient=r)
for r in to_add:
if r.id < 0:
await ingredients.insert_ingredient(conn, r)
await shopping.request(conn, person, ingredient=r)
2024-05-18 07:05:01 +00:00
await conn.commit()
2025-07-27 05:24:54 +00:00
return await get_my_shopping_list(conn, person)
2024-05-18 07:05:01 +00:00
class MealIdWrapper(BaseModel):
meal_id: int
@app.post("/api/shopping/current/meals/me")
2025-07-27 05:24:54 +00:00
async def request_meal(r: MealIdWrapper, conn: sqlite3.Connection = Depends(get_db), person: persons.Person = Depends(cookie_person)) -> shopping.ShoppingListItem:
2024-05-18 07:05:01 +00:00
meal = await meals.find_meal_by_id(conn, r.meal_id)
if not meal:
return JSONResponse(status_code=404, content={'message': 'Meal not found'})
2025-07-27 05:24:54 +00:00
response = await shopping.request(conn, person, meal=meal)
2024-05-18 07:05:01 +00:00
await conn.commit()
return response
@app.delete("/api/shopping/current/meals/{meal_id}")
2024-05-18 07:05:01 +00:00
async def unrequest_meal(meal_id: int, conn: sqlite3.Connection = Depends(get_db), person: persons.Person = Depends(cookie_person)) -> dict:
meal = await meals.find_meal_by_id(conn, meal_id)
if not meal:
return JSONResponse(status_code=404, content={'message': 'Meal not found'})
2025-07-27 05:24:54 +00:00
await shopping.remove_request(conn, person, meal=meal)
2024-05-18 07:05:01 +00:00
await conn.commit()
return {}
@app.get("/api/persons")
2024-05-04 04:22:19 +00:00
async def get_persons(q: str = None, conn: sqlite3.Connection = Depends(get_db)) -> List[meals.Person]:
query = persons.search_by_name(conn, q) if q else persons.get_all(conn)
2024-01-13 08:44:07 +00:00
result = []
2024-05-04 04:22:19 +00:00
async for person in query:
2024-01-13 08:44:07 +00:00
result.append(person)
return result
@app.post("/api/persons")
2024-01-13 08:44:07 +00:00
async def create_person(person: persons.Person, conn: sqlite3.Connection = Depends(get_db)) -> persons.Person:
2024-04-28 03:37:01 +00:00
await persons.insert_person(conn, person)
2024-01-13 08:44:07 +00:00
await conn.commit()
2024-04-25 02:03:30 +00:00
return person
class LoginBody(BaseModel):
username: str
@app.post('/api/auth/login')
2024-04-25 02:03:30 +00:00
async def login(data: LoginBody, conn: sqlite3.Connection = Depends(get_db)) -> persons.Person:
person = await persons.get_by_name(conn, data.username)
if not person:
return JSONResponse(status_code=404, content={'message': 'Person not found'})
response = JSONResponse(content=jsonable_encoder(person))
response.set_cookie(key='user_id', value=str(person.id))
2024-04-28 02:15:19 +00:00
return response
@app.post('/api/auth/refresh')
2024-04-28 02:15:19 +00:00
async def current_user(user: persons.Person = Depends(cookie_person)) -> persons.Person:
return user
if os.environ.get('DOOF_PROD', False):
from fastapi.staticfiles import StaticFiles
app.mount("/", StaticFiles(directory="./front-dist", html=True), name="front-dist")
else:
# Proxy the request to the frontend development server
from starlette.requests import Request
from starlette.responses import StreamingResponse
from starlette.background import BackgroundTask
import httpx
client = httpx.AsyncClient(base_url="http://localhost:8080/")
async def _reverse_proxy(request: Request):
url = httpx.URL(path=request.url.path,
query=request.url.query.encode("utf-8"))
rp_req = client.build_request(request.method, url,
headers=request.headers.raw,
content=request.stream())
rp_resp = await client.send(rp_req, stream=True)
return StreamingResponse(
rp_resp.aiter_raw(),
status_code=rp_resp.status_code,
headers=rp_resp.headers,
background=BackgroundTask(rp_resp.aclose),
)
app.add_route("/{path:path}",_reverse_proxy, ["GET", "POST"])