munch-ease-backend/shopping/db.py

254 lines
10 KiB
Python
Raw Normal View History

2025-07-27 05:24:54 +00:00
from common import BaseLinkedModel
from meals import Meal, find_meal_by_id
2024-05-17 09:09:03 +00:00
from ingredients import Ingredient, insert_ingredient
from persons import Person
from products import Product
from typing import AsyncIterator, List, ClassVar, Optional
2024-05-17 09:09:03 +00:00
from datetime import datetime
2024-05-17 09:09:03 +00:00
2025-07-27 05:24:54 +00:00
class ShoppingListItem(BaseLinkedModel):
2024-05-17 09:09:03 +00:00
KEYS: ClassVar[List[str]] = ['id', 'ingredient_id', 'list_id', 'person_id', 'meal_id', 'created_date']
2024-05-20 10:09:57 +00:00
id: int = -1
list_id: Optional[int] = None
2024-05-17 09:09:03 +00:00
2025-07-27 05:24:54 +00:00
person_id: int = -1
person: Optional[Person] = None
2024-05-18 07:05:01 +00:00
ingredient_id: Optional[int] = None
2024-05-17 09:09:03 +00:00
ingredient: Optional[Ingredient] = None
meal_id: Optional[int] = None
meal: Optional[Meal] = None
2024-10-14 05:59:05 +00:00
created_date: datetime = datetime.now().astimezone()
2024-05-17 09:09:03 +00:00
from enum import Enum
class StoreEnum(str, Enum):
woolworths = 'woolworths'
coles = 'coles'
home = ''
2024-05-17 09:09:03 +00:00
2025-07-27 05:24:54 +00:00
class ShoppingList(BaseLinkedModel):
KEYS: ClassVar[List[str]] = ['id', 'created_date', 'store_name']
2024-05-20 10:09:57 +00:00
id: int = -1
2024-10-14 05:59:05 +00:00
created_date: datetime = datetime.now().astimezone()
store_name: StoreEnum = ''
2025-07-27 05:24:54 +00:00
purchased_by_id: int = -1
purchased_by: Optional[Person] = None
items: List[ShoppingListItem] = []
2025-07-27 01:58:28 +00:00
2024-05-17 09:09:03 +00:00
async def create(conn):
await conn.execute('''
CREATE TABLE IF NOT EXISTS ShoppingList (
id INTEGER PRIMARY KEY,
2024-10-14 06:36:56 +00:00
created_date DATETIME NOT NULL,
store_name TEXT NOT NULL,
2025-07-27 05:24:54 +00:00
purchased_by_id INTEGER,
FOREIGN KEY(purchased_by_id) REFERENCES Person(id)
2024-05-17 09:09:03 +00:00
);''')
2025-07-27 05:24:54 +00:00
2024-05-17 09:09:03 +00:00
await conn.execute('''
2025-07-27 05:24:54 +00:00
CREATE TABLE IF NOT EXISTS ShoppingListItem (
2024-05-17 09:09:03 +00:00
id INTEGER PRIMARY KEY,
ingredient_id INTEGER,
list_id INTEGER,
person_id INTEGER,
meal_id INTEGER,
2024-10-14 06:36:56 +00:00
created_date DATETIME NOT NULL,
2024-05-17 09:09:03 +00:00
FOREIGN KEY(ingredient_id) REFERENCES Ingredient(id),
2025-07-27 05:24:54 +00:00
FOREIGN KEY(list_id) REFERENCES ShoppingList(id),
2024-05-17 09:09:03 +00:00
FOREIGN KEY(person_id) REFERENCES Person(id),
2025-07-27 05:24:54 +00:00
FOREIGN KEY(meal_id) REFERENCES Meal(id)
2024-05-17 09:09:03 +00:00
);''')
2024-05-20 10:09:57 +00:00
2025-07-27 05:24:54 +00:00
def validate_request(request: ShoppingListItem) -> None:
if request.person_id < 0:
raise ValueError('Requests must have a person')
2024-05-20 10:09:57 +00:00
# A request must have either an ingredient or a meal, but not both
if not request.ingredient and not request.meal:
raise ValueError('Request must have either an ingredient or a meal')
2025-07-27 05:24:54 +00:00
async def purchase(conn, shopping_list: ShoppingList) -> None:
if shopping_list.purchased_by_id is None:
raise ValueError('Shopping list must have a person id')
2024-05-17 09:09:03 +00:00
2025-07-27 05:24:54 +00:00
if shopping_list.items is None or len(shopping_list.items) == 0:
raise ValueError('Shopping list must have items')
2024-05-20 10:09:57 +00:00
2024-10-14 05:59:05 +00:00
shopping_list.created_date = datetime.now().astimezone()
2024-05-17 09:09:03 +00:00
async with conn.execute('''
2025-07-27 05:24:54 +00:00
INSERT INTO ShoppingList (created_date, store_name, purchased_by_id)
VALUES (?, ?, ?)
''', (shopping_list.created_date.isoformat(), shopping_list.store_name, shopping_list.purchased_by_id)) as cursor:
2024-05-17 09:09:03 +00:00
shopping_list.id = cursor.lastrowid
2025-07-27 05:24:54 +00:00
for item in shopping_list.items:
item.list_id = shopping_list.id
validate_request(item)
if item.ingredient and item.ingredient.id < 0:
await insert_ingredient(conn, item.ingredient)
if item.ingredient_id is None or item.ingredient_id < 0:
raise ValueError('Ingredient request must have a valid ingredient id')
isMeal = item.meal_id is None or item.meal_id < 0
isPersonRequest = (not isMeal) and item.person_id is not None and item.person_id >= 0
if not isMeal and not isPersonRequest:
raise ValueError('Ingredient request must have either a meal or a person id')
if isPersonRequest:
# Update existing request from its null id, or throw
async with conn.execute('''
UPDATE ShoppingListItem
SET list_id = ?
WHERE ingredient_id = ? AND person_id = ? AND meal_id IS NULL
''', (shopping_list.id, item.ingredient_id, item.person_id)) as cursor:
if cursor.rowcount == 0:
raise ValueError('Ingredient request must have a valid person id and ingredient id')
elif isMeal:
# Insert new request for meal
if item.meal_id is None or item.meal_id < 0:
raise ValueError('Meal request must have a valid meal id')
async with conn.execute('''
INSERT INTO ShoppingListItem (ingredient_id, list_id, person_id, meal_id, created_date)
VALUES (?, ?, ?, ?, ?)
''', (item.ingredient_id, shopping_list.id, item.person_id, item.meal_id, item.created_date.isoformat())) as cursor:
item.id = cursor.lastrowid
# TODO: Calculate which meals have been fulfilled and update meal status
async def requested_meal_ids(conn) -> AsyncIterator[ShoppingListItem]:
async with conn.execute(f'''
SELECT {ShoppingListItem.KEYS}
FROM ShoppingListItem
WHERE list_id IS NULL AND meal_id IS NOT NULL AND meal_id > 0
''') as cursor:
async for row in cursor:
yield ShoppingListItem(**{k:v for k,v in zip(ShoppingListItem.KEYS, row)})
async def request(conn, person: Person, ingredient: Optional[Ingredient] = None, meal: Optional[Meal] = None) -> ShoppingListItem:
if ingredient is not None and meal is not None:
raise ValueError('Cannot request both an ingredient and a meal')
if ingredient is None and meal is None:
raise ValueError('Must specify either an ingredient or a meal to request')
if meal is not None and meal.id < 0:
raise ValueError('Meal must have a valid id')
if ingredient is not None and ingredient.id < 0:
await insert_ingredient(conn, ingredient)
2024-05-20 10:09:57 +00:00
2025-07-27 05:24:54 +00:00
item = ShoppingListItem(ingredient=ingredient, person=person, meal=meal)
2024-05-20 10:09:57 +00:00
2025-07-27 05:24:54 +00:00
validate_request(item)
2024-05-17 09:09:03 +00:00
2025-07-27 05:24:54 +00:00
async with conn.execute('''
INSERT INTO ShoppingListItem (ingredient_id, person_id, meal_id, created_date)
VALUES (?, ?, ?, ?)
''', (item.ingredient_id, item.person_id, item.meal_id, item.created_date.isoformat())) as cursor:
item.id = cursor.lastrowid
2024-05-20 10:09:57 +00:00
2025-07-27 05:24:54 +00:00
return item
2024-05-20 10:09:57 +00:00
2025-07-27 05:24:54 +00:00
async def remove_request(conn, person: Person, meal: Optional[Meal] = None, ingredient: Optional[Ingredient] = None) -> None:
failed = True
if meal is not None:
# Ensure a record is removed
2024-05-20 10:09:57 +00:00
async with conn.execute('''
2025-07-27 05:24:54 +00:00
DELETE FROM ShoppingListItem
WHERE list_id IS NULL AND meal_id = ?
''', (meal.id,)) as cursor:
if cursor.rowcount > 0:
failed = False
elif ingredient is not None:
# Ensure a record is removed
async with conn.execute('''
DELETE FROM ShoppingListItem
WHERE list_id IS NULL AND ingredient_id = ? AND person_id = ?
''', (ingredient.id, person.id)) as cursor:
if cursor.rowcount > 0:
failed = False
2024-05-20 10:09:57 +00:00
2025-07-27 05:24:54 +00:00
if failed:
raise ValueError('Must specify either a meal or an ingredient to remove')
2024-05-17 09:09:03 +00:00
2025-07-27 05:24:54 +00:00
async def find_items_by_list_id(conn, list_id: Optional[int]) -> AsyncIterator[ShoppingListItem]:
2024-05-17 09:09:03 +00:00
# Join Ingredient and Product to also load ingredient and product
ingredient_keys = [f'ingredient.{key}' for key in Ingredient.KEYS]
product_keys = [f'product.{key}' for key in Product.KEYS]
2025-07-27 05:24:54 +00:00
request_keys = [f'shoppinglistitem.{key}' for key in ShoppingListItem.KEYS]
2024-05-17 09:09:03 +00:00
person_keys = [f'person.{key}' for key in Person.KEYS]
select = f'''
2024-05-17 09:09:03 +00:00
SELECT {','.join(ingredient_keys + product_keys + request_keys + person_keys)}
2025-07-27 05:24:54 +00:00
FROM ShoppingListItem
LEFT JOIN Ingredient ON ShoppingListItem.ingredient_id = Ingredient.id
2024-05-17 09:09:03 +00:00
LEFT JOIN Product ON Ingredient.product_id = Product.id
2025-07-27 05:24:54 +00:00
LEFT JOIN Person ON ShoppingListItem.person_id = Person.id
'''
where, params = ' WHERE list_id IS NULL', ()
if list_id is not None:
where, params = ' WHERE list_id = ?', (list_id,)
cursor = await conn.execute(select + where, params)
2024-05-17 09:09:03 +00:00
async for row in cursor:
product_keys = {k:v for k,v in zip(Product.KEYS, row[len(Ingredient.KEYS):len(Ingredient.KEYS) + len(Product.KEYS)])}
product = Product(**product_keys) if product_keys['id'] else None
ingredient_keys = {k:v for k,v in zip(Ingredient.KEYS, row[:len(Ingredient.KEYS)])}
2024-05-18 07:05:01 +00:00
ingredient = Ingredient(**ingredient_keys, product=product) if ingredient_keys['id'] else None
2024-05-17 09:09:03 +00:00
person_keys = {k:v for k,v in zip(Person.KEYS, row[-len(Person.KEYS):])}
person = Person(**person_keys) if person_keys['id'] else None
2025-07-27 05:24:54 +00:00
request_keys = {k:v for k,v in zip(ShoppingListItem.KEYS, row[len(Ingredient.KEYS) + len(Product.KEYS):-len(Person.KEYS)])}
request = ShoppingListItem(**request_keys, ingredient=ingredient, person=person)
2024-05-18 07:05:01 +00:00
2024-05-20 10:09:57 +00:00
if request.meal_id is not None:
2024-05-18 07:05:01 +00:00
request.meal = await find_meal_by_id(conn, request.meal_id)
2024-05-17 09:09:03 +00:00
yield request
async def load_shopping_list(conn, id: int) -> ShoppingList:
shopping_list = None
async with conn.execute(f'''
SELECT {','.join(ShoppingList.KEYS)} FROM ShoppingList
WHERE id = ?
LIMIT 1
''', (id,)) as cursor:
async for row in cursor:
shopping_list = ShoppingList(**{k:v for k,v in zip(ShoppingList.KEYS, row)})
break
if shopping_list:
2025-07-27 05:24:54 +00:00
async for item in find_items_by_list_id(conn, shopping_list.id):
shopping_list.items.append(item)
2024-05-17 09:09:03 +00:00
return shopping_list
2025-07-27 05:24:54 +00:00
async def get_purchased_ingredients(conn, meal_ids: List[int]) -> AsyncIterator[ShoppingListItem]:
if not meal_ids:
return
2024-05-18 07:05:01 +00:00
2025-07-27 05:24:54 +00:00
async with conn.execute(f'''
SELECT {','.join(ShoppingListItem.KEYS)}
FROM ShoppingListItem
WHERE meal_id IN ({','.join(['?'] * len(meal_ids))})
''', meal_ids) as cursor:
2024-05-19 03:43:06 +00:00
async for row in cursor:
2025-07-27 05:24:54 +00:00
yield ShoppingListItem(**{k:v for k,v in zip(ShoppingListItem.KEYS, row)})