fix: batch-cook dishes never deducted pantry when marked cooked
Ingredients aren't attributable to individual batch dishes (they're one merged/shared list for the whole prep session, unlike steps which have `appliesTo`) — the cooked route's pantry-deduction block was unconditionally skipped whenever batchDishId was set, so pantry was never touched for any batch-cook recipe. Deducts once, on the first dish marked cooked for that recipe+user (checked via prior cookingHistory rows) — matches the fridge/freezer-day design intent of "cook the batch once, eat dishes over several days" rather than deducting (or trying to deduct) per individual dish. Verified locally: first dish cooked deducted the full recipe's ingredients from pantry; second dish cooked did not double-deduct.
This commit is contained in:
@@ -27,11 +27,21 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
const parsed = Schema.safeParse(body);
|
||||
const data = parsed.success ? parsed.data : { deductFromPantry: true };
|
||||
|
||||
// Ingredients aren't attributable to individual batch dishes — they're one
|
||||
// merged/shared list for the whole prep session (unlike steps, which have
|
||||
// `appliesTo`). So pantry deduction for a batch-cook recipe happens once,
|
||||
// on the first dish marked cooked, rather than per-dish.
|
||||
let isFirstBatchCook = false;
|
||||
if (data.batchDishId) {
|
||||
const dish = await db.query.recipeBatchDishes.findFirst({
|
||||
where: and(eq(recipeBatchDishes.id, data.batchDishId), eq(recipeBatchDishes.recipeId, id)),
|
||||
});
|
||||
if (!dish) return NextResponse.json({ error: "Dish not found" }, { status: 404 });
|
||||
|
||||
const priorCook = await db.query.cookingHistory.findFirst({
|
||||
where: and(eq(cookingHistory.recipeId, id), eq(cookingHistory.userId, userId)),
|
||||
});
|
||||
isFirstBatchCook = !priorCook;
|
||||
}
|
||||
|
||||
await db.insert(cookingHistory).values({
|
||||
@@ -44,11 +54,14 @@ export async function POST(req: NextRequest, { params }: Params) {
|
||||
cookedAt: new Date(),
|
||||
});
|
||||
|
||||
if (data.deductFromPantry && !data.batchDishId) {
|
||||
if (data.deductFromPantry && (!data.batchDishId || isFirstBatchCook)) {
|
||||
const ings = await db.query.recipeIngredients.findMany({
|
||||
where: eq(recipeIngredients.recipeId, id),
|
||||
});
|
||||
const scale = data.servings ? data.servings / recipe.baseServings : 1;
|
||||
// A batch session's merged ingredient list is deducted once as a whole,
|
||||
// regardless of which single dish triggered the first cook — never
|
||||
// scaled by that one dish's serving count.
|
||||
const scale = data.batchDishId ? 1 : (data.servings ? data.servings / recipe.baseServings : 1);
|
||||
const userPantry = await db.query.pantryItems.findMany({
|
||||
where: eq(pantryItems.userId, userId),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user