feat(recipe): add step quantities and appliance settings
Release Drafter / auto_label (push) Skipped
Backend Lint and Test / tests (sqlite) (push) Canceled after 0s
Backend Lint and Test / tests (postgres) (push) Canceled after 0s
Docker Nightly Production / Backend Server Tests (push) Canceled after 0s
Frontend Lint and Test / lint (push) Canceled after 0s
Docker Nightly Production / Frontend Tests (push) Canceled after 0s
Build Package / Build frontend and wheel (push) Canceled after 0s
Docker Nightly Production / Build Package (push) Canceled after 0s
Docker Nightly Production / Build E2E Image Cache (push) Canceled after 0s
Docker Nightly Production / Build Tagged Release (push) Canceled after 0s
Docker Nightly Production / Notify Discord (push) Canceled after 0s
CodeQL / Analyze (javascript-typescript) (push) Canceled after 0s
CodeQL / Analyze (python) (push) Canceled after 0s
Release Drafter / draft_release (push) Canceled after 0s

This commit is contained in:
jfmcarreira committed 2026-11-30 14:44:17 +00:00
1 parent 1dd63a070b
commit 05cfb98ceb
32 files changed
+735 -46

No files matched your search

@@ -17,14 +17,15 @@ import { useIngredientTextParser } from "~/composables/recipes";
interface Props {
ingredient?: RecipeIngredient;
scale?: number;
showZero?: boolean;
}
const { ingredient, scale = 1 } = defineProps<Props>();
const { ingredient, scale = 1, showZero = false } = defineProps<Props>();
const { useParsedIngredientText } = useIngredientTextParser();
const baseText = computed(() => {
if (!ingredient) return "";
const parsed = useParsedIngredientText(ingredient, scale);
const parsed = useParsedIngredientText(ingredient, scale, true, undefined, showZero);
return [parsed.quantity, parsed.unit, parsed.name].filter(Boolean).join(" ").trim();
});
</script>
@@ -45,10 +45,12 @@ interface Props {
// off by default: the shopping list and the add-to-list dialog reuse this row, and a menu
// button is noise in both. the recipe renderer opts in
showSubstitutions?: boolean;
showZero?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
scale: 1,
showSubstitutions: false,
showZero: false,
});
const route = useRoute();
const auth = useMealieAuth();
@@ -56,7 +58,7 @@ const groupSlug = computed(() => route.params.groupSlug || auth.user?.value?.gro
const { useParsedIngredientText } = useIngredientTextParser();
const parsedIng = computed(() => {
return useParsedIngredientText(props.ingredient, props.scale, true, groupSlug.value.toString());
return useParsedIngredientText(props.ingredient, props.scale, true, groupSlug.value.toString(), props.showZero);
});
</script>
@@ -98,4 +98,17 @@ describe("RecipeIngredients", () => {
const labels = wrapper.findAll("input[type='checkbox']").map(input => input.attributes("aria-label"));
expect(labels).toEqual(["2 cups flour", "salt to taste"]);
});
test("tracks separate portions independently while keeping legacy references shared", async () => {
const first = mountIngredients([ingredients.curryPaste]);
await first.setProps({ portionKey: "step-a", portionReferenceIds: [ingredients.curryPaste.referenceId] });
await first.find(".checkbox").trigger("click");
const second = mountIngredients([ingredients.curryPaste]);
await second.setProps({ portionKey: "step-b", portionReferenceIds: [ingredients.curryPaste.referenceId] });
expect(second.find(".checkbox").attributes("aria-pressed")).toBe("false");
first.unmount();
const restored = mountIngredients([ingredients.curryPaste]);
await restored.setProps({ portionKey: "step-a", portionReferenceIds: [ingredients.curryPaste.referenceId] });
expect(restored.find(".checkbox").attributes("aria-pressed")).toBe("true");
});
});
@@ -32,7 +32,7 @@
<template #prepend>
<v-checkbox
:model-value="isChecked(index)"
:aria-label="parseIngredientText(ingredient, scale, false)"
:aria-label="parseIngredientText(ingredient, scale, false, isExplicitZero(ingredient))"
hide-details
class="pt-0 mt-0"
color="secondary"
@@ -45,6 +45,7 @@
<RecipeIngredientListItem
:ingredient="ingredient"
:scale="scale"
:show-zero="isExplicitZero(ingredient)"
show-substitutions
/>
</v-list-item-title>
@@ -65,16 +66,26 @@ interface Props {
scale?: number;
isCookMode?: boolean;
storageKey?: string;
portionKey?: string;
portionReferenceIds?: string[];
zeroPortionReferenceIds?: string[];
}
const props = withDefaults(defineProps<Props>(), {
value: () => [],
scale: 1,
isCookMode: false,
storageKey: undefined,
portionKey: undefined,
portionReferenceIds: () => [],
zeroPortionReferenceIds: () => [],
});
const { parseIngredientText } = useIngredientTextParser();
function isExplicitZero(ingredient: RecipeIngredient) {
return !!ingredient.referenceId && props.zeroPortionReferenceIds.includes(ingredient.referenceId);
}
function validateTitle(title?: string | null) {
return !(title === undefined || title === "" || title === null);
}
@@ -112,7 +123,10 @@ function checkedState() {
function checkedKey(index: number) {
const referenceId = props.value[index]?.referenceId;
return referenceId ? `ref:${referenceId}` : `idx:${index}`;
const key = referenceId ? `ref:${referenceId}` : `idx:${index}`;
return props.portionKey && referenceId && props.portionReferenceIds.includes(referenceId)
? `step:${props.portionKey}:${key}`
: key;
}
function isChecked(index: number) {
@@ -95,7 +95,7 @@
<RecipePageInstructions
v-model="recipe.recipeInstructions"
v-model:assets="recipe.assets"
:recipe="displayedRecipe"
:recipe="recipe"
:scale="scale"
:ingredient-storage-key="ingredientStorageKey"
/>
@@ -121,7 +121,7 @@
v-model="recipe"
class="px-1 my-4 d-print-none"
/>
<RecipePrintContainer :recipe="displayedRecipe" :scale="scale" />
<RecipePrintContainer :recipe="displayedRecipe" :source-ingredients="recipe.recipeIngredient" :scale="scale" />
</v-container>
<!-- Floating save button when toolbar scrolls out of view -->
<v-fab
@@ -176,7 +176,7 @@
v-model="recipe.recipeInstructions"
v-model:assets="recipe.assets"
class="overflow-y-hidden px-4"
:recipe="displayedRecipe"
:recipe="recipe"
:scale="scale"
:ingredient-storage-key="ingredientStorageKey"
/>
@@ -191,7 +191,7 @@
v-model="recipe.recipeInstructions"
v-model:assets="recipe.assets"
class="overflow-y-hidden mt-n5 px-2 px-md-4"
:recipe="displayedRecipe"
:recipe="recipe"
:scale="scale"
:ingredient-storage-key="ingredientStorageKey"
/>
@@ -0,0 +1,68 @@
import { mount } from "@vue/test-utils";
import { describe, expect, test, vi } from "vitest";
import { ref } from "vue";
import { createVuetify } from "vuetify";
import * as components from "vuetify/components";
import * as directives from "vuetify/directives";
import RecipePageInstructions from "./RecipePageInstructions.vue";
import { makeRecipe } from "~/tests/factories";
vi.mock("vue-draggable-plus", () => ({
VueDraggable: { template: "<div><slot /></div>" },
}));
vi.mock("~/composables/api", () => ({
useUserApi: () => ({}),
useStaticRoutes: () => ({ recipeAssetPath: () => "" }),
}));
vi.mock("~/composables/recipe-page/shared-state", () => ({
usePageState: () => ({ isCookMode: ref(false), isEditForm: ref(true), toggleCookMode: () => {} }),
}));
vi.mock("~/composables/recipe-page/use-extract-ingredient-references", () => ({
useExtractIngredientReferences: () => ({ extractIngredientReferences: () => [] }),
}));
vi.mock("~/composables/use-locales", () => ({
useLocales: () => ({ locales: [{ value: "en-US" }], locale: { value: "en-US" } }),
}));
describe("RecipePageInstructions", () => {
test("edits fractional ingredient portions without rounding on blur", async () => {
const recipe = makeRecipe({
recipeIngredient: [{ referenceId: "ingredient", quantity: 2, food: { name: "flour" } }],
recipeInstructions: [{ id: "step", text: "Mix", ingredientReferences: [{ referenceId: "ingredient", quantity: 0.5 }] }],
});
const wrapper = mount(RecipePageInstructions, {
props: { recipe, modelValue: recipe.recipeInstructions, assets: [] },
global: {
plugins: [createVuetify({ components, directives })],
mocks: { $globals: { icons: {} } },
stubs: {
BaseDialog: true,
BaseButton: true,
BaseButtonGroup: true,
DropZone: { template: "<div><slot /></div>" },
MarkdownEditor: true,
RecipeStepCooking: true,
},
},
});
const field = wrapper.findComponent(components.VNumberInput);
expect(field.props("precision")).toBeNull();
const input = field.find("input");
expect(input.element.value).toBe("0.5");
await input.trigger("focus");
await input.setValue("1.");
input.element.setSelectionRange(2, 2);
const decimalDigit = new InputEvent("beforeinput", {
bubbles: true,
cancelable: true,
inputType: "insertText",
data: "2",
});
expect(input.element.dispatchEvent(decimalDigit)).toBe(true);
await input.setValue("1.25");
await input.trigger("blur");
expect(recipe.recipeInstructions[0].ingredientReferences?.[0].quantity).toBe(1.25);
expect(input.element.value).toBe("1.25");
});
});
@@ -423,6 +423,19 @@
:ingredient="ingredientLookup[linkRef.referenceId]"
:scale="scale"
/>
<v-number-input
v-model="linkRef.quantity"
:label="$t('recipe.step-quantity')"
:min="0"
:precision="null"
density="compact"
control-variant="hidden"
clearable
@click.stop
/>
<div v-if="linkRef.referenceId && overallocatedIds.has(linkRef.referenceId)" class="text-warning text-body-2">
{{ $t('recipe.step-quantity-exceeds') }}
</div>
</div>
</div>
<div
@@ -445,6 +458,7 @@
:is-edit-mode="isEditForm"
@update:model-value="step.durationSeconds = $event"
/>
<RecipeStepCooking v-model="step.cooking" edit />
</v-card-text>
</DropZone>
@@ -465,13 +479,13 @@
class="ml-n4"
>
<RecipeIngredients
:value="recipe.recipeIngredient.filter((ing) => {
if (!step.ingredientReferences) return false
return step.ingredientReferences.map((ref) => ref.referenceId).includes(ing.referenceId || '')
})"
:value="displayStepIngredients(step)"
:scale="scale"
:is-cook-mode="isCookMode"
:storage-key="ingredientStorageKey"
:portion-key="step.id ?? undefined"
:portion-reference-ids="portionReferenceIds"
:zero-portion-reference-ids="zeroPortionIds(step)"
/>
</div>
<v-divider
@@ -503,6 +517,16 @@
class="markdown"
:source="step.text"
/>
<div v-if="!isCookMode && hasLinkedIngredients(step)" class="mt-2">
<RecipeIngredientHtml
v-for="(ingredient, i) in displayStepIngredients(step)"
:key="ingredient.referenceId ?? i"
:ingredient="ingredient"
:scale="scale"
:show-zero="!!ingredient.referenceId && zeroPortionIds(step).includes(ingredient.referenceId)"
/>
</div>
<RecipeStepCooking :model-value="step.cooking" />
</v-col>
</v-row>
</v-card-text>
@@ -532,6 +556,10 @@ import DropZone from "~/components/global/DropZone.vue";
import { alert } from "~/composables/use-toast";
import RecipeIngredients from "~/components/Domain/Recipe/RecipeIngredients.vue";
import RecipeIngredientHtml from "~/components/Domain/Recipe/RecipeIngredientHtml.vue";
import RecipeStepCooking from "~/components/Domain/Recipe/RecipeStepCooking.vue";
import { overallocatedIngredientIds, stepIngredients } from "~/lib/recipe/step-ingredients";
import { useUnitConversion } from "~/composables/recipes/use-unit-conversion";
import { useUnitSystem } from "~/composables/recipes/use-unit-system";
import { mergeSteps, undoStepMerge, type StepMerge } from "~/lib/recipe/instruction-merge";
import CookTime from "./CookTime.vue";
@@ -558,6 +586,19 @@ const emit = defineEmits(["click-instruction-field", "update:assets"]);
const i18n = useI18n();
const { isCookMode, toggleCookMode, isEditForm } = usePageState(props.recipe.slug);
const { extractIngredientReferences } = useExtractIngredientReferences();
const { convertIngredient } = useUnitConversion();
const { unitSystem } = useUnitSystem();
function displayStepIngredients(step: RecipeStep) {
const ingredients = stepIngredients(step, props.recipe.recipeIngredient);
return unitSystem.value ? ingredients.map(ingredient => convertIngredient(ingredient, unitSystem.value!, props.scale)) : ingredients;
}
function zeroPortionIds(step: RecipeStep): string[] {
return (step.ingredientReferences ?? [])
.filter(ref => ref.quantity === 0 && ref.referenceId)
.map(ref => ref.referenceId!);
}
const dialog = ref(false);
const disabledSteps = ref<number[]>([]);
@@ -678,6 +719,10 @@ const activeNoteReferenceIds = ref<string[]>([]);
const activeText = ref("");
const linkedNotesSheetOpen = ref(false);
const activeStepLinkedNotes = ref<RecipeNote[]>([]);
const overallocatedIds = computed(() => overallocatedIngredientIds(instructionList.value, props.recipe.recipeIngredient));
const portionReferenceIds = computed(() => [...new Set(instructionList.value.flatMap(step =>
(step.ingredientReferences ?? []).filter(ref => ref.quantity != null && ref.referenceId).map(ref => ref.referenceId!),
))]);
const availableDialogNextStep = computed(() => activeLinkerIndex.value < instructionList.value.length - 1);
const activeDialogStepText = computed(() => activeText.value);
@@ -722,7 +767,7 @@ function saveDialogLinks() {
}
step.ingredientReferences = activeRefs.value.map((referenceId) => {
return { referenceId };
return step.ingredientReferences?.find(ref => ref.referenceId === referenceId) ?? { referenceId };
});
step.noteReferences = activeNoteReferenceIds.value.map((referenceId) => {
@@ -891,6 +936,9 @@ function mergeAbove(target: number, source: number) {
if (merge) {
mergeHistory.value.push(merge);
}
else if (target >= 0) {
alert.error(i18n.t("recipe.step-merge-conflict"));
}
}
function undoMerge(event: KeyboardEvent) {
@@ -2,6 +2,7 @@
<div class="print-container">
<RecipePrintView
:recipe="recipe"
:source-ingredients="sourceIngredients"
:scale="scale"
:density="'compact'"
/>
@@ -10,11 +11,12 @@
<script setup lang="ts">
import RecipePrintView from "~/components/Domain/Recipe/RecipePrintView.vue";
import type { RecipeOut } from "~/lib/api/types/recipe";
import type { RecipeIngredient, RecipeOut } from "~/lib/api/types/recipe";
interface Props {
recipe: RecipeOut;
scale?: number;
sourceIngredients?: RecipeIngredient[];
}
withDefaults(defineProps<Props>(), {
@@ -0,0 +1,42 @@
import { mount } from "@vue/test-utils";
import { describe, expect, test, vi } from "vitest";
import RecipePrintView from "./RecipePrintView.vue";
import { makeRecipe } from "~/tests/factories";
vi.mock("~/composables/api", () => ({
useStaticRoutes: () => ({ recipeImage: () => "" }),
}));
vi.mock("~/composables/use-locales", () => ({
useLocales: () => ({ locales: [{ value: "en-US" }], locale: { value: "en-US" } }),
}));
describe("RecipePrintView", () => {
test("renders ingredients and places each cooking operation with its step", () => {
const recipe = makeRecipe({
recipeIngredient: [{ referenceId: "ingredient", quantity: 100, food: { name: "flour" } }],
recipeInstructions: [
{ text: "Mix", durationSeconds: 180, cooking: { temperatureCelsius: 120, speed: "spoon" } },
{ text: "Rest" },
],
});
const wrapper = mount(RecipePrintView, {
props: { recipe },
global: {
mocks: { $globals: { icons: { primary: "", potSteam: "" } } },
stubs: {
SafeMarkdown: { props: ["source"], template: "<div>{{ source }}</div>" },
SafeInlineHtml: { props: ["html"], template: "<span>{{ html }}</span>" },
RecipeTimeCard: true,
},
},
});
expect(wrapper.find(".ingredient-cell").text()).toContain("flour");
expect(wrapper.find(".ingredient-cell").text()).not.toContain("120");
const steps = wrapper.findAll(".recipe-step-body");
expect(steps).toHaveLength(2);
expect(steps[0].element.parentElement?.textContent).toContain("120 °C");
expect(steps[0].element.parentElement?.textContent).toContain("3m");
expect(steps[1].element.parentElement?.textContent).not.toContain("120 °C");
});
});
@@ -136,6 +136,8 @@
:source="step.text"
class="recipe-step-body"
/>
<CookTime :model-value="step.durationSeconds" :is-edit-mode="false" />
<RecipeStepCooking :model-value="step.cooking" />
<!-- Step Ingredients -->
<div
v-if="preferences.showLinkedIngredients && step.ingredientReferences && step.ingredientReferences.length > 0"
@@ -155,7 +157,7 @@
:key="`ingredient-${ingredientIndex}`"
>
<p class="ingredient-body">
<SafeInlineHtml :html="parseText(ingredient)" />
<SafeInlineHtml :html="parseText(ingredient, step.ingredientReferences?.some(ref => ref.referenceId === ingredient.referenceId && ref.quantity === 0))" />
</p>
</template>
</div>
@@ -224,6 +226,11 @@ import { ImagePosition, useUserPrintPreferences } from "~/composables/use-users/
import { ingredientSubstitutionSummary, useFoodPlurality, useIngredientTextParser, useNutritionLabels } from "~/composables/recipes";
import { usePageState } from "~/composables/recipe-page/shared-state";
import { useScaledAmount } from "~/composables/recipes/use-scaled-amount";
import CookTime from "~/components/Domain/Recipe/RecipePage/RecipePageParts/CookTime.vue";
import RecipeStepCooking from "~/components/Domain/Recipe/RecipeStepCooking.vue";
import { stepIngredients } from "~/lib/recipe/step-ingredients";
import { useUnitConversion } from "~/composables/recipes/use-unit-conversion";
import { useUnitSystem } from "~/composables/recipes/use-unit-system";
type IngredientSection = {
sectionName: string;
@@ -240,6 +247,7 @@ interface Props {
recipe: RecipeOut;
scale?: number;
dense?: boolean;
sourceIngredients?: RecipeIngredient[];
}
const props = withDefaults(defineProps<Props>(), {
scale: 1,
@@ -251,6 +259,8 @@ const preferences = useUserPrintPreferences();
const { recipeImage } = useStaticRoutes();
const { imageKey } = usePageState(props.recipe.slug);
const { labels } = useNutritionLabels();
const { convertIngredient } = useUnitConversion();
const { unitSystem } = useUnitSystem();
const servingsDisplay = computed(() => {
const { scaledAmountDisplay } = useScaledAmount(props.recipe.recipeYieldQuantity, props.scale);
@@ -395,11 +405,10 @@ const stepLinkedIngredients = computed(() => {
return;
}
const referenceIds = new Set(step.ingredientReferences.map(ref => ref.referenceId));
map.set(
`${sectionIndex}-${stepIndex}`,
props.recipe.recipeIngredient.filter(ing => ing.referenceId && referenceIds.has(ing.referenceId)),
);
const ingredients = stepIngredients(step, props.sourceIngredients ?? props.recipe.recipeIngredient);
map.set(`${sectionIndex}-${stepIndex}`, props.sourceIngredients && unitSystem.value
? ingredients.map(ingredient => convertIngredient(ingredient, unitSystem.value!, props.scale))
: ingredients);
});
});
@@ -408,8 +417,8 @@ const stepLinkedIngredients = computed(() => {
const { parseIngredientText } = useIngredientTextParser();
function parseText(ingredient: RecipeIngredient) {
return parseIngredientText(ingredient, props.scale);
function parseText(ingredient: RecipeIngredient, showZero = false) {
return parseIngredientText(ingredient, props.scale, true, showZero);
}
const { shouldPluralizeFood } = useFoodPlurality();
@@ -0,0 +1,35 @@
import { mount } from "@vue/test-utils";
import { describe, expect, test } from "vitest";
import { createVuetify } from "vuetify";
import * as components from "vuetify/components";
import * as directives from "vuetify/directives";
import RecipeStepCooking from "./RecipeStepCooking.vue";
describe("RecipeStepCooking", () => {
test("displays numeric and named settings", () => {
const wrapper = mount(RecipeStepCooking, {
props: { modelValue: { appliance: "thermomix", temperatureCelsius: 120, speed: "spoon", mode: "steaming" } },
});
expect(wrapper.text()).toContain("120 °C");
expect(wrapper.text()).toContain("Speed: spoon");
expect(wrapper.text()).toContain("steaming");
});
test("edits whole degrees without replacing an imported fraction on focus and blur", async () => {
const wrapper = mount(RecipeStepCooking, {
props: { modelValue: { temperatureCelsius: 37.5 }, edit: true },
global: { plugins: [createVuetify({ components, directives })] },
});
const field = wrapper.findComponent(components.VNumberInput);
const input = field.find("input");
expect(field.props("precision")).toBe(0);
expect(field.props("step")).toBe(1);
expect(input.element.value).toBe("38");
expect(wrapper.text()).toContain("37.5 °C");
await input.trigger("focus");
await input.trigger("blur");
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
await input.setValue("39");
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([{ temperatureCelsius: 39 }]);
});
});
@@ -0,0 +1,78 @@
<template>
<div v-if="edit" class="mt-3" @click.stop>
<div class="text-subtitle-2">
{{ $t("recipe.step-cooking") }}
</div>
<v-text-field :model-value="modelValue?.appliance" :label="$t('recipe.step-appliance')" clearable density="compact" @update:model-value="update('appliance', $event || null)" />
<v-number-input
:model-value="inputTemperature"
:label="$t('recipe.step-temperature')"
:precision="0"
:step="1"
:hint="fractionalTemperature ? $t('recipe.step-temperature-saved', { temperature: modelValue?.temperatureCelsius }) : undefined"
persistent-hint
hide-details="auto"
density="compact"
control-variant="hidden"
clearable
@update:model-value="updateTemperature"
/>
<v-text-field
:model-value="modelValue?.speed"
:label="$t('recipe.step-speed')"
clearable
density="compact"
@change="updateSpeed(($event.target as HTMLInputElement).value)"
@click:clear="updateSpeed(null)"
/>
<v-text-field :model-value="modelValue?.mode" :label="$t('recipe.step-mode')" clearable density="compact" @update:model-value="update('mode', $event || null)" />
<v-btn v-if="modelValue" variant="text" size="small" @click="emit('update:modelValue', null)">
{{ $t("recipe.step-cooking-clear") }}
</v-btn>
</div>
<div v-else-if="modelValue && parts.length" class="text-body-2 mt-2">
{{ parts.join(" · ") }}
</div>
</template>
<script setup lang="ts">
import type { StepCooking } from "~/lib/api/types/recipe";
const props = defineProps<{ modelValue?: StepCooking | null; edit?: boolean }>();
const emit = defineEmits<{ "update:modelValue": [value: StepCooking | null] }>();
const { t } = useI18n();
// Keep imported fractional temperatures until the user changes the displayed value.
const inputTemperature = computed(() => props.modelValue?.temperatureCelsius == null
? null
: Math.round(props.modelValue.temperatureCelsius));
const fractionalTemperature = computed(() => props.modelValue?.temperatureCelsius != null
&& !Number.isInteger(props.modelValue.temperatureCelsius));
function updateTemperature(value: number | null) {
if (value !== inputTemperature.value) {
update("temperatureCelsius", value);
}
}
function update<K extends keyof StepCooking>(key: K, value: StepCooking[K]) {
emit("update:modelValue", { ...props.modelValue, [key]: value });
}
function updateSpeed(value: string | null) {
const text = String(value ?? "").trim();
const numeric = Number(text);
update("speed", !text ? null : Number.isFinite(numeric) ? numeric : text);
}
const parts = computed(() => {
const cooking = props.modelValue;
if (!cooking) return [];
return [
cooking.appliance,
cooking.temperatureCelsius != null ? `${cooking.temperatureCelsius} °C` : null,
cooking.speed != null ? t("recipe.step-speed-value", { speed: cooking.speed }) : null,
cooking.mode,
].filter(Boolean);
});
</script>
@@ -3,10 +3,11 @@ import type { RecipeIngredient } from "~/lib/api/types/recipe";
import { useIngredientTextParser } from "../use-recipe-ingredients";
import { useLocales } from "~/composables/use-locales";
import { makeRecipe } from "~/tests/factories";
import { stepIngredients } from "~/lib/recipe/step-ingredients";
vi.mock("~/composables/use-locales");
let parseIngredientText: (ingredient: RecipeIngredient, scale?: number, includeFormating?: boolean) => string;
let parseIngredientText: ReturnType<typeof useIngredientTextParser>["parseIngredientText"];
let ingredientToParserString: (ingredient: RecipeIngredient) => string;
let useParsedIngredientText: ReturnType<typeof useIngredientTextParser>["useParsedIngredientText"];
@@ -32,6 +33,19 @@ describe("parseIngredientText", () => {
...overrides,
});
test("scales explicit step quantities without changing the recipe ingredient", () => {
const original = createRecipeIngredient({ referenceId: "i", quantity: 100 });
const [portion] = stepIngredients({ text: "Mix", ingredientReferences: [{ referenceId: "i", quantity: 20 }] }, [original]);
expect(parseIngredientText(portion, 2, false)).toContain("40");
expect(original.quantity).toBe(100);
});
test("shows an explicit zero portion without changing legacy zero display", () => {
const ingredient = createRecipeIngredient({ quantity: 0 });
expect(parseIngredientText(ingredient, 1, false, true)).toContain("0 cup");
expect(parseIngredientText(ingredient, 1, false)).not.toContain("0");
});
test("adds note section if note present", () => {
const ingredient = createRecipeIngredient({ note: "custom note" });
@@ -90,13 +90,16 @@ export function useFoodPlurality() {
export function useIngredientTextParser() {
const { shouldPluralizeFood } = useFoodPlurality();
function useParsedIngredientText(ingredient: RecipeIngredient, scale = 1, includeFormating = true, groupSlug?: string): ParsedIngredientText {
function useParsedIngredientText(ingredient: RecipeIngredient, scale = 1, includeFormating = true, groupSlug?: string, showZero = false): ParsedIngredientText {
const { quantity, food, unit, note, referencedRecipe } = ingredient;
const usePluralUnit = quantity !== undefined && ((quantity || 0) * scale > 1 || (quantity || 0) * scale === 0);
const usePluralFood = shouldPluralizeFood(ingredient, scale);
let returnQty = "";
if (showZero && quantity === 0) {
returnQty = "0";
}
// casting to number is required as sometimes quantity is a string
if (quantity && Number(quantity) !== 0) {
const scaledQuantity = Number((quantity * scale));
@@ -133,15 +136,15 @@ export function useIngredientTextParser() {
return {
quantity: returnQty || undefined,
unit: unitName && quantity ? unitName : undefined,
unit: unitName && (quantity || (showZero && quantity === 0)) ? unitName : undefined,
name: ingName || undefined,
note: note || undefined,
recipeLink: useRecipeLink(referencedRecipe || undefined, groupSlug),
};
};
function parseIngredientText(ingredient: RecipeIngredient, scale = 1, includeFormating = true): string {
const { quantity, unit, name, note } = useParsedIngredientText(ingredient, scale, includeFormating);
function parseIngredientText(ingredient: RecipeIngredient, scale = 1, includeFormating = true, showZero = false): string {
const { quantity, unit, name, note } = useParsedIngredientText(ingredient, scale, includeFormating, undefined, showZero);
return `${quantity || ""} ${unit || ""} ${name || ""} ${note || ""}`.replace(/ {2,}/g, " ").trim();
};
+11
View File
@@ -592,6 +592,17 @@
"linked-notes-with-count": "Linked Notes ({count})",
"no-notes-to-link": "No notes to link",
"merge-above": "Merge Above",
"step-quantity": "Quantity for this step (original units)",
"step-quantity-exceeds": "Explicit step quantities exceed the recipe ingredient quantity.",
"step-cooking": "Cooking operation",
"step-appliance": "Appliance",
"step-temperature": "Temperature (°C)",
"step-temperature-saved": "Saved temperature: {temperature} °C. Changing this field replaces it with whole degrees.",
"step-speed": "Speed (number or name)",
"step-speed-value": "Speed: {speed}",
"step-mode": "Mode",
"step-cooking-clear": "Clear cooking operation",
"step-merge-conflict": "These steps cannot be merged without losing a title, summary, cooking settings or ingredient quantities.",
"move-to-bottom": "Move To Bottom",
"move-to-top": "Move To Top",
"decrease-scale-label": "Decrease Scale by 1",
+8
View File
@@ -467,13 +467,21 @@ export interface RecipeStep {
ingredientReferences?: IngredientReferences[];
noteReferences?: NoteReference[];
durationSeconds?: number | null;
cooking?: StepCooking | null;
}
export interface IngredientReferences {
referenceId?: string | null;
quantity?: number | null;
}
export interface NoteReference {
referenceId?: string | null;
}
export interface StepCooking {
appliance?: string | null;
temperatureCelsius?: number | null;
speed?: number | string | null;
mode?: string | null;
}
export interface Nutrition {
calories?: string | null;
carbohydrateContent?: string | null;
+8
View File
@@ -205,6 +205,7 @@ export interface IngredientFoodSave {
}
export interface IngredientReferences {
referenceId?: string | null;
quantity?: number | null;
}
export interface IngredientRequest {
parser?: RegisteredParser;
@@ -380,6 +381,13 @@ export interface RecipeStep {
ingredientReferences?: IngredientReferences[];
noteReferences?: NoteReference[];
durationSeconds?: number | null;
cooking?: StepCooking | null;
}
export interface StepCooking {
appliance?: string | null;
temperatureCelsius?: number | null;
speed?: number | string | null;
mode?: string | null;
}
export interface RecipeAsset {
name: string;
@@ -5,7 +5,7 @@ import type { RecipeStep } from "~/lib/api/types/recipe";
function step(id: string, overrides: Partial<RecipeStep> = {}): RecipeStep {
return {
id,
title: `Title ${id}`,
title: "",
text: `Text ${id}`,
ingredientReferences: [],
noteReferences: [],
@@ -18,6 +18,29 @@ function refs(...ids: string[]) {
}
describe("mergeSteps", () => {
test("preserves cooking and sums explicit portions, including on undo", () => {
const steps = [
step("a", { ingredientReferences: [{ referenceId: "i1", quantity: 20 }] }),
step("b", { ingredientReferences: [{ referenceId: "i1", quantity: 30 }], durationSeconds: 180, cooking: { speed: "spoon" } }),
];
const original = structuredClone(steps);
const merge = mergeSteps(steps, 0, 1)!;
expect(steps[0].ingredientReferences?.[0].quantity).toBe(50);
expect(steps[0].cooking?.speed).toBe("spoon");
expect(steps[0].durationSeconds).toBe(180);
undoStepMerge(steps, merge);
expect(steps).toEqual(original);
});
test("rejects ambiguous operations and mixed inherited and explicit portions", () => {
const operations = [step("a", { cooking: { speed: 1 } }), step("b", { durationSeconds: 20 })];
expect(mergeSteps(operations, 0, 1)).toBeNull();
expect(operations).toHaveLength(2);
const portions = [step("a", { ingredientReferences: refs("i1") }), step("b", { ingredientReferences: [{ referenceId: "i1", quantity: 2 }] })];
expect(mergeSteps(portions, 0, 1)).toBeNull();
expect(portions).toHaveLength(2);
expect(mergeSteps([step("a"), step("b", { summary: "Keep this" })], 0, 1)).toBeNull();
});
test("appends the source text and removes the source step", () => {
const steps = [step("a"), step("b"), step("c")];
@@ -63,7 +86,7 @@ describe("undoStepMerge", () => {
test("restores both steps as they were before the merge", () => {
const original = [
step("a", { ingredientReferences: refs("i1"), noteReferences: refs("n1") }),
step("b", { ingredientReferences: refs("i2"), noteReferences: refs("n2"), summary: "s", durationSeconds: 60 }),
step("b", { ingredientReferences: refs("i2"), noteReferences: refs("n2"), durationSeconds: 60 }),
];
const steps = structuredClone(original);
+32 -3
View File
@@ -3,7 +3,7 @@ import type { RecipeStep } from "~/lib/api/types/recipe";
export interface StepMerge {
target: number;
source: number;
targetStep: Pick<RecipeStep, "text" | "ingredientReferences" | "noteReferences">;
targetStep: Pick<RecipeStep, "text" | "ingredientReferences" | "noteReferences" | "durationSeconds" | "cooking">;
sourceStep: RecipeStep;
}
@@ -19,10 +19,35 @@ function mergeReferences<T extends { referenceId?: string | null }>(target: T[]
export function mergeSteps(steps: RecipeStep[], target: number, source: number): StepMerge | null {
const targetStep = steps[target];
const sourceStep = steps[source];
if (!targetStep || !sourceStep) {
if (!targetStep || !sourceStep || target === source) {
return null;
}
// A single step cannot retain two independent section titles or summaries.
if (sourceStep.title || sourceStep.summary) {
return null;
}
// Two operations cannot be represented faithfully by the single-operation schema.
if ((targetStep.cooking || targetStep.durationSeconds) && (sourceStep.cooking || sourceStep.durationSeconds)) {
return null;
}
const ingredientReferences = [...(targetStep.ingredientReferences ?? [])];
for (const ref of sourceStep.ingredientReferences ?? []) {
const index = ingredientReferences.findIndex(existing => existing.referenceId === ref.referenceId);
if (index < 0) {
ingredientReferences.push(ref);
}
else {
const existing = ingredientReferences[index];
if ((existing.quantity == null) !== (ref.quantity == null)) {
return null; // An inherited quantity cannot be added to an explicit portion.
}
if (existing.quantity != null && ref.quantity != null) {
ingredientReferences[index] = { ...existing, quantity: existing.quantity + ref.quantity };
}
}
}
const merge: StepMerge = {
target,
source,
@@ -30,13 +55,17 @@ export function mergeSteps(steps: RecipeStep[], target: number, source: number):
text: targetStep.text,
ingredientReferences: targetStep.ingredientReferences,
noteReferences: targetStep.noteReferences,
durationSeconds: targetStep.durationSeconds,
cooking: targetStep.cooking,
},
sourceStep,
};
targetStep.text += " " + sourceStep.text;
targetStep.ingredientReferences = mergeReferences(targetStep.ingredientReferences, sourceStep.ingredientReferences);
targetStep.ingredientReferences = ingredientReferences;
targetStep.noteReferences = mergeReferences(targetStep.noteReferences, sourceStep.noteReferences);
targetStep.durationSeconds = targetStep.durationSeconds ?? sourceStep.durationSeconds;
targetStep.cooking = targetStep.cooking ?? sourceStep.cooking;
steps.splice(source, 1);
return merge;
@@ -0,0 +1,19 @@
import { describe, expect, test } from "vitest";
import { overallocatedIngredientIds, stepIngredients } from "./step-ingredients";
import type { RecipeIngredient, RecipeStep } from "~/lib/api/types/recipe";
describe("step ingredient portions", () => {
const ingredients: RecipeIngredient[] = [{ referenceId: "a", quantity: 100 }, { referenceId: "b", quantity: 2 }];
const step: RecipeStep = { text: "Mix", ingredientReferences: [{ referenceId: "a", quantity: 20 }, { referenceId: "b" }] };
test("uses overrides without changing the original list", () => {
const result = stepIngredients(step, ingredients);
expect(result.map(item => item.quantity)).toEqual([20, 2]);
expect(ingredients[0].quantity).toBe(100);
});
test("warns only when explicit portions exceed the total", () => {
const other: RecipeStep = { text: "Finish", ingredientReferences: [{ referenceId: "a", quantity: 81 }] };
expect([...overallocatedIngredientIds([step, other], ingredients)]).toEqual(["a"]);
});
});
@@ -0,0 +1,25 @@
import type { RecipeIngredient, RecipeStep } from "~/lib/api/types/recipe";
// Work on copies: the recipe-level list remains the source for shopping lists.
export function stepIngredients(step: RecipeStep, ingredients: RecipeIngredient[]): RecipeIngredient[] {
return (step.ingredientReferences ?? []).flatMap((reference) => {
const ingredient = ingredients.find(item => item.referenceId && item.referenceId === reference.referenceId);
if (!ingredient) return [];
return [{ ...ingredient, quantity: reference.quantity ?? ingredient.quantity, title: "" }];
});
}
export function overallocatedIngredientIds(steps: RecipeStep[], ingredients: RecipeIngredient[]): Set<string> {
const totals = new Map<string, number>();
for (const step of steps) {
for (const ref of step.ingredientReferences ?? []) {
if (ref.referenceId && ref.quantity != null) {
totals.set(ref.referenceId, (totals.get(ref.referenceId) ?? 0) + ref.quantity);
}
}
}
return new Set(ingredients.filter(ingredient =>
ingredient.referenceId && ingredient.quantity != null && ingredient.quantity > 0
&& (totals.get(ingredient.referenceId) ?? 0) > ingredient.quantity + 1e-9,
).map(ingredient => ingredient.referenceId!));
}
@@ -0,0 +1,23 @@
"""Add optional quantities to instruction ingredient references.
Revision ID: b742c6d50a10
Revises: a136609cde0f
"""
import sqlalchemy as sa
from alembic import op
revision = "b742c6d50a10"
down_revision = "a136609cde0f"
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table("recipe_ingredient_ref_link") as batch_op:
batch_op.add_column(sa.Column("quantity", sa.Float(), nullable=True))
def downgrade():
with op.batch_alter_table("recipe_ingredient_ref_link") as batch_op:
batch_op.drop_column("quantity")
@@ -0,0 +1,23 @@
"""Add optional cooking settings to instructions.
Revision ID: c981d7e62b11
Revises: b742c6d50a10
"""
import sqlalchemy as sa
from alembic import op
revision = "c981d7e62b11"
down_revision = "b742c6d50a10"
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table("recipe_instructions") as batch_op:
batch_op.add_column(sa.Column("cooking", sa.JSON(), nullable=True))
def downgrade():
with op.batch_alter_table("recipe_instructions") as batch_op:
batch_op.drop_column("cooking")
+3 -1
View File
@@ -1,4 +1,4 @@
from sqlalchemy import ForeignKey, Integer, String, orm
from sqlalchemy import JSON, Float, ForeignKey, Integer, String, orm
from sqlalchemy.orm import Mapped, mapped_column
from .._model_base import BaseMixins, SqlAlchemyBase
@@ -10,6 +10,7 @@ class RecipeIngredientRefLink(SqlAlchemyBase, BaseMixins):
__tablename__ = "recipe_ingredient_ref_link"
instruction_id: Mapped[GUID | None] = mapped_column(GUID, ForeignKey("recipe_instructions.id"), index=True)
reference_id: Mapped[GUID | None] = mapped_column(GUID, index=True)
quantity: Mapped[float | None] = mapped_column(Float)
@auto_init()
def __init__(self, **_) -> None:
@@ -36,6 +37,7 @@ class RecipeInstruction(SqlAlchemyBase):
text: Mapped[str | None] = mapped_column(String)
summary: Mapped[str | None] = mapped_column(String)
duration_seconds: Mapped[int | None] = mapped_column(Integer)
cooking: Mapped[dict | None] = mapped_column(JSON)
ingredient_references: Mapped[list[RecipeIngredientRefLink]] = orm.relationship(
RecipeIngredientRefLink, cascade="all, delete-orphan"
+2 -1
View File
@@ -90,7 +90,7 @@ from .recipe_share_token import (
RecipeShareTokenSave,
RecipeShareTokenSummary,
)
from .recipe_step import IngredientReferences, NoteReference, RecipeStep
from .recipe_step import IngredientReferences, NoteReference, RecipeStep, StepCooking
from .recipe_suggestion import (
RecipeSuggestionQuery,
RecipeSuggestionResponse,
@@ -145,6 +145,7 @@ __all__ = [
"IngredientReferences",
"NoteReference",
"RecipeStep",
"StepCooking",
"RecipeImageTypes",
"Nutrition",
"IngredientConfidence",
+14 -1
View File
@@ -1,7 +1,7 @@
from typing import Any
from uuid import UUID, uuid4
from pydantic import UUID4, ConfigDict, Field, field_validator
from pydantic import UUID4, ConfigDict, Field, FiniteFloat, field_validator
from mealie.schema._mealie import MealieModel
@@ -12,6 +12,7 @@ class IngredientReferences(MealieModel):
"""
reference_id: UUID4 | None = None
quantity: float | None = Field(default=None, ge=0, allow_inf_nan=False)
model_config = ConfigDict(from_attributes=True)
@@ -20,6 +21,17 @@ class NoteReference(MealieModel):
model_config = ConfigDict(from_attributes=True)
class StepCooking(MealieModel):
"""Optional appliance settings for the single operation represented by a step."""
model_config = ConfigDict(extra="forbid")
appliance: str | None = None
temperature_celsius: float | None = Field(default=None, allow_inf_nan=False)
speed: FiniteFloat | str | None = None
mode: str | None = None
class RecipeStep(MealieModel):
id: UUID | None = Field(default_factory=uuid4)
title: str | None = "" # This is the section title!!!
@@ -30,6 +42,7 @@ class RecipeStep(MealieModel):
model_config = ConfigDict(from_attributes=True)
duration_seconds: int | None = Field(default=None, ge=1, le=2147483647, strict=True)
cooking: StepCooking | None = None
@field_validator("duration_seconds", mode="before")
@classmethod
@@ -68,17 +68,18 @@ class EnrichInstructionsStep(WorkflowStep):
def _apply(
step: RecipeStep, details: OpenAIInstructionEnrichment, ingredient_ids: list[UUID], note_ids: list[UUID]
) -> None:
if ingredient_refs := _resolve_references(details.ingredients, ingredient_ids):
has_portions = any(ref.quantity is not None for ref in step.ingredient_references)
if not has_portions and (ingredient_refs := _resolve_references(details.ingredients, ingredient_ids)):
step.ingredient_references = [IngredientReferences(reference_id=ref) for ref in ingredient_refs]
if note_refs := _resolve_references(details.notes, note_ids):
step.note_references = [NoteReference(reference_id=ref) for ref in note_refs]
if details.duration and (seconds := cleaner.clean_duration(details.duration)):
if step.duration_seconds is None and details.duration and (seconds := cleaner.clean_duration(details.duration)):
step.duration_seconds = seconds
summary, text = (details.summary or "").strip(), (details.text or "").strip()
if summary and text and not step.summary:
if summary and text and not step.summary and not step.cooking and not has_portions:
step.summary, step.text = summary, text
async def run(self, ctx: WorkflowContext) -> None:
+16 -5
View File
@@ -410,9 +410,8 @@ class RecipeService(RecipeServiceBase):
elif not isinstance(data, dict):
return data
# extras is free-form user data, so it is copied as-is: walking into it would add the
# group and household keys stamped below to whatever the user stored there.
if key == "extras":
# JSON metadata has no ownership columns. Do not add group or household keys.
if key in ("extras", "cooking"):
return data
# force group_id and household_id to match the group id of the current user
@@ -556,17 +555,29 @@ class RecipeService(RecipeServiceBase):
new_recipe_data = old_recipe.model_dump(exclude={"id", "name", "slug", "image", "comments"}, round_trip=True)
draft = RecipeDraft.model_validate(new_recipe_data)
ingredient_reference_map = {
ingredient.reference_id: uuid4()
for ingredient in old_recipe.recipe_ingredient
if ingredient.reference_id is not None
}
# Asset images in steps directly link to the original recipe, so we
# need to update them to references to the assets we copy below
def replace_recipe_step(step: RecipeStep) -> RecipeStep:
new_id = uuid4()
new_text = step.text.replace(str(old_recipe.id), str(draft.id))
new_step = step.model_copy(update={"id": new_id, "text": new_text})
refs = [
ref.model_copy(
update={"reference_id": ingredient_reference_map.get(ref.reference_id, ref.reference_id)}
)
for ref in step.ingredient_references
]
new_step = step.model_copy(update={"id": new_id, "text": new_text, "ingredient_references": refs})
return new_step
# Copy ingredients to make them independent of the original
def copy_recipe_ingredient(ingredient: RecipeIngredient):
new_reference_id = uuid4()
new_reference_id = ingredient_reference_map.get(ingredient.reference_id, uuid4())
new_ingredient = ingredient.model_copy(update={"reference_id": new_reference_id})
return new_ingredient
@@ -64,8 +64,15 @@ def create_populated_recipe(api_client: TestClient, user: TestUser) -> dict:
"title": "Prep Work",
"summary": "Season the meat",
"text": "Season the **beef**.",
"ingredientReferences": [{"referenceId": reference_id}],
"ingredientReferences": [{"referenceId": reference_id, "quantity": 0.5}],
"noteReferences": [{"referenceId": note_reference_id}],
"durationSeconds": 180,
"cooking": {
"appliance": "thermomix",
"temperatureCelsius": 120,
"speed": "spoon",
"mode": "steaming",
},
}
],
}
@@ -91,6 +98,56 @@ def camel_case_export(api_client: TestClient, user: TestUser, slug: str) -> str:
EXPORTS: list[Callable[[TestClient, TestUser, str], str]] = [snake_case_export, camel_case_export]
def test_duplicate_remaps_ingredient_links_and_preserves_step_metadata(api_client: TestClient, unique_user: TestUser):
original = create_populated_recipe(api_client, unique_user)
response = api_client.post(
api_routes.recipes_slug_duplicate(original["slug"]), json={"name": random_string()}, headers=unique_user.token
)
assert response.status_code == 201, response.text
duplicate = response.json()
original_step = original["recipeInstructions"][0]
step = duplicate["recipeInstructions"][0]
assert duplicate["recipeIngredient"][0]["referenceId"] != original["recipeIngredient"][0]["referenceId"]
assert step["ingredientReferences"][0]["referenceId"] == duplicate["recipeIngredient"][0]["referenceId"]
assert step["ingredientReferences"][0]["quantity"] == 0.5
assert step["cooking"] == original_step["cooking"]
assert step["durationSeconds"] == 180
def test_update_and_clear_existing_step_metadata(api_client: TestClient, unique_user: TestUser):
recipe = create_populated_recipe(api_client, unique_user)
step = recipe["recipeInstructions"][0]
step["ingredientReferences"][0]["quantity"] = 1.25
step["cooking"]["speed"] = 1
response = api_client.put(api_routes.recipes_slug(recipe["slug"]), json=recipe, headers=unique_user.token)
assert response.status_code == 200, response.text
saved = api_client.get(api_routes.recipes_slug(recipe["slug"]), headers=unique_user.token).json()
assert saved["recipeInstructions"][0]["ingredientReferences"][0]["quantity"] == 1.25
assert saved["recipeInstructions"][0]["cooking"]["speed"] == 1
saved["recipeInstructions"][0]["ingredientReferences"][0]["quantity"] = None
saved["recipeInstructions"][0]["cooking"] = None
response = api_client.put(api_routes.recipes_slug(recipe["slug"]), json=saved, headers=unique_user.token)
assert response.status_code == 200, response.text
cleared = api_client.get(api_routes.recipes_slug(recipe["slug"]), headers=unique_user.token).json()
assert cleared["recipeInstructions"][0]["ingredientReferences"][0]["quantity"] is None
assert cleared["recipeInstructions"][0]["cooking"] is None
def test_shopping_list_uses_recipe_quantity_not_step_portion(
api_client: TestClient, unique_user: TestUser, shopping_lists
):
recipe = create_populated_recipe(api_client, unique_user)
shopping_list = shopping_lists[0]
response = api_client.post(
api_routes.households_shopping_lists_item_id_recipe_recipe_id(shopping_list.id, recipe["id"]),
headers=unique_user.token,
)
assert response.status_code == 200, response.text
result = api_client.get(api_routes.households_shopping_lists_item_id(shopping_list.id), headers=unique_user.token)
assert result.status_code == 200
assert result.json()["listItems"][0]["quantity"] == 2
def paste(
api_client: TestClient, user: TestUser, data: str, include_tags: bool = True, include_categories: bool = True
) -> Response:
@@ -135,6 +192,9 @@ def test_paste_mealie_export_keeps_contents(
step = imported["recipeInstructions"][0]
assert (step["title"], step["summary"], step["text"]) == ("Prep Work", "Season the meat", "Season the **beef**.")
assert [ref["referenceId"] for ref in step["ingredientReferences"]] == [ingredient["referenceId"]]
assert step["ingredientReferences"][0]["quantity"] == 0.5
assert step["durationSeconds"] == 180
assert step["cooking"] == original["recipeInstructions"][0]["cooking"]
# the recipe the export came from is untouched
still_there = api_client.get(api_routes.recipes_slug(original["slug"]), headers=unique_user.token)
@@ -7,7 +7,7 @@ from mealie.schema.openai.recipe import OpenAIInstructionEnrichment, OpenAIInstr
from mealie.schema.recipe.recipe import RecipeDraft
from mealie.schema.recipe.recipe_ingredient import RecipeIngredient
from mealie.schema.recipe.recipe_notes import RecipeNote
from mealie.schema.recipe.recipe_step import RecipeStep
from mealie.schema.recipe.recipe_step import IngredientReferences, RecipeStep, StepCooking
from mealie.services.recipe.import_workflow import (
RecipeImportWorkflow,
StepOutcome,
@@ -179,6 +179,26 @@ async def test_an_existing_heading_is_kept():
assert step.text == "Make the batter: whisk the flour and eggs."
@pytest.mark.asyncio
async def test_enrichment_does_not_replace_existing_cooking_metadata():
recipe = _recipe()
step = recipe.recipe_instructions[0]
step.ingredient_references = [
IngredientReferences(reference_id=recipe.recipe_ingredient[0].reference_id, quantity=0.5)
]
step.cooking = StepCooking(speed="spoon")
step.duration_seconds = 42
before = step.model_dump()
ctx = _ctx(
recipe,
_respond(
OpenAIInstructionEnrichment(step=1, ingredients=[2], duration="PT3M", summary="Changed", text="Changed")
),
)
await EnrichInstructionsStep().run(ctx)
assert step.model_dump() == before
@pytest.mark.asyncio
async def test_no_response_leaves_the_recipe_alone():
recipe = _recipe()
@@ -0,0 +1,33 @@
import pytest
from pydantic import ValidationError
from mealie.schema.recipe.recipe_step import IngredientReferences, RecipeStep, StepCooking
def test_legacy_step_and_explicit_zero():
step = RecipeStep(text="Mix", ingredient_references=[IngredientReferences(quantity=0)])
assert step.cooking is None
assert step.ingredient_references[0].quantity == 0
assert IngredientReferences().quantity is None
@pytest.mark.parametrize("speed", [1, 0.5, "spoon"])
def test_cooking_speeds(speed):
assert StepCooking(speed=speed).speed == speed
@pytest.mark.parametrize("quantity", [-1, float("inf"), float("nan")])
def test_invalid_quantity(quantity):
with pytest.raises(ValidationError):
IngredientReferences(quantity=quantity)
def test_nonfinite_speed_rejected():
with pytest.raises(ValidationError):
StepCooking(speed=float("inf"))
def test_unknown_cooking_settings_are_not_silently_discarded():
with pytest.raises(ValidationError):
StepCooking.model_validate({"speed": 2, "reverse": True})
assert "reverse" not in StepCooking.model_json_schema(by_alias=True)["properties"]
@@ -0,0 +1,50 @@
from importlib.util import module_from_spec, spec_from_file_location
from io import StringIO
from pathlib import Path
import pytest
from alembic.migration import MigrationContext
from alembic.operations import Operations
from sqlalchemy import create_engine, inspect, text
VERSIONS = Path(__file__).parents[2] / "mealie/alembic/versions"
MIGRATIONS = [
("2026-11-30-00.00.00_b742c6d50a10_add_step_ingredient_quantity.py", "recipe_ingredient_ref_link", "quantity"),
("2026-11-30-00.00.01_c981d7e62b11_add_step_cooking.py", "recipe_instructions", "cooking"),
]
def load_migration(filename):
spec = spec_from_file_location("step_metadata_migration", VERSIONS / filename)
module = module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.mark.parametrize(("filename", "table", "column"), MIGRATIONS)
@pytest.mark.parametrize("dialect", ["sqlite", "postgresql"])
def test_additive_migration_sql(filename, table, column, dialect):
output = StringIO()
context = MigrationContext.configure(dialect_name=dialect, opts={"as_sql": True, "output_buffer": output})
with Operations.context(context):
load_migration(filename).upgrade()
sql = output.getvalue().upper()
assert f"ALTER TABLE {table.upper()} ADD COLUMN {column.upper()}" in sql
assert "NOT NULL" not in sql
assert "DEFAULT" not in sql
@pytest.mark.parametrize(("filename", "table", "column"), MIGRATIONS)
def test_sqlite_upgrade_and_downgrade_preserve_rows(filename, table, column):
engine = create_engine("sqlite://")
with engine.begin() as connection:
connection.execute(text(f"CREATE TABLE {table} (id INTEGER PRIMARY KEY, text VARCHAR)"))
connection.execute(text(f"INSERT INTO {table} (id, text) VALUES (1, 'existing')"))
migration = load_migration(filename)
with Operations.context(MigrationContext.configure(connection)):
migration.upgrade()
assert next(col for col in inspect(connection).get_columns(table) if col["name"] == column)["nullable"]
assert connection.execute(text(f"SELECT id, text, {column} FROM {table}")).one() == (1, "existing", None)
migration.downgrade()
assert connection.execute(text(f"SELECT id, text FROM {table}")).one() == (1, "existing")
engine.dispose()