feat(shopping): dedupe ingredient requests per household and make household_id static in DDL
This commit is contained in:
parent
978c970fb6
commit
32a7e6226f
6 changed files with 119 additions and 3 deletions
|
|
@ -166,7 +166,7 @@ Household-scoped routes (implemented):
|
||||||
|
|
||||||
Shopping requests parity (preserved in v2):
|
Shopping requests parity (preserved in v2):
|
||||||
- Request meal: `POST /api/v1/households/{householdSlug}/shopping/current/meals/me` (scoped) and unrequest `DELETE /current/meals/{mealId}`.
|
- Request meal: `POST /api/v1/households/{householdSlug}/shopping/current/meals/me` (scoped) and unrequest `DELETE /current/meals/{mealId}`.
|
||||||
- Request individual ingredient: `POST /api/v1/households/{householdSlug}/shopping/current/ingredients` (scoped). Response is `ListIngredientItem`; item appears in `GET /current` under `outstandingItems`. Household isolation enforced.
|
- Request individual ingredient: `POST /api/v1/households/{householdSlug}/shopping/current/ingredients` (scoped). Response is `ListIngredientItem`; item appears in `GET /current` under `outstandingItems`. Household isolation enforced. Duplicate requests for the same ingredient by the same user within the same household return the existing request (no duplicate rows). Covered by `tests/test_shopping_request_ingredient_dedupe_v2.py`.
|
||||||
|
|
||||||
Repositories accept `household_id` and filter by it across `meals`, `recipes`, and `shopping` domains.
|
Repositories accept `household_id` and filter by it across `meals`, `recipes`, and `shopping` domains.
|
||||||
|
|
||||||
|
|
@ -199,6 +199,7 @@ Repositories accept `household_id` and filter by it across `meals`, `recipes`, a
|
||||||
- Add composite indices `(household_id, id)` where high-cardinality pagination will benefit.
|
- Add composite indices `(household_id, id)` where high-cardinality pagination will benefit.
|
||||||
- Extend migration to add FK constraints from tenant tables to `Household(id)` where safe.
|
- Extend migration to add FK constraints from tenant tables to `Household(id)` where safe.
|
||||||
- Plan and implement data backfill for cross-table references once `users` replace `persons` in code.
|
- Plan and implement data backfill for cross-table references once `users` replace `persons` in code.
|
||||||
|
- Ensure fresh bootstraps include `household_id` in all tenant table DDL (now updated for Ingredient, Recipe, Meal, ShoppingList, ShoppingListItem).
|
||||||
|
|
||||||
2. **[✅] Implement New Authentication System**:
|
2. **[✅] Implement New Authentication System**:
|
||||||
- Implemented v2 JWT auth while keeping v1 cookie auth intact during transition:
|
- Implemented v2 JWT auth while keeping v1 cookie auth intact during transition:
|
||||||
|
|
|
||||||
|
|
@ -17,6 +17,7 @@ async def create(conn):
|
||||||
product_id INTEGER,
|
product_id INTEGER,
|
||||||
recipe_id INTEGER,
|
recipe_id INTEGER,
|
||||||
meal_id INTEGER,
|
meal_id INTEGER,
|
||||||
|
household_id INTEGER,
|
||||||
FOREIGN KEY (product_id) REFERENCES Product(id),
|
FOREIGN KEY (product_id) REFERENCES Product(id),
|
||||||
FOREIGN KEY (recipe_id) REFERENCES Recipe(id),
|
FOREIGN KEY (recipe_id) REFERENCES Recipe(id),
|
||||||
FOREIGN KEY (meal_id) REFERENCES Meal(id)
|
FOREIGN KEY (meal_id) REFERENCES Meal(id)
|
||||||
|
|
|
||||||
|
|
@ -24,7 +24,8 @@ async def create(conn):
|
||||||
suggested_date DATETIME,
|
suggested_date DATETIME,
|
||||||
consumed_date DATETIME DEFAULT NULL,
|
consumed_date DATETIME DEFAULT NULL,
|
||||||
deleted_date DATETIME DEFAULT NULL,
|
deleted_date DATETIME DEFAULT NULL,
|
||||||
purchase_date DATETIME DEFAULT NULL
|
purchase_date DATETIME DEFAULT NULL,
|
||||||
|
household_id INTEGER
|
||||||
);"""
|
);"""
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -23,6 +23,7 @@ async def create(conn):
|
||||||
|
|
||||||
date_hidden DATETIME DEFAULT NULL,
|
date_hidden DATETIME DEFAULT NULL,
|
||||||
hidden_by_id INTEGER DEFAULT NULL,
|
hidden_by_id INTEGER DEFAULT NULL,
|
||||||
|
household_id INTEGER,
|
||||||
|
|
||||||
FOREIGN KEY (based_on_recipe) REFERENCES Recipe(id)
|
FOREIGN KEY (based_on_recipe) REFERENCES Recipe(id)
|
||||||
FOREIGN KEY (created_by_id) REFERENCES Person(id)
|
FOREIGN KEY (created_by_id) REFERENCES Person(id)
|
||||||
|
|
|
||||||
|
|
@ -11,6 +11,7 @@ async def create(conn):
|
||||||
created_date DATETIME NOT NULL,
|
created_date DATETIME NOT NULL,
|
||||||
store_name TEXT NOT NULL,
|
store_name TEXT NOT NULL,
|
||||||
purchased_by_id INTEGER,
|
purchased_by_id INTEGER,
|
||||||
|
household_id INTEGER,
|
||||||
FOREIGN KEY(purchased_by_id) REFERENCES Person(id)
|
FOREIGN KEY(purchased_by_id) REFERENCES Person(id)
|
||||||
);"""
|
);"""
|
||||||
)
|
)
|
||||||
|
|
@ -25,6 +26,7 @@ async def create(conn):
|
||||||
meal_id INTEGER,
|
meal_id INTEGER,
|
||||||
recipe_id INTEGER,
|
recipe_id INTEGER,
|
||||||
created_date DATETIME NOT NULL,
|
created_date DATETIME NOT NULL,
|
||||||
|
household_id INTEGER,
|
||||||
FOREIGN KEY(ingredient_id) REFERENCES Ingredient(id),
|
FOREIGN KEY(ingredient_id) REFERENCES Ingredient(id),
|
||||||
FOREIGN KEY(list_id) REFERENCES ShoppingList(id),
|
FOREIGN KEY(list_id) REFERENCES ShoppingList(id),
|
||||||
FOREIGN KEY(person_id) REFERENCES Person(id),
|
FOREIGN KEY(person_id) REFERENCES Person(id),
|
||||||
|
|
@ -42,6 +44,16 @@ async def create(conn):
|
||||||
await conn.execute(
|
await conn.execute(
|
||||||
"CREATE INDEX IF NOT EXISTS idx_shopping_item_person_null_list ON ShoppingListItem(person_id, ingredient_id) WHERE list_id IS NULL;"
|
"CREATE INDEX IF NOT EXISTS idx_shopping_item_person_null_list ON ShoppingListItem(person_id, ingredient_id) WHERE list_id IS NULL;"
|
||||||
)
|
)
|
||||||
|
# Household indices for scoped queries
|
||||||
|
await conn.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_shopping_list_household_id ON ShoppingList(household_id);"
|
||||||
|
)
|
||||||
|
await conn.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_shopping_item_household_id ON ShoppingListItem(household_id);"
|
||||||
|
)
|
||||||
|
await conn.execute(
|
||||||
|
"CREATE INDEX IF NOT EXISTS idx_shopping_item_household_person_ing_null_list ON ShoppingListItem(household_id, person_id, ingredient_id) WHERE list_id IS NULL;"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def validate_request(request: ShoppingListItem) -> None:
|
def validate_request(request: ShoppingListItem) -> None:
|
||||||
|
|
@ -298,7 +310,21 @@ async def request_ingredient_scoped(
|
||||||
if ingredient is None or getattr(ingredient, "id", -1) < 0:
|
if ingredient is None or getattr(ingredient, "id", -1) < 0:
|
||||||
raise ValueError("Ingredient must have a valid id")
|
raise ValueError("Ingredient must have a valid id")
|
||||||
|
|
||||||
# TODO: Check if ingredient is already requested by this person
|
# If already requested by this person and not yet purchased in this household, return existing
|
||||||
|
where = "WHERE list_id IS NULL AND meal_id IS NULL AND ingredient_id = ? AND person_id = ? AND household_id = ?"
|
||||||
|
params = (ingredient.id, person_id, household_id)
|
||||||
|
async with conn.execute(
|
||||||
|
f"""
|
||||||
|
SELECT id, ingredient_id, list_id, person_id, meal_id, recipe_id, created_date
|
||||||
|
FROM ShoppingListItem
|
||||||
|
{where}
|
||||||
|
LIMIT 1
|
||||||
|
""",
|
||||||
|
params,
|
||||||
|
) as cur:
|
||||||
|
row = await cur.fetchone()
|
||||||
|
if row:
|
||||||
|
return ShoppingListItem(**{k: v for k, v in zip(ShoppingListItem.KEYS, row)})
|
||||||
|
|
||||||
item = ShoppingListItem(ingredient_id=ingredient.id, person_id=person_id, meal_id=None)
|
item = ShoppingListItem(ingredient_id=ingredient.id, person_id=person_id, meal_id=None)
|
||||||
|
|
||||||
|
|
|
||||||
86
tests/test_shopping_request_ingredient_dedupe_v2.py
Normal file
86
tests/test_shopping_request_ingredient_dedupe_v2.py
Normal file
|
|
@ -0,0 +1,86 @@
|
||||||
|
import unittest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
import main
|
||||||
|
from db import connect, create
|
||||||
|
from scripts.migration_to_households import run_migration
|
||||||
|
|
||||||
|
|
||||||
|
class TestShoppingRequestIngredientDedupeV2(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def asyncSetUp(self):
|
||||||
|
self.conn = await connect(":memory:")
|
||||||
|
await create(self.conn)
|
||||||
|
await run_migration(self.conn)
|
||||||
|
|
||||||
|
async def override_get_db():
|
||||||
|
try:
|
||||||
|
yield self.conn
|
||||||
|
finally:
|
||||||
|
pass
|
||||||
|
|
||||||
|
main.app.dependency_overrides[main.get_db] = override_get_db
|
||||||
|
self.client = TestClient(main.app)
|
||||||
|
|
||||||
|
# Register user and create a household
|
||||||
|
r = self.client.post(
|
||||||
|
"/api/v1/auth/register",
|
||||||
|
json={"email": "ing2@test.com", "password": "pw", "displayName": "Ing2"},
|
||||||
|
)
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
token = r.json()["accessToken"]
|
||||||
|
self.headers = {"Authorization": f"Bearer {token}"}
|
||||||
|
|
||||||
|
r = self.client.post("/api/v1/households", headers=self.headers, json={"name": "H"})
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
self.slug = r.json()["slug"]
|
||||||
|
|
||||||
|
# Resolve household id
|
||||||
|
async with self.conn.execute("SELECT id FROM Household WHERE slug = ?", (self.slug,)) as c:
|
||||||
|
row = await c.fetchone()
|
||||||
|
assert row is not None
|
||||||
|
self.hid = int(row[0])
|
||||||
|
|
||||||
|
# Seed one ingredient in household
|
||||||
|
await self.conn.execute(
|
||||||
|
"INSERT INTO Ingredient (name, line, unit, quantity, recipe_id, meal_id, household_id) VALUES ('Eggs', '12 eggs', 'dozen', 1, NULL, NULL, ?)",
|
||||||
|
(self.hid,),
|
||||||
|
)
|
||||||
|
async with self.conn.execute("SELECT last_insert_rowid()") as c:
|
||||||
|
row = await c.fetchone()
|
||||||
|
assert row is not None
|
||||||
|
self.eggs_id = int(row[0])
|
||||||
|
await self.conn.commit()
|
||||||
|
|
||||||
|
async def asyncTearDown(self):
|
||||||
|
await self.conn.close()
|
||||||
|
main.app.dependency_overrides.clear()
|
||||||
|
|
||||||
|
def test_request_same_ingredient_twice_deduped(self):
|
||||||
|
# First request
|
||||||
|
r1 = self.client.post(
|
||||||
|
f"/api/v1/households/{self.slug}/shopping/current/ingredients",
|
||||||
|
headers=self.headers,
|
||||||
|
json={"ingredientId": self.eggs_id},
|
||||||
|
)
|
||||||
|
assert r1.status_code == 200, r1.text
|
||||||
|
item1 = r1.json()
|
||||||
|
|
||||||
|
# Second request for same ingredient should not create a duplicate; return same item
|
||||||
|
r2 = self.client.post(
|
||||||
|
f"/api/v1/households/{self.slug}/shopping/current/ingredients",
|
||||||
|
headers=self.headers,
|
||||||
|
json={"ingredientId": self.eggs_id},
|
||||||
|
)
|
||||||
|
assert r2.status_code == 200, r2.text
|
||||||
|
item2 = r2.json()
|
||||||
|
|
||||||
|
assert item1["id"] == item2["id"], "Should return existing request item"
|
||||||
|
|
||||||
|
# Outstanding list should contain exactly one instance for the ingredient
|
||||||
|
r = self.client.get(
|
||||||
|
f"/api/v1/households/{self.slug}/shopping/current", headers=self.headers
|
||||||
|
)
|
||||||
|
assert r.status_code == 200, r.text
|
||||||
|
cur = r.json()
|
||||||
|
outstanding = [i for i in cur["outstandingItems"] if i.get("ingredientId") == self.eggs_id]
|
||||||
|
assert len(outstanding) == 1, outstanding
|
||||||
Loading…
Reference in a new issue