feat(recipe): add step quantities and appliance settings
Release Drafter / auto_label (push) Skipped
Release Drafter / draft_release (push) Canceled after 0s
CodeQL / Analyze (javascript-typescript) (push) Canceled after 0s
CodeQL / Analyze (python) (push) Canceled after 0s
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

This commit is contained in:
jfmcarreira committed 2026-12-01 13:05:50 +00:00
1 parent 1dd63a070b
commit 8dad430650
51 files changed
+2775 -77

No files matched your search

+70
View File
@@ -0,0 +1,70 @@
# Fork-specific cooking operations
Optional native data; no appliance, scales or cooking mode is executed by
Mealie. Device interpretation and supported wire values belong to integrations.
Existing recipes need no appliance information.
## Ingredient references
`quantityKind` distinguishes `full`, `partial`, `remaining`, `unknown`,
`prepared`, `asNeeded` and `referenceOnly`. Missing kinds preserve the legacy
null/full and numeric/explicit behavior. A partial portion requires a number,
including an explicit zero.
Non-numeric kinds store a zero **compatibility sentinel** in `quantity` so older
clients cannot inherit the recipe total. Current clients use the kind instead:
unknown/prepared/qualitative/reference-only associations have no numeric amount.
A remainder is calculated only when unambiguous and never persisted as a fixed
portion.
`weighing` is unspecified (including null/missing), `manual` or `weigh`; grams
alone never authorize scales. Unknown or non-allocation references cannot request
weighing. `role`, `destination`, `quantityMinimum`, `quantityMaximum`,
`approximate`, `containerCount` and `sourceText` preserve allocation context.
Quantities use the ingredient's unit and are per-container when a count exists.
The editor checks the whole allocation ledger, including inherited quantities,
container counts and repetitions, and warns about ambiguous remainders.
Shopping lists still use recipe totals. Display scaling does not rewrite native
quantities or machine settings. Stable allocation IDs keep completion independent.
## Operation settings
`durationSeconds` accepts finite positive seconds with millisecond precision;
legacy zero remains unspecified. Exact seconds and the existing minute shortcut
are both editable.
The existing optional `cooking` object adds:
- `actionType`, `timerType`, `applianceInstance`: generic action/appliance context.
- `accessories`: named items with installed/removed/unknown/conditional/open/closed
states, including lid context; no installation is inferred from prose.
- `durationKind`, `durationRangeSeconds`, `durationCondition`: fixed, ranged,
user-selected or condition-controlled time.
- `speedKind`, `speedRange`, `speedProgression`: retain ranges and ordered ramps
independently of an existing fixed/selected `speed`.
- `modeParameters`: named text, number, boolean or range parameters, with units.
Source labels such as thickness or doneness remain unchanged.
- `optional`, `condition`, `requiresConfirmation`, `repetitions`,
`repetitionRange`, `dependsOnStepIds`: declarative execution context, not a
workflow engine. Dependencies must belong to this recipe and be acyclic.
- `reviews`: categorized evidence, candidate ingredient IDs, resolution, approved
native content and history. Linking a candidate starts with an unknown amount.
Resolution requires an explanation; subsequent edits reopen approved reviews.
Omitting reviews cannot erase their provenance. Bridge extras are untouched.
Native JSON, duplication, editing and printing preserve these fields.
Duplication/import remap identities and dependencies together. Unsafe merges
are refused; undo restores safe merges.
## Deployment
Back up the database and deploy backend/frontend together. Migrations
`e274a9d13c50` (fractional duration) and `d3f629aa71b4` (allocation context) retain
legacy values. Duration downgrade refuses fractional data; allocation downgrade
removes the new columns and requires an export/backup.
Use the existing lockfile and pinned pnpm version. Schema/types are generated
with the project's tooling. Validation-only tools need not become application
dependencies. Repository-wide pre-existing TypeScript debt is outside this
feature change.
@@ -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,28 @@ interface Props {
scale?: number;
isCookMode?: boolean;
storageKey?: string;
portionKey?: string;
portionReferenceIds?: string[];
portionAllocationIds?: (string | null)[];
zeroPortionReferenceIds?: string[];
}
const props = withDefaults(defineProps<Props>(), {
value: () => [],
scale: 1,
isCookMode: false,
storageKey: undefined,
portionKey: undefined,
portionReferenceIds: () => [],
portionAllocationIds: () => [],
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);
}
@@ -111,8 +124,13 @@ function checkedState() {
}
function checkedKey(index: number) {
const allocationId = props.portionAllocationIds[index];
if (props.portionKey && allocationId) return `allocation:${allocationId}`;
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"
/>
@@ -18,7 +18,7 @@ function editor(value: number | null = null) {
describe("instruction duration in minutes with seconds storage", () => {
it("always shows a blank optional input without emitting a duration", () => {
const wrapper = editor();
expect(wrapper.findAll("input")).toHaveLength(1);
expect(wrapper.findAll("input")).toHaveLength(2);
expect(wrapper.find("input").element.value).toBe("");
expect(wrapper.find("input").attributes("placeholder")).toBe("Minutes");
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
@@ -60,7 +60,13 @@ describe("instruction duration in minutes with seconds storage", () => {
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([120]);
wrapper.unmount();
});
it.each([[3661, "1h 1m 1s"], [90, "1m 30s"], [60, "1m"], [30, "30s"], [null, ""]] as const)("displays %s with units", async (value, text) => {
it("allows an exact fractional-second duration", async () => {
const wrapper = editor();
await wrapper.findAll("input")[1]!.setValue("0.5");
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([0.5]);
wrapper.unmount();
});
it.each([[3661, "1h 1m 1s"], [90, "1m 30s"], [61.001, "1m 1.001s"], [0.5, "0.5s"], [60, "1m"], [30, "30s"], [null, ""]] as const)("displays %s with units", async (value, text) => {
const wrapper = editor(value);
await wrapper.setProps({ isEditMode: false });
expect(wrapper.text()).toBe(text);
@@ -14,7 +14,24 @@
inset
hide-details="auto"
@update:model-value="updateDuration"
@keypress="e => e.key === '-' && e.preventDefault()"
@keypress="(e: KeyboardEvent) => e.key === '-' && e.preventDefault()"
@click.stop
/>
<v-number-input
v-if="isEditMode"
:model-value="modelValue ?? null"
class="step-duration"
:min="0"
:max="2147483647"
:step="0.001"
:precision="3"
:label="$t('recipe.step-duration-seconds')"
density="compact"
inset
clearable
hide-details="auto"
@update:model-value="emit('update:modelValue', $event || null)"
@keypress="(e: KeyboardEvent) => e.key === '-' && e.preventDefault()"
@click.stop
/>
<span v-else-if="modelValue" class="text-body-2">
@@ -60,7 +77,7 @@ const formattedDuration = computed(() => {
const seconds = props.modelValue ?? 0;
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const remainder = seconds % 60;
const remainder = (Math.round(seconds * 1000) % 60000) / 1000;
return [
hours ? t("recipe.step-duration-value-hours", { hours }) : "",
minutes ? t("recipe.step-duration-value-minutes", { minutes }) : "",
@@ -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");
});
});
@@ -415,7 +415,7 @@
>
<div
v-for="(linkRef, i) in step.ingredientReferences"
:key="linkRef.referenceId ?? i"
:key="linkRef.allocationId ?? linkRef.referenceId ?? i"
class="mb-1"
>
<RecipeIngredientHtml
@@ -423,6 +423,13 @@
:ingredient="ingredientLookup[linkRef.referenceId]"
:scale="scale"
/>
<RecipeStepAllocationEditor :model-value="linkRef" @update:model-value="Object.assign(linkRef, $event)" />
<div v-if="linkRef.referenceId && overallocatedIds.has(linkRef.referenceId)" class="text-warning text-body-2">
{{ $t('recipe.step-quantity-exceeds') }}
</div>
<div v-if="linkRef.quantityKind === 'remaining' && linkRef.referenceId && unresolvedRemainingIds.has(linkRef.referenceId)" class="text-warning text-body-2">
{{ $t('recipe.step-remaining-unknown') }}
</div>
</div>
</div>
<div
@@ -445,6 +452,7 @@
:is-edit-mode="isEditForm"
@update:model-value="step.durationSeconds = $event"
/>
<RecipeStepCooking v-model="step.cooking" :ingredients="recipe.recipeIngredient" edit @link-ingredient="linkReviewIngredient(step, $event)" />
</v-card-text>
</DropZone>
@@ -465,13 +473,14 @@
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"
:portion-allocation-ids="stepAllocationIds(step)"
:zero-portion-reference-ids="zeroPortionIds(step)"
/>
</div>
<v-divider
@@ -503,6 +512,17 @@
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" />
<RecipeStepAllocationSummary :references="step.ingredientReferences" :ingredients="recipe.recipeIngredient" :scale="scale" />
</v-col>
</v-row>
</v-card-text>
@@ -532,6 +552,12 @@ 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 RecipeStepAllocationEditor from "~/components/Domain/Recipe/RecipeStepAllocationEditor.vue";
import RecipeStepAllocationSummary from "~/components/Domain/Recipe/RecipeStepAllocationSummary.vue";
import { overallocatedIngredientIds, stepIngredients, unresolvedRemainingIngredientIds } 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";
@@ -556,8 +582,33 @@ const props = defineProps({
const emit = defineEmits(["click-instruction-field", "update:assets"]);
const i18n = useI18n();
function linkReviewIngredient(step: RecipeStep, referenceId: string) {
step.ingredientReferences ??= [];
if (!step.ingredientReferences.some(ref => ref.referenceId === referenceId)) {
step.ingredientReferences.push({ allocationId: uuid4(), referenceId, quantityKind: "unknown", quantity: 0 });
}
}
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, instructionList.value);
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.quantityKind || ref.quantityKind === "partial") && ref.referenceId)
.map(ref => ref.referenceId!);
}
function stepAllocationIds(step: RecipeStep): (string | null)[] {
return (step.ingredientReferences ?? [])
.filter(ref => ref.referenceId && props.recipe.recipeIngredient.some(ingredient => ingredient.referenceId === ref.referenceId))
.map(ref => ref.quantityKind || ref.quantity != null ? ref.allocationId ?? null : null);
}
const dialog = ref(false);
const disabledSteps = ref<number[]>([]);
@@ -678,6 +729,11 @@ 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 unresolvedRemainingIds = computed(() => unresolvedRemainingIngredientIds(instructionList.value, props.recipe.recipeIngredient));
const portionReferenceIds = computed(() => [...new Set(instructionList.value.flatMap(step =>
(step.ingredientReferences ?? []).filter(ref => (ref.quantityKind || 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 +778,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 +947,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,76 @@
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.each([true, false])("renders settings with their step and only labels reverse rotation: %s", (reverse) => {
const recipe = makeRecipe({
recipeIngredient: [{ referenceId: "ingredient", quantity: 100, food: { name: "flour" } }],
recipeInstructions: [
{ text: "Mix", durationSeconds: 180, cooking: { temperatureCelsius: 120, speed: "spoon", reverse } },
{ 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?.includes("Reverse rotation")).toBe(reverse);
expect(wrapper.text()).not.toContain("Forward rotation");
expect(steps[0].element.parentElement?.textContent).toContain("3m");
expect(steps[1].element.parentElement?.textContent).not.toContain("120 °C");
expect(steps[1].element.parentElement?.textContent).not.toContain("Reverse rotation");
});
test("prints fractional pulses, ranges, accessories and allocation intent without scaling operation settings", () => {
const recipe = makeRecipe({
recipeIngredient: [{ referenceId: "flour", quantity: 100, food: { name: "flour" } }],
recipeInstructions: [{
text: "Check consistency", durationSeconds: 0.5,
ingredientReferences: [{ referenceId: "flour", quantityKind: "unknown", quantity: 0, weighing: "manual", destination: "bowl" }],
cooking: {
durationRangeSeconds: { minimum: 0.5, maximum: 2 },
speedProgression: [1, 3, 5], accessories: [{ name: "lid", state: "open" }],
optional: true, condition: "If too coarse", repetitions: 3,
modeParameters: [{ name: "thickness", kind: "text", value: "coarse" }],
},
}],
});
const wrapper = mount(RecipePrintView, {
props: { recipe, scale: 2 },
global: {
mocks: { $globals: { icons: { primary: "", potSteam: "" } } },
stubs: { SafeMarkdown: true, SafeInlineHtml: true, RecipeTimeCard: true },
},
});
expect(wrapper.text()).toContain("0.5s");
expect(wrapper.text()).toContain("0.5–2 s");
expect(wrapper.text()).toContain("1 → 3 → 5");
expect(wrapper.text()).toContain("lid: Open");
expect(wrapper.text()).toContain("Unknown amount");
expect(wrapper.text()).toContain("If too coarse");
expect(recipe.recipeIngredient[0]!.quantity).toBe(100);
expect(recipe.recipeInstructions[0]!.ingredientReferences![0]!.quantity).toBe(0);
});
});
@@ -136,6 +136,9 @@
:source="step.text"
class="recipe-step-body"
/>
<CookTime :model-value="step.durationSeconds" :is-edit-mode="false" />
<RecipeStepCooking :model-value="step.cooking" />
<RecipeStepAllocationSummary :references="step.ingredientReferences" :ingredients="sourceIngredients ?? recipe.recipeIngredient" :scale="scale" />
<!-- Step Ingredients -->
<div
v-if="preferences.showLinkedIngredients && step.ingredientReferences && step.ingredientReferences.length > 0"
@@ -155,7 +158,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 && (!ref.quantityKind || ref.quantityKind === 'partial')))" />
</p>
</template>
</div>
@@ -224,6 +227,12 @@ 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 RecipeStepAllocationSummary from "~/components/Domain/Recipe/RecipeStepAllocationSummary.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 +249,7 @@ interface Props {
recipe: RecipeOut;
scale?: number;
dense?: boolean;
sourceIngredients?: RecipeIngredient[];
}
const props = withDefaults(defineProps<Props>(), {
scale: 1,
@@ -251,6 +261,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 +407,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, props.recipe.recipeInstructions);
map.set(`${sectionIndex}-${stepIndex}`, props.sourceIngredients && unitSystem.value
? ingredients.map(ingredient => convertIngredient(ingredient, unitSystem.value!, props.scale))
: ingredients);
});
});
@@ -408,8 +419,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,49 @@
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 RecipeStepAllocationEditor from "./RecipeStepAllocationEditor.vue";
describe("allocation intent editor", () => {
test("does not change legacy quantities on mount and never infers scale activation", () => {
const wrapper = mount(RecipeStepAllocationEditor, {
props: { modelValue: { referenceId: "flour", quantity: null } },
global: { plugins: [createVuetify({ components, directives })] },
});
expect(wrapper.findComponent(components.VSelect).props("modelValue")).toBe("full");
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
});
test("selects unknown safely and retains the association identity", async () => {
const wrapper = mount(RecipeStepAllocationEditor, {
props: { modelValue: { allocationId: "allocation", referenceId: "flour", quantity: 20, weighing: "weigh" } },
global: { plugins: [createVuetify({ components, directives })] },
});
await wrapper.findComponent(components.VSelect).vm.$emit("update:modelValue", "unknown");
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([{
allocationId: "allocation", referenceId: "flour", quantity: 0, quantityKind: "unknown", weighing: "unspecified",
}]);
});
test("edits partial portions and weighing independently", async () => {
const wrapper = mount(RecipeStepAllocationEditor, {
props: { modelValue: { allocationId: "allocation", referenceId: "flour", quantityKind: "partial", quantity: 0 } },
global: { plugins: [createVuetify({ components, directives })] },
});
await wrapper.findComponent(components.VNumberInput).vm.$emit("update:modelValue", 0.5);
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({ quantity: 0.5, quantityKind: "partial" });
const weighing = wrapper.findAllComponents(components.VSelect)[1]!;
await weighing.vm.$emit("update:modelValue", "manual");
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({ quantity: 0, weighing: "manual" });
});
test("requires a portion to be entered when an unknown amount is changed to partial", async () => {
const wrapper = mount(RecipeStepAllocationEditor, {
props: { modelValue: { referenceId: "flour", quantityKind: "unknown", quantity: 0 } },
global: { plugins: [createVuetify({ components, directives })] },
});
await wrapper.findComponent(components.VSelect).vm.$emit("update:modelValue", "partial");
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({ quantityKind: "partial", quantity: null });
});
});
@@ -0,0 +1,72 @@
<template>
<div @click.stop>
<v-select :model-value="kind" :items="allocationOptions" :label="$t('recipe.allocation-kind')" density="compact" @update:model-value="setKind" />
<v-number-input
v-if="kind === 'partial'"
:model-value="modelValue.quantity"
:label="$t('recipe.step-quantity')"
:min="0"
:precision="null"
density="compact"
clearable
@update:model-value="update('quantity', $event)"
/>
<v-select :model-value="modelValue.weighing ?? 'unspecified'" :items="weighingOptions" :label="$t('recipe.weighing-intent')" density="compact" @update:model-value="update('weighing', $event)" />
<v-text-field :model-value="modelValue.role" :label="$t('recipe.allocation-role')" clearable density="compact" @update:model-value="update('role', $event || null)" />
<v-text-field :model-value="modelValue.destination" :label="$t('recipe.allocation-destination')" clearable density="compact" @update:model-value="update('destination', $event || null)" />
<v-number-input
:model-value="modelValue.quantityMinimum"
:label="$t('recipe.allocation-minimum')"
:min="0"
:precision="null"
clearable
density="compact"
@update:model-value="update('quantityMinimum', $event)"
/>
<v-number-input
:model-value="modelValue.quantityMaximum"
:label="$t('recipe.allocation-maximum')"
:min="0"
:precision="null"
clearable
density="compact"
@update:model-value="update('quantityMaximum', $event)"
/>
<v-number-input
:model-value="modelValue.containerCount"
:label="$t('recipe.allocation-containers')"
:min="1"
:precision="0"
clearable
density="compact"
@update:model-value="update('containerCount', $event)"
/>
<v-checkbox :model-value="modelValue.approximate ?? false" :label="$t('recipe.allocation-approximate')" density="compact" @update:model-value="update('approximate', $event)" />
<v-text-field :model-value="modelValue.sourceText" :label="$t('recipe.allocation-source')" clearable density="compact" @update:model-value="update('sourceText', $event || null)" />
</div>
</template>
<script setup lang="ts">
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import type { IngredientReferences } from "~/lib/api/types/recipe";
const props = defineProps<{ modelValue: IngredientReferences }>();
const emit = defineEmits<{ "update:modelValue": [value: IngredientReferences] }>();
const { t } = useI18n();
const kind = computed(() => props.modelValue.quantityKind ?? (props.modelValue.quantity == null ? "full" : "partial"));
const kinds = ["full", "partial", "remaining", "unknown", "prepared", "asNeeded", "referenceOnly"] as const;
const allocationOptions = computed(() => kinds.map(value => ({ title: t(`recipe.allocation-${value}`), value })));
const weighingOptions = computed(() => ["unspecified", "manual", ...(kind.value === "full" || kind.value === "partial" ? ["weigh"] : [])].map(value => ({ title: t(`recipe.weighing-${value}`), value })));
function update<K extends keyof IngredientReferences>(key: K, value: IngredientReferences[K]) {
emit("update:modelValue", { ...props.modelValue, [key]: value });
}
function setKind(value: NonNullable<IngredientReferences["quantityKind"]>) {
emit("update:modelValue", {
...props.modelValue,
quantityKind: value,
quantity: value === "full" ? null : value === "partial" ? (kind.value === "partial" ? props.modelValue.quantity : null) : 0,
weighing: value === "full" || value === "partial" ? props.modelValue.weighing : "unspecified",
});
}
</script>
@@ -0,0 +1,40 @@
<template>
<div v-for="(reference, index) in references ?? []" :key="reference.allocationId ?? index" class="text-body-2">
<template v-if="reference.quantityKind || reference.weighing || reference.destination || reference.role || reference.sourceText || reference.approximate || reference.containerCount != null || reference.quantityMinimum != null || reference.quantityMaximum != null">
{{ ingredientName(reference.referenceId) }}:
{{ $t(`recipe.allocation-${allocationKind(reference)}`) }}
<template v-if="reference.weighing && reference.weighing !== 'unspecified'">
· {{ $t(`recipe.weighing-${reference.weighing}`) }}
</template>
<template v-if="reference.role">
· {{ reference.role }}
</template>
<template v-if="reference.destination">
· {{ reference.destination }}
</template>
<template v-if="reference.approximate">
· {{ $t("recipe.allocation-approximate") }}
</template>
<template v-if="reference.quantityMinimum != null || reference.quantityMaximum != null">
· {{ reference.quantityMinimum == null ? "?" : reference.quantityMinimum * scale }}–{{ reference.quantityMaximum == null ? "?" : reference.quantityMaximum * scale }}
</template>
<template v-if="reference.containerCount != null">
· ×{{ reference.containerCount }}
</template>
<template v-if="reference.sourceText">
· {{ reference.sourceText }}
</template>
</template>
</div>
</template>
<script setup lang="ts">
import type { IngredientReferences, RecipeIngredient } from "~/lib/api/types/recipe";
import { allocationKind } from "~/lib/recipe/step-ingredients";
const props = withDefaults(defineProps<{ references?: IngredientReferences[]; ingredients: RecipeIngredient[]; scale?: number }>(), { scale: 1 });
function ingredientName(referenceId?: string | null) {
const ingredient = props.ingredients.find(item => item.referenceId === referenceId);
return ingredient?.food?.name || ingredient?.note || "";
}
</script>
@@ -0,0 +1,59 @@
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 }]);
});
test.each([true, false, null, undefined])("only displays reverse rotation: %s", (reverse) => {
const wrapper = mount(RecipeStepCooking, { props: { modelValue: { speed: 2, reverse } } });
expect(wrapper.text().includes("Reverse rotation")).toBe(reverse === true);
expect(wrapper.text()).not.toContain("Forward rotation");
expect(wrapper.text()).toContain("Speed: 2");
});
test("does not render a settings row for forward rotation alone", () => {
const wrapper = mount(RecipeStepCooking, { props: { modelValue: { reverse: false } } });
expect(wrapper.find(".text-body-2").exists()).toBe(false);
});
test("edits and clears direction while preserving other cooking settings", async () => {
const wrapper = mount(RecipeStepCooking, {
props: { modelValue: { speed: 2, reverse: true }, edit: true },
global: { plugins: [createVuetify({ components, directives })] },
});
const field = wrapper.findComponent(components.VSelect);
await field.vm.$emit("update:modelValue", false);
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([{ speed: 2, reverse: false }]);
await field.vm.$emit("update:modelValue", null);
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([{ speed: 2, reverse: null }]);
});
});
@@ -0,0 +1,114 @@
<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-select
:model-value="modelValue?.reverse"
:items="directionOptions"
:label="$t('recipe.step-direction')"
clearable
density="compact"
@update:model-value="update('reverse', $event)"
/>
<v-text-field :model-value="modelValue?.mode" :label="$t('recipe.step-mode')" clearable density="compact" @update:model-value="update('mode', $event || null)" />
<RecipeStepOperationDetails :model-value="modelValue" :ingredients="ingredients" @update:model-value="emit('update:modelValue', $event)" @link-ingredient="emit('linkIngredient', $event)" />
<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>
<div v-if="!edit && modelValue?.reviews?.length" class="text-body-2 mt-2">
<div v-for="(review, index) in modelValue.reviews" :key="index">
{{ $t(`recipe.review-category-${review.category}`) }} — {{ $t(`recipe.review-status-${review.status ?? 'unresolved'}`) }}:
{{ review.source }} {{ review.reason }} {{ review.resolution }}
</div>
</div>
</template>
<script setup lang="ts">
import type { RecipeIngredient, StepCooking } from "~/lib/api/types/recipe";
import RecipeStepOperationDetails from "./RecipeStepOperationDetails.vue";
const props = defineProps<{ modelValue?: StepCooking | null; edit?: boolean; ingredients?: RecipeIngredient[] }>();
const emit = defineEmits<{ "update:modelValue": [value: StepCooking | null]; "linkIngredient": [referenceId: string] }>();
const { t } = useI18n();
const directionOptions = computed(() => [
{ title: t("recipe.step-forward"), value: false },
{ title: t("recipe.step-reverse"), value: true },
]);
// 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.reverse === true ? t("recipe.step-reverse") : null,
cooking.mode,
cooking.actionType ? t(`recipe.action-${cooking.actionType}`) : null,
cooking.applianceInstance,
cooking.timerType ? t(`recipe.timer-${cooking.timerType}`) : null,
cooking.durationKind ? t(`recipe.setting-${cooking.durationKind}`) : null,
...(cooking.accessories ?? []).map(accessory => `${accessory.name}: ${t(`recipe.accessory-${accessory.state}`)}`),
cooking.durationRangeSeconds ? `${t("recipe.operation-duration-range")}: ${cooking.durationRangeSeconds.minimum ?? "?"}–${cooking.durationRangeSeconds.maximum ?? "?"} s` : null,
cooking.durationCondition,
cooking.speedRange ? `${t("recipe.operation-speed-range")}: ${cooking.speedRange.minimum ?? "?"}–${cooking.speedRange.maximum ?? "?"}` : null,
cooking.speedProgression?.length ? `${t("recipe.operation-speed-progression")}: ${cooking.speedProgression.join(" → ")}` : null,
...(cooking.modeParameters ?? []).map(parameter => `${parameter.name}: ${parameter.value ?? [parameter.minimum, parameter.maximum].filter(v => v != null).join("–")} ${parameter.unit ?? ""}`),
cooking.optional ? t("recipe.operation-is-optional") : null,
cooking.condition,
cooking.requiresConfirmation ? t("recipe.operation-confirmation") : null,
cooking.repetitions != null ? `${t("recipe.operation-repetitions")}: ${cooking.repetitions}` : null,
cooking.repetitionRange ? `${t("recipe.operation-repetition-range")}: ${cooking.repetitionRange.minimum ?? "?"}–${cooking.repetitionRange.maximum ?? "?"}` : null,
].filter(Boolean);
});
</script>
@@ -0,0 +1,91 @@
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 RecipeStepOperationDetails from "./RecipeStepOperationDetails.vue";
import type { StepCooking } from "~/lib/api/types/recipe";
function editor(modelValue: StepCooking = {}) {
return mount(RecipeStepOperationDetails, {
props: { modelValue },
global: { plugins: [createVuetify({ components, directives })] },
});
}
describe("generic operation editor", () => {
test("edits fractional duration bounds without inventing a fixed setting", async () => {
const wrapper = editor({ speed: 2, durationKind: "range" });
const inputs = wrapper.findAllComponents(components.VNumberInput);
await inputs.find(input => input.props("label") === "Minimum duration (seconds)")!.vm.$emit("update:modelValue", 0.5);
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([{
speed: 2, durationKind: "range", durationRangeSeconds: { minimum: 0.5 },
}]);
});
test("preserves progressive speeds and rejects an invalid progression visibly", async () => {
const wrapper = editor({ speed: 1, speedKind: "progression", speedProgression: [1, 3, 5] });
const input = wrapper.findAllComponents(components.VTextField).find(field => field.props("label") === "Speed progression (comma-separated)")!.find("input");
await input.setValue("1, 2.5, 6");
await input.trigger("change");
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({ speed: 1, speedProgression: [1, 2.5, 6] });
const count = wrapper.emitted("update:modelValue")!.length;
await input.setValue("1, invalid");
await input.trigger("change");
expect(wrapper.emitted("update:modelValue")).toHaveLength(count);
expect(wrapper.text()).toContain("Enter a comma-separated list of numbers.");
});
test("edits accessory state and typed mode parameters without changing other settings", async () => {
const settings: StepCooking = {
appliance: "mixer",
accessories: [{ name: "basket", state: "unknown" }],
modeParameters: [{ name: "pulses", kind: "number", value: 3 }],
};
const wrapper = editor(settings);
const accessory = wrapper.findAllComponents(components.VSelect).find(field => field.props("label") === "State")!;
await accessory.vm.$emit("update:modelValue", "removed");
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({
accessories: [{ name: "basket", state: "removed" }], modeParameters: settings.modeParameters,
});
const parameter = wrapper.findAllComponents(components.VNumberInput).find(field => field.props("label") === "Value")!;
await parameter.vm.$emit("update:modelValue", 4);
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({
modeParameters: [{ name: "pulses", kind: "number", value: 4 }], appliance: "mixer",
});
});
test("edits conditions and repeats independently", async () => {
const wrapper = editor({ optional: true, condition: "If too coarse", requiresConfirmation: true });
const repeats = wrapper.findAllComponents(components.VNumberInput).find(field => field.props("label") === "Repetitions")!;
await repeats.vm.$emit("update:modelValue", 3);
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({
optional: true, condition: "If too coarse", requiresConfirmation: true, repetitions: 3,
});
});
test("explicit parameter type changes clear incompatible values with a visible hint", async () => {
const wrapper = editor({ modeParameters: [{ name: "pulses", kind: "number", value: 3 }] });
const field = wrapper.findAllComponents(components.VSelect).find(input => input.props("label") === "Parameter type")!;
expect(wrapper.text()).toContain("Changing type clears the previous value and bounds.");
await field.vm.$emit("update:modelValue", "range");
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({
modeParameters: [{ name: "pulses", kind: "range", value: null, minimum: null, maximum: null }],
});
});
test("exposes review candidates, provenance and an explicit resolution", async () => {
const wrapper = editor({
reviews: [{ id: "review", category: "ingredient", source: "some flour", reason: "Unknown portion", candidateIngredientIds: ["flour"], status: "unresolved" }],
});
await wrapper.setProps({ ingredients: [{ referenceId: "flour", quantity: 100, note: "flour" }] });
const link = wrapper.findAllComponents(components.VSelect).find(field => field.props("label") === "Link a candidate ingredient (unknown amount)")!;
await link.vm.$emit("update:modelValue", "flour");
expect(wrapper.emitted("linkIngredient")).toEqual([["flour"]]);
const resolution = wrapper.findAllComponents(components.VTextField).find(field => field.props("label") === "Resolution")!;
await resolution.vm.$emit("update:modelValue", "Confirmed manual addition");
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({
reviews: [{ source: "some flour", reason: "Unknown portion", resolution: "Confirmed manual addition", status: "unresolved" }],
});
});
});
@@ -0,0 +1,288 @@
<template>
<div class="mt-2">
<v-select
:model-value="modelValue?.actionType"
:items="actionTypes"
:label="$t('recipe.operation-type')"
clearable
density="compact"
@update:model-value="update('actionType', $event)"
/>
<v-select
:model-value="modelValue?.timerType"
:items="timerTypes"
:label="$t('recipe.operation-timer-type')"
clearable
density="compact"
@update:model-value="update('timerType', $event)"
/>
<v-select
:model-value="modelValue?.durationKind"
:items="durationKinds"
:label="$t('recipe.operation-duration-kind')"
clearable
density="compact"
@update:model-value="update('durationKind', $event)"
/>
<v-select
:model-value="modelValue?.speedKind"
:items="speedKinds"
:label="$t('recipe.operation-speed-kind')"
clearable
density="compact"
@update:model-value="update('speedKind', $event)"
/>
<v-text-field :model-value="modelValue?.applianceInstance" :label="$t('recipe.operation-instance')" clearable density="compact" @update:model-value="update('applianceInstance', $event || null)" />
<div v-for="range in ranges" :key="range.key" class="d-flex ga-2">
<v-number-input
:model-value="modelValue?.[range.key]?.minimum"
:label="$t(range.minimum)"
:precision="range.key === 'repetitionRange' ? 0 : null"
density="compact"
clearable
@update:model-value="setRange(range.key, 'minimum', $event)"
/>
<v-number-input
:model-value="modelValue?.[range.key]?.maximum"
:label="$t(range.maximum)"
:precision="range.key === 'repetitionRange' ? 0 : null"
density="compact"
clearable
@update:model-value="setRange(range.key, 'maximum', $event)"
/>
</div>
<v-text-field :model-value="modelValue?.durationCondition" :label="$t('recipe.operation-duration-condition')" clearable density="compact" @update:model-value="update('durationCondition', $event || null)" />
<v-text-field
:model-value="(modelValue?.speedProgression ?? []).join(', ')"
:label="$t('recipe.operation-speed-progression')"
:error-messages="progressionError ? [$t('recipe.operation-invalid-progression')] : []"
clearable
density="compact"
@change="setProgression(($event.target as HTMLInputElement).value)"
@click:clear="setProgression('')"
/>
<v-select
:model-value="modelValue?.optional"
:items="optionalOptions"
:label="$t('recipe.operation-optional')"
clearable
density="compact"
@update:model-value="update('optional', $event)"
/>
<v-text-field :model-value="modelValue?.condition" :label="$t('recipe.operation-condition')" clearable density="compact" @update:model-value="update('condition', $event || null)" />
<v-checkbox :model-value="modelValue?.requiresConfirmation ?? false" :label="$t('recipe.operation-confirmation')" density="compact" @update:model-value="update('requiresConfirmation', $event)" />
<v-combobox
:model-value="modelValue?.dependsOnStepIds ?? []"
:label="$t('recipe.operation-dependencies')"
multiple
chips
density="compact"
@update:model-value="update('dependsOnStepIds', $event)"
/>
<v-number-input
:model-value="modelValue?.repetitions"
:label="$t('recipe.operation-repetitions')"
:min="1"
:precision="0"
clearable
density="compact"
@update:model-value="update('repetitions', $event)"
/>
<div class="text-subtitle-2">
{{ $t("recipe.operation-accessories") }}
</div>
<div v-for="(accessory, index) in modelValue?.accessories ?? []" :key="index" class="d-flex ga-2">
<v-text-field :model-value="accessory.name" :label="$t('recipe.operation-name')" density="compact" @update:model-value="setAccessory(index, 'name', $event)" />
<v-select :model-value="accessory.state" :items="accessoryStates" :label="$t('recipe.operation-state')" density="compact" @update:model-value="setAccessory(index, 'state', $event)" />
<v-btn variant="text" @click="removeAccessory(index)">
{{ $t("general.delete") }}
</v-btn>
</div>
<v-btn size="small" variant="text" @click="addAccessory">
{{ $t("recipe.operation-add-accessory") }}
</v-btn>
<div class="text-subtitle-2 mt-2">
{{ $t("recipe.operation-parameters") }}
</div>
<div v-for="(parameter, index) in modelValue?.modeParameters ?? []" :key="index">
<v-text-field :model-value="parameter.name" :label="$t('recipe.operation-name')" density="compact" @update:model-value="setParameter(index, 'name', $event)" />
<v-select
:model-value="parameter.kind ?? 'text'"
:items="parameterKinds"
:label="$t('recipe.operation-parameter-kind')"
:hint="$t('recipe.operation-parameter-kind-hint')"
persistent-hint
density="compact"
@update:model-value="setParameterKind(index, $event)"
/>
<v-number-input
v-if="parameter.kind === 'number'"
:model-value="typeof parameter.value === 'number' ? parameter.value : null"
:label="$t('recipe.operation-parameter-value')"
:precision="null"
clearable
density="compact"
@update:model-value="setParameter(index, 'value', $event)"
/>
<v-select
v-else-if="parameter.kind === 'boolean'"
:model-value="parameter.value"
:items="optionalOptions"
:label="$t('recipe.operation-parameter-value')"
clearable
density="compact"
@update:model-value="setParameter(index, 'value', $event)"
/>
<v-text-field v-else-if="parameter.kind !== 'range'" :model-value="parameter.value == null ? '' : String(parameter.value)" :label="$t('recipe.operation-parameter-value')" density="compact" @change="setParameter(index, 'value', ($event.target as HTMLInputElement).value)" />
<v-text-field :model-value="parameter.unit" :label="$t('recipe.operation-parameter-unit')" clearable density="compact" @update:model-value="setParameter(index, 'unit', $event || null)" />
<div v-if="parameter.kind === 'range'" class="d-flex ga-2">
<v-number-input
:model-value="parameter.minimum"
:label="$t('recipe.operation-parameter-minimum')"
:precision="null"
clearable
density="compact"
@update:model-value="setParameter(index, 'minimum', $event)"
/>
<v-number-input
:model-value="parameter.maximum"
:label="$t('recipe.operation-parameter-maximum')"
:precision="null"
clearable
density="compact"
@update:model-value="setParameter(index, 'maximum', $event)"
/>
</div>
<v-btn size="small" variant="text" @click="removeParameter(index)">
{{ $t("general.delete") }}
</v-btn>
</div>
<v-btn size="small" variant="text" @click="addParameter">
{{ $t("recipe.operation-add-parameter") }}
</v-btn>
<div class="text-subtitle-2 mt-2">
{{ $t("recipe.operation-reviews") }}
</div>
<div v-for="(review, index) in modelValue?.reviews ?? []" :key="index" class="mb-3">
<v-select :model-value="review.category" :items="reviewCategories" :label="$t('recipe.operation-review-category')" density="compact" @update:model-value="setReview(index, 'category', $event)" />
<v-text-field :model-value="review.source" :readonly="!!review.history?.length" :label="$t('recipe.operation-review-source')" density="compact" @update:model-value="setReview(index, 'source', $event)" />
<v-text-field :model-value="review.reason" :readonly="!!review.history?.length" :label="$t('recipe.operation-review-reason')" density="compact" @update:model-value="setReview(index, 'reason', $event)" />
<v-select
v-if="review.category === 'ingredient'"
:model-value="review.candidateIngredientIds ?? []"
:items="ingredientOptions"
:label="$t('recipe.operation-review-candidates')"
multiple
chips
:readonly="!!review.history?.length"
density="compact"
@update:model-value="setReview(index, 'candidateIngredientIds', $event)"
/>
<v-select
v-if="review.category === 'ingredient'"
:items="ingredientOptions.filter(item => review.candidateIngredientIds?.includes(item.value))"
:label="$t('recipe.operation-review-link')"
density="compact"
@update:model-value="emit('linkIngredient', $event)"
/>
<v-text-field :model-value="review.resolution" :label="$t('recipe.operation-review-resolution')" clearable density="compact" @update:model-value="setReview(index, 'resolution', $event || null)" />
<v-select :model-value="review.status ?? 'unresolved'" :items="reviewStatuses" :label="$t('recipe.operation-review-status')" density="compact" @update:model-value="setReview(index, 'status', $event)" />
<details v-if="review.history?.length">
<summary>{{ $t("recipe.operation-review-history") }}</summary>
<div v-for="(event, eventIndex) in review.history" :key="eventIndex">
{{ event.at }} — {{ $t(`recipe.review-status-${event.status}`) }} — {{ event.resolution }}
<pre class="review-history">{{ event.content }}</pre>
</div>
</details>
<v-btn v-if="!review.history?.length" size="small" variant="text" @click="removeReview(index)">
{{ $t("general.delete") }}
</v-btn>
</div>
<v-btn size="small" variant="text" @click="addReview">
{{ $t("recipe.operation-add-review") }}
</v-btn>
</div>
</template>
<script setup lang="ts">
import type { RecipeIngredient, StepAccessory, StepCooking, StepParameter, StepRange, StepReview } from "~/lib/api/types/recipe";
const props = defineProps<{ modelValue?: StepCooking | null; ingredients?: RecipeIngredient[] }>();
const emit = defineEmits<{ "update:modelValue": [value: StepCooking]; "linkIngredient": [referenceId: string] }>();
const { t } = useI18n();
const progressionError = ref(false);
const options = (prefix: string, values: string[]) => values.map(value => ({ title: t(`recipe.${prefix}-${value}`), value }));
const actionTypes = computed(() => options("action", ["manual", "machine", "oven", "waiting", "weighing"]));
const timerTypes = computed(() => options("timer", ["machine", "manual", "oven", "resting"]));
const durationKinds = computed(() => options("setting", ["fixed", "range", "userSelected", "condition"]));
const speedKinds = computed(() => options("setting", ["fixed", "range", "progression"]));
const parameterKinds = computed(() => options("parameter-kind", ["text", "number", "boolean", "range"]));
const accessoryStates = computed(() => options("accessory", ["installed", "removed", "unknown", "conditional", "open", "closed"]));
const optionalOptions = computed(() => [{ title: t("general.yes"), value: true }, { title: t("general.no"), value: false }]);
const reviewCategories = computed(() => options("review-category", ["ingredient", "operation", "schema", "unsupported"]));
const reviewStatuses = computed(() => options("review-status", ["unresolved", "resolved"]));
const ingredientOptions = computed(() => (props.ingredients ?? []).filter(i => i.referenceId).map(i => ({ title: i.display || i.note || i.referenceId!, value: i.referenceId! })));
const ranges = [
{ key: "durationRangeSeconds", minimum: "recipe.operation-duration-minimum", maximum: "recipe.operation-duration-maximum" },
{ key: "speedRange", minimum: "recipe.operation-speed-minimum", maximum: "recipe.operation-speed-maximum" },
{ key: "repetitionRange", minimum: "recipe.operation-repeat-minimum", maximum: "recipe.operation-repeat-maximum" },
] as const;
function update<K extends keyof StepCooking>(key: K, value: StepCooking[K]) {
emit("update:modelValue", { ...props.modelValue, [key]: value });
}
function setRange(key: "durationRangeSeconds" | "speedRange" | "repetitionRange", bound: keyof StepRange, value: number | null) {
const range = { ...props.modelValue?.[key], [bound]: value };
update(key, range.minimum == null && range.maximum == null ? null : range);
}
function setProgression(text: string) {
const values = text.trim() ? text.split(",").map(value => value.trim()) : [];
progressionError.value = values.some(value => !value || !Number.isFinite(Number(value)));
if (!progressionError.value) update("speedProgression", values.map(Number));
}
function setAccessory<K extends keyof StepAccessory>(index: number, key: K, value: StepAccessory[K]) {
const items = [...(props.modelValue?.accessories ?? [])];
const existing = items[index];
if (!existing) return;
items[index] = { ...existing, [key]: value };
update("accessories", items);
}
function addAccessory() { update("accessories", [...(props.modelValue?.accessories ?? []), { name: "", state: "unknown" }]); }
function removeAccessory(index: number) { update("accessories", (props.modelValue?.accessories ?? []).filter((_, i) => i !== index)); }
function setParameter<K extends keyof StepParameter>(index: number, key: K, value: StepParameter[K]) {
const items = [...(props.modelValue?.modeParameters ?? [])];
const existing = items[index];
if (!existing) return;
items[index] = { ...existing, [key]: value };
update("modeParameters", items);
}
function setParameterKind(index: number, kind: NonNullable<StepParameter["kind"]>) {
const items = [...(props.modelValue?.modeParameters ?? [])];
const existing = items[index];
if (!existing || (existing.kind ?? "text") === kind) return;
items[index] = { ...existing, kind, value: null, minimum: null, maximum: null };
update("modeParameters", items);
}
function addParameter() { update("modeParameters", [...(props.modelValue?.modeParameters ?? []), { name: "" }]); }
function removeParameter(index: number) { update("modeParameters", (props.modelValue?.modeParameters ?? []).filter((_, i) => i !== index)); }
function setReview<K extends keyof StepReview>(index: number, key: K, value: StepReview[K]) {
const items = [...(props.modelValue?.reviews ?? [])];
const existing = items[index];
if (!existing) return;
items[index] = { ...existing, [key]: value };
update("reviews", items);
}
function addReview() { update("reviews", [...(props.modelValue?.reviews ?? []), { category: "operation", status: "unresolved" }]); }
function removeReview(index: number) { update("reviews", (props.modelValue?.reviews ?? []).filter((_, i) => i !== index)); }
</script>
<style scoped>
.review-history {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>
@@ -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();
};
+110
View File
@@ -592,6 +592,116 @@
"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": "Step quantities, including full-quantity references, exceed the recipe ingredient quantity.",
"step-remaining-unknown": "The remaining quantity is ambiguous. Review the other allocations and repetitions.",
"step-duration-seconds": "Exact duration (seconds)",
"allocation-kind": "Step allocation",
"allocation-full": "Full recipe quantity",
"allocation-partial": "Specified portion",
"allocation-remaining": "Remaining amount",
"allocation-unknown": "Unknown amount",
"allocation-prepared": "Previously prepared",
"allocation-asNeeded": "As needed",
"allocation-referenceOnly": "Reference only",
"weighing-intent": "Weighing intent",
"weighing-unspecified": "Unspecified",
"weighing-manual": "Manual",
"weighing-weigh": "Weigh",
"allocation-role": "Role",
"allocation-destination": "Destination",
"allocation-minimum": "Minimum quantity",
"allocation-maximum": "Maximum quantity",
"allocation-containers": "Container count (quantity per container)",
"allocation-approximate": "Approximate quantity",
"allocation-source": "Source display text",
"operation-timer-type": "Timer context",
"timer-machine": "Machine timer",
"timer-manual": "Manual timer",
"timer-oven": "Oven timer",
"timer-resting": "Resting timer",
"operation-duration-kind": "Duration setting",
"operation-speed-kind": "Speed setting",
"setting-fixed": "Fixed",
"setting-range": "Range",
"setting-userSelected": "User-selected",
"setting-condition": "Condition-controlled",
"setting-progression": "Progression",
"operation-confirmation": "User confirmation required",
"operation-dependencies": "Dependency step IDs",
"operation-parameter-kind": "Parameter type",
"operation-parameter-kind-hint": "Changing type clears the previous value and bounds.",
"parameter-kind-text": "Text",
"parameter-kind-number": "Number",
"parameter-kind-boolean": "Boolean",
"parameter-kind-range": "Range",
"review-category-schema": "Schema limitation",
"review-category-unsupported": "Unsupported operation",
"operation-review-link": "Link a candidate ingredient (unknown amount)",
"operation-review-history": "Review history",
"operation-type": "Action type",
"operation-instance": "Appliance instance",
"action-manual": "Manual",
"action-machine": "Machine",
"action-oven": "Oven",
"action-waiting": "Waiting",
"action-weighing": "Weighing",
"operation-duration-minimum": "Minimum duration (seconds)",
"operation-duration-maximum": "Maximum duration (seconds)",
"operation-duration-range": "Duration range",
"operation-duration-condition": "Duration condition",
"operation-speed-minimum": "Minimum speed",
"operation-speed-maximum": "Maximum speed",
"operation-speed-range": "Speed range",
"operation-speed-progression": "Speed progression (comma-separated)",
"operation-invalid-progression": "Enter a comma-separated list of numbers.",
"operation-optional": "Optional",
"operation-is-optional": "Optional",
"operation-condition": "Execution condition",
"operation-repetitions": "Repetitions",
"operation-repeat-minimum": "Minimum repetitions",
"operation-repeat-maximum": "Maximum repetitions",
"operation-repetition-range": "Repetition range",
"operation-accessories": "Accessories and setup",
"operation-name": "Name",
"operation-state": "State",
"operation-add-accessory": "Add accessory",
"accessory-installed": "Installed",
"accessory-removed": "Removed",
"accessory-unknown": "Unknown",
"accessory-conditional": "Conditional",
"accessory-open": "Open",
"accessory-closed": "Closed",
"operation-parameters": "Mode parameters",
"operation-parameter-value": "Value",
"operation-parameter-unit": "Unit",
"operation-parameter-minimum": "Minimum",
"operation-parameter-maximum": "Maximum",
"operation-add-parameter": "Add parameter",
"operation-reviews": "Review items",
"operation-review-category": "Category",
"review-category-ingredient": "Ingredient",
"review-category-operation": "Operation",
"operation-review-source": "Source text",
"operation-review-reason": "Reason",
"operation-review-candidates": "Candidate ingredients",
"operation-review-resolution": "Resolution",
"operation-review-status": "Status",
"review-status-unresolved": "Unresolved",
"review-status-resolved": "Resolved",
"operation-add-review": "Add review item",
"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-direction": "Rotation direction",
"step-forward": "Forward rotation",
"step-reverse": "Reverse rotation",
"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",
+70
View File
@@ -467,13 +467,83 @@ export interface RecipeStep {
ingredientReferences?: IngredientReferences[];
noteReferences?: NoteReference[];
durationSeconds?: number | null;
cooking?: StepCooking | null;
}
export interface IngredientReferences {
referenceId?: string | null;
allocationId?: string | null;
quantity?: number | null;
quantityKind?: ("full" | "partial" | "remaining" | "unknown" | "prepared" | "asNeeded" | "referenceOnly") | null;
weighing?: ("unspecified" | "manual" | "weigh") | null;
role?: string | null;
destination?: string | null;
quantityMinimum?: number | null;
quantityMaximum?: number | null;
approximate?: boolean | null;
containerCount?: number | null;
sourceText?: string | null;
}
export interface NoteReference {
referenceId?: string | null;
}
export interface StepCooking {
appliance?: string | null;
temperatureCelsius?: number | null;
speed?: number | string | null;
reverse?: boolean | null;
mode?: string | null;
applianceInstance?: string | null;
actionType?: ("manual" | "machine" | "oven" | "waiting" | "weighing") | null;
timerType?: ("machine" | "manual" | "oven" | "resting") | null;
durationKind?: ("fixed" | "range" | "userSelected" | "condition") | null;
accessories?: StepAccessory[];
durationRangeSeconds?: StepRange | null;
durationCondition?: string | null;
speedRange?: StepRange | null;
speedKind?: ("fixed" | "range" | "progression") | null;
speedProgression?: number[];
modeParameters?: StepParameter[];
optional?: boolean | null;
condition?: string | null;
requiresConfirmation?: boolean | null;
dependsOnStepIds?: string[];
repetitions?: number | null;
repetitionRange?: StepRange | null;
reviews?: StepReview[];
}
export interface StepAccessory {
name: string;
state: "installed" | "removed" | "unknown" | "conditional" | "open" | "closed";
}
export interface StepRange {
minimum?: number | null;
maximum?: number | null;
}
export interface StepParameter {
name: string;
kind?: "text" | "number" | "boolean" | "range";
value?: number | string | boolean | null;
unit?: string | null;
minimum?: number | null;
maximum?: number | null;
}
export interface StepReview {
id?: string;
category: "ingredient" | "operation" | "schema" | "unsupported";
source?: string;
reason?: string;
candidateIngredientIds?: string[];
status?: "unresolved" | "resolved";
resolution?: string | null;
approvedContent?: string | null;
history?: StepReviewEvent[];
}
export interface StepReviewEvent {
at: string;
status: "unresolved" | "resolved";
resolution?: string | null;
content: string;
}
export interface Nutrition {
calories?: string | null;
carbohydrateContent?: string | null;
+70
View File
@@ -205,6 +205,17 @@ export interface IngredientFoodSave {
}
export interface IngredientReferences {
referenceId?: string | null;
allocationId?: string | null;
quantity?: number | null;
quantityKind?: ("full" | "partial" | "remaining" | "unknown" | "prepared" | "asNeeded" | "referenceOnly") | null;
weighing?: ("unspecified" | "manual" | "weigh") | null;
role?: string | null;
destination?: string | null;
quantityMinimum?: number | null;
quantityMaximum?: number | null;
approximate?: boolean | null;
containerCount?: number | null;
sourceText?: string | null;
}
export interface IngredientRequest {
parser?: RegisteredParser;
@@ -380,6 +391,65 @@ 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;
reverse?: boolean | null;
mode?: string | null;
applianceInstance?: string | null;
actionType?: ("manual" | "machine" | "oven" | "waiting" | "weighing") | null;
timerType?: ("machine" | "manual" | "oven" | "resting") | null;
durationKind?: ("fixed" | "range" | "userSelected" | "condition") | null;
accessories?: StepAccessory[];
durationRangeSeconds?: StepRange | null;
durationCondition?: string | null;
speedRange?: StepRange | null;
speedKind?: ("fixed" | "range" | "progression") | null;
speedProgression?: number[];
modeParameters?: StepParameter[];
optional?: boolean | null;
condition?: string | null;
requiresConfirmation?: boolean | null;
dependsOnStepIds?: string[];
repetitions?: number | null;
repetitionRange?: StepRange | null;
reviews?: StepReview[];
}
export interface StepAccessory {
name: string;
state: "installed" | "removed" | "unknown" | "conditional" | "open" | "closed";
}
export interface StepRange {
minimum?: number | null;
maximum?: number | null;
}
export interface StepParameter {
name: string;
kind?: "text" | "number" | "boolean" | "range";
value?: number | string | boolean | null;
unit?: string | null;
minimum?: number | null;
maximum?: number | null;
}
export interface StepReview {
id?: string;
category: "ingredient" | "operation" | "schema" | "unsupported";
source?: string;
reason?: string;
candidateIngredientIds?: string[];
status?: "unresolved" | "resolved";
resolution?: string | null;
approvedContent?: string | null;
history?: StepReviewEvent[];
}
export interface StepReviewEvent {
at: string;
status: "unresolved" | "resolved";
resolution?: string | null;
content: string;
}
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);
+43 -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,46 @@ 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;
}
if (sourceStep.cooking?.reviews?.length || sourceStep.cooking?.dependsOnStepIds?.length
|| steps.some(step => sourceStep.id && step.cooking?.dependsOnStepIds?.includes(sourceStep.id))) {
return null; // Do not discard review identity or break an execution dependency.
}
// 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.allocationId && ref.allocationId && existing.allocationId !== ref.allocationId) {
return null;
}
if (existing.quantityKind || ref.quantityKind || existing.weighing || ref.weighing
|| existing.role || ref.role || existing.destination || ref.destination) {
return null; // Distinct allocation intents cannot safely be combined.
}
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 +66,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,71 @@
import { describe, expect, test } from "vitest";
import { overallocatedIngredientIds, stepIngredients, unresolvedRemainingIngredientIds } 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 when explicit portions exceed the total", () => {
const other: RecipeStep = { text: "Finish", ingredientReferences: [{ referenceId: "a", quantity: 81 }] };
expect([...overallocatedIngredientIds([step, other], ingredients)]).toEqual(["a"]);
});
test("includes inherited full portions in the allocation ledger", () => {
const full: RecipeStep = { text: "Add all", ingredientReferences: [{ referenceId: "a" }] };
const extra: RecipeStep = { text: "Add more", ingredientReferences: [{ referenceId: "a", quantity: 1 }] };
expect([...overallocatedIngredientIds([full], ingredients)]).toEqual([]);
expect([...overallocatedIngredientIds([full, extra], ingredients)]).toEqual(["a"]);
expect([...overallocatedIngredientIds([full, full], ingredients)]).toEqual(["a"]);
});
test("distinguishes explicit zero and unknown recipe totals", () => {
const zero: RecipeIngredient[] = [{ referenceId: "a", quantity: 0 }, { referenceId: "b", quantity: null }];
const refs: RecipeStep = { text: "Mix", ingredientReferences: [{ referenceId: "a", quantity: 1 }, { referenceId: "b", quantity: 100 }] };
expect([...overallocatedIngredientIds([refs], zero)]).toEqual(["a"]);
refs.ingredientReferences![0]!.quantity = 0;
expect([...overallocatedIngredientIds([refs], zero)]).toEqual([]);
});
test("does not inherit quantities for unknown or prepared ingredients", () => {
for (const kind of ["unknown", "prepared", "asNeeded", "referenceOnly"] as const) {
const step: RecipeStep = { text: "Use", ingredientReferences: [{ referenceId: "a", quantity: 0, quantityKind: kind }] };
expect(stepIngredients(step, ingredients)[0]!.quantity).toBeNull();
expect([...overallocatedIngredientIds([step, step], ingredients)]).toEqual([]);
}
});
test("derives only an unambiguous remainder and keeps scaling separate", () => {
const first: RecipeStep = { text: "First", ingredientReferences: [{ referenceId: "a", quantity: 20, quantityKind: "partial", containerCount: 2 }] };
const rest: RecipeStep = { text: "Rest", ingredientReferences: [{ referenceId: "a", quantity: 0, quantityKind: "remaining" }] };
expect(stepIngredients(rest, ingredients, [first, rest])[0]!.quantity).toBe(60);
expect(stepIngredients(rest, ingredients, [first, rest, rest])[0]!.quantity).toBeNull();
expect(rest.ingredientReferences![0]!.quantity).toBe(0);
expect(ingredients[0]!.quantity).toBe(100);
});
test("includes container counts and repetitions in the whole-recipe ledger", () => {
const packets: RecipeStep = {
text: "Add packets", cooking: { repetitions: 2 },
ingredientReferences: [{ referenceId: "a", quantityKind: "partial", quantity: 30, containerCount: 2 }],
};
expect([...overallocatedIngredientIds([packets], ingredients)]).toEqual(["a"]);
});
test("warns when repeated or multiple remainders cannot be quantified safely", () => {
const rest: RecipeStep = {
text: "Use the remainder", cooking: { repetitions: 2 },
ingredientReferences: [{ referenceId: "a", quantityKind: "remaining", quantity: 0 }],
};
expect([...unresolvedRemainingIngredientIds([rest], ingredients)]).toEqual(["a"]);
rest.cooking = null;
expect([...unresolvedRemainingIngredientIds([rest], ingredients)]).toEqual([]);
expect([...unresolvedRemainingIngredientIds([rest, rest], ingredients)]).toEqual(["a"]);
});
});
@@ -0,0 +1,72 @@
import type { IngredientReferences, RecipeIngredient, RecipeStep } from "~/lib/api/types/recipe";
export function allocationKind(reference: IngredientReferences) {
return reference.quantityKind ?? (reference.quantity == null ? "full" : "partial");
}
// Remainders are display-only derived values. Never store them as fixed portions:
// changing the recipe total or another step would make that value stale.
export function remainingQuantity(referenceId: string, steps: RecipeStep[], ingredient: RecipeIngredient): number | null {
if (ingredient.quantity == null) return null;
let allocated = 0;
let remainders = 0;
for (const step of steps) {
for (const ref of step.ingredientReferences ?? []) {
if (ref.referenceId !== referenceId) continue;
const kind = allocationKind(ref);
if (kind === "prepared" || kind === "referenceOnly") continue;
if (["unknown", "asNeeded"].includes(kind) || ref.approximate
|| ref.quantityMinimum != null || ref.quantityMaximum != null
|| step.cooking?.optional || step.cooking?.condition || step.cooking?.repetitionRange) return null;
if (kind === "remaining") {
if ((step.cooking?.repetitions ?? 1) !== 1 || (ref.containerCount ?? 1) !== 1) return null;
remainders++;
}
else allocated += (ref.quantity ?? ingredient.quantity) * (ref.containerCount ?? 1) * (step.cooking?.repetitions ?? 1);
}
}
return remainders === 1 && allocated <= ingredient.quantity ? ingredient.quantity - allocated : null;
}
export function unresolvedRemainingIngredientIds(steps: RecipeStep[], ingredients: RecipeIngredient[]): Set<string> {
const remainingIds = new Set(steps.flatMap(step => (step.ingredientReferences ?? [])
.filter(ref => ref.quantityKind === "remaining" && ref.referenceId).map(ref => ref.referenceId!)));
return new Set(ingredients.filter(ingredient => ingredient.referenceId && remainingIds.has(ingredient.referenceId)
&& remainingQuantity(ingredient.referenceId, steps, ingredient) == null).map(ingredient => ingredient.referenceId!));
}
// Work on copies: the recipe-level list remains the source for shopping lists.
export function stepIngredients(step: RecipeStep, ingredients: RecipeIngredient[], steps: RecipeStep[] = []): RecipeIngredient[] {
return (step.ingredientReferences ?? []).flatMap((reference) => {
const ingredient = ingredients.find(item => item.referenceId && item.referenceId === reference.referenceId);
if (!ingredient) return [];
const kind = allocationKind(reference);
let quantity = reference.quantity ?? ingredient.quantity;
if (kind === "remaining") quantity = remainingQuantity(reference.referenceId!, steps, ingredient);
else if (["unknown", "prepared", "asNeeded", "referenceOnly"].includes(kind)) quantity = null;
else if (quantity != null) quantity *= reference.containerCount ?? 1;
return [{ ...ingredient, quantity, title: "" }];
});
}
export function overallocatedIngredientIds(steps: RecipeStep[], ingredients: RecipeIngredient[]): Set<string> {
const totals = new Map<string, number>();
const recipeQuantities = new Map(ingredients.map(ingredient => [ingredient.referenceId, ingredient.quantity]));
for (const step of steps) {
for (const ref of step.ingredientReferences ?? []) {
if (ref.referenceId) {
if (["remaining", "unknown", "prepared", "asNeeded", "referenceOnly"].includes(allocationKind(ref))) continue;
// A missing portion inherits the entire recipe quantity, not zero.
const quantity = ref.quantityMaximum ?? ref.quantity ?? recipeQuantities.get(ref.referenceId);
if (quantity != null) {
totals.set(ref.referenceId, (totals.get(ref.referenceId) ?? 0)
+ quantity * (ref.containerCount ?? 1) * (step.cooking?.repetitions ?? step.cooking?.repetitionRange?.maximum ?? 1));
}
}
}
}
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!));
}
+5
View File
@@ -4,3 +4,8 @@ allowBuilds:
json-editor-vue: true
unrs-resolver: true
vue-demi: true
# Nuxt modules resolve these existing dependencies from the application root.
publicHoistPattern:
- '@intlify/*'
- vite
@@ -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")
@@ -0,0 +1,32 @@
"""Allow millisecond precision in instruction durations.
Revision ID: e274a9d13c50
Revises: c981d7e62b11
"""
import sqlalchemy as sa
from alembic import op
revision = "e274a9d13c50"
down_revision = "c981d7e62b11"
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table("recipe_instructions") as batch_op:
batch_op.alter_column("duration_seconds", existing_type=sa.Integer(), type_=sa.Float(), existing_nullable=True)
def downgrade():
# Refuse to silently round or truncate newly stored fractional durations.
connection = op.get_bind()
if connection.execute(
sa.text(
"SELECT COUNT(*) FROM recipe_instructions "
"WHERE duration_seconds IS NOT NULL AND duration_seconds != CAST(duration_seconds AS INTEGER)"
)
).scalar_one():
raise RuntimeError("Cannot downgrade while recipe steps have fractional durations")
with op.batch_alter_table("recipe_instructions") as batch_op:
batch_op.alter_column("duration_seconds", existing_type=sa.Float(), type_=sa.Integer(), existing_nullable=True)
@@ -0,0 +1,42 @@
"""Store ingredient allocation intent.
Revision ID: d3f629aa71b4
Revises: e274a9d13c50
"""
import sqlalchemy as sa
from alembic import op
from mealie.db.models._model_utils.guid import GUID
revision = "d3f629aa71b4"
down_revision = "e274a9d13c50"
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table("recipe_ingredient_ref_link") as batch_op:
for name in ("quantity_kind", "weighing", "role", "destination"):
batch_op.add_column(sa.Column(name, sa.String(), nullable=True))
batch_op.add_column(sa.Column("allocation_id", GUID(), nullable=True))
batch_op.add_column(sa.Column("quantity_minimum", sa.Float(), nullable=True))
batch_op.add_column(sa.Column("quantity_maximum", sa.Float(), nullable=True))
batch_op.add_column(sa.Column("approximate", sa.Boolean(), nullable=True))
batch_op.add_column(sa.Column("container_count", sa.Integer(), nullable=True))
batch_op.add_column(sa.Column("source_text", sa.String(), nullable=True))
def downgrade():
with op.batch_alter_table("recipe_ingredient_ref_link") as batch_op:
for name in (
"source_text",
"container_count",
"approximate",
"quantity_maximum",
"quantity_minimum",
"allocation_id",
):
batch_op.drop_column(name)
for name in ("destination", "role", "weighing", "quantity_kind"):
batch_op.drop_column(name)
+14 -3
View File
@@ -1,4 +1,4 @@
from sqlalchemy import ForeignKey, Integer, String, orm
from sqlalchemy import JSON, Boolean, Float, ForeignKey, Integer, String, orm
from sqlalchemy.orm import Mapped, mapped_column
from .._model_base import BaseMixins, SqlAlchemyBase
@@ -10,6 +10,17 @@ 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)
allocation_id: Mapped[GUID | None] = mapped_column(GUID, default=GUID.generate)
quantity: Mapped[float | None] = mapped_column(Float)
quantity_kind: Mapped[str | None] = mapped_column(String)
weighing: Mapped[str | None] = mapped_column(String)
role: Mapped[str | None] = mapped_column(String)
destination: Mapped[str | None] = mapped_column(String)
quantity_minimum: Mapped[float | None] = mapped_column(Float)
quantity_maximum: Mapped[float | None] = mapped_column(Float)
approximate: Mapped[bool | None] = mapped_column(Boolean)
container_count: Mapped[int | None] = mapped_column(Integer)
source_text: Mapped[str | None] = mapped_column(String)
@auto_init()
def __init__(self, **_) -> None:
@@ -35,7 +46,8 @@ class RecipeInstruction(SqlAlchemyBase):
title: Mapped[str | None] = mapped_column(String) # This is the section title
text: Mapped[str | None] = mapped_column(String)
summary: Mapped[str | None] = mapped_column(String)
duration_seconds: Mapped[int | None] = mapped_column(Integer)
duration_seconds: Mapped[float | None] = mapped_column(Float)
cooking: Mapped[dict | None] = mapped_column(JSON)
ingredient_references: Mapped[list[RecipeIngredientRefLink]] = orm.relationship(
RecipeIngredientRefLink, cascade="all, delete-orphan"
@@ -43,7 +55,6 @@ class RecipeInstruction(SqlAlchemyBase):
note_references: Mapped[list[RecipeNoteRefLink]] = orm.relationship(RecipeNoteRefLink, cascade="all, delete-orphan")
model_config = AutoInitOptions(
exclude={
"id",
"ingredient_references",
"note_references",
}
+17 -1
View File
@@ -90,7 +90,17 @@ from .recipe_share_token import (
RecipeShareTokenSave,
RecipeShareTokenSummary,
)
from .recipe_step import IngredientReferences, NoteReference, RecipeStep
from .recipe_step import (
IngredientReferences,
NoteReference,
RecipeStep,
StepAccessory,
StepCooking,
StepParameter,
StepRange,
StepReview,
StepReviewEvent,
)
from .recipe_suggestion import (
RecipeSuggestionQuery,
RecipeSuggestionResponse,
@@ -145,6 +155,12 @@ __all__ = [
"IngredientReferences",
"NoteReference",
"RecipeStep",
"StepAccessory",
"StepCooking",
"StepParameter",
"StepRange",
"StepReview",
"StepReviewEvent",
"RecipeImageTypes",
"Nutrition",
"IngredientConfidence",
+27 -1
View File
@@ -4,7 +4,7 @@ import datetime
from numbers import Number
from pathlib import Path
from typing import Annotated, Any, ClassVar
from uuid import uuid4
from uuid import UUID, uuid4
from pydantic import UUID4, BaseModel, ConfigDict, Field, field_validator, model_validator
from pydantic_core.core_schema import ValidationInfo
@@ -139,6 +139,32 @@ class RecipeDraft(MealieModel):
model_config = ConfigDict(from_attributes=True)
@model_validator(mode="after")
def validate_step_dependencies(self) -> RecipeDraft:
steps = {step.id: step for step in self.recipe_instructions if step.id is not None}
if len(steps) != sum(step.id is not None for step in self.recipe_instructions):
raise ValueError("Instruction identities must be unique within a recipe")
visiting: set[UUID] = set()
visited: set[UUID] = set()
def visit(step_id: UUID) -> None:
if step_id in visiting:
raise ValueError("Step dependencies must not contain a cycle")
if step_id in visited:
return
visiting.add(step_id)
step = steps[step_id]
for dependency in step.cooking.depends_on_step_ids if step.cooking else []:
if dependency not in steps:
raise ValueError("A dependency must reference an instruction in this recipe")
visit(dependency)
visiting.remove(step_id)
visited.add(step_id)
for step_id in steps:
visit(step_id)
return self
@model_validator(mode="before")
@classmethod
def accept_legacy_cook_time(cls, data: Any) -> Any:
+229 -8
View File
@@ -1,7 +1,18 @@
from typing import Any
from uuid import UUID, uuid4
from datetime import datetime
from decimal import Decimal
from typing import Annotated, Any, Literal, Self
from uuid import UUID, uuid4, uuid5
from pydantic import UUID4, ConfigDict, Field, field_validator
from pydantic import (
UUID4,
ConfigDict,
Field,
FiniteFloat,
StrictBool,
field_serializer,
field_validator,
model_validator,
)
from mealie.schema._mealie import MealieModel
@@ -12,14 +23,212 @@ class IngredientReferences(MealieModel):
"""
reference_id: UUID4 | None = None
allocation_id: UUID | None = Field(default_factory=uuid4)
quantity: float | None = Field(default=None, ge=0, allow_inf_nan=False)
quantity_kind: (
Literal["full", "partial", "remaining", "unknown", "prepared", "asNeeded", "referenceOnly"] | None
) = None
weighing: Literal["unspecified", "manual", "weigh"] | None = None
role: str | None = None
destination: str | None = None
quantity_minimum: float | None = Field(default=None, ge=0, allow_inf_nan=False)
quantity_maximum: float | None = Field(default=None, ge=0, allow_inf_nan=False)
approximate: StrictBool | None = None
container_count: int | None = Field(default=None, ge=1, strict=True)
source_text: str | None = None
model_config = ConfigDict(from_attributes=True)
@model_validator(mode="after")
def validate_allocation(self) -> Self:
if self.quantity_minimum is not None and self.quantity_maximum is not None:
if self.quantity_minimum > self.quantity_maximum:
raise ValueError("Quantity minimum must not exceed maximum")
if self.quantity_kind == "full" and self.quantity is not None:
raise ValueError("A full allocation inherits the recipe quantity")
if self.quantity_kind == "partial" and self.quantity is None:
raise ValueError("A partial allocation requires an explicit quantity")
if self.quantity_kind in {"remaining", "unknown", "prepared", "asNeeded", "referenceOnly"}:
# A legacy client treats null as the full recipe quantity. Zero is a
# compatibility sentinel, not a measured amount for these kinds.
if self.quantity not in (None, 0):
raise ValueError("This allocation kind cannot have a numeric quantity")
self.quantity = 0
if self.weighing == "weigh" and self.quantity_kind in {
"remaining",
"unknown",
"prepared",
"asNeeded",
"referenceOnly",
}:
raise ValueError("An unspecified or non-allocation quantity cannot be weighed")
return self
class NoteReference(MealieModel):
reference_id: UUID4 | None = None
model_config = ConfigDict(from_attributes=True)
class StepRange(MealieModel):
model_config = ConfigDict(extra="forbid")
minimum: float | None = Field(default=None, strict=True, allow_inf_nan=False)
maximum: float | None = Field(default=None, strict=True, allow_inf_nan=False)
@model_validator(mode="after")
def validate_bounds(self) -> Self:
if self.minimum is None and self.maximum is None:
raise ValueError("A range requires at least one bound")
if self.minimum is not None and self.maximum is not None and self.minimum > self.maximum:
raise ValueError("Range minimum must not exceed maximum")
return self
class StepAccessory(MealieModel):
model_config = ConfigDict(extra="forbid")
name: str = Field(min_length=1)
state: Literal["installed", "removed", "unknown", "conditional", "open", "closed"]
class StepParameter(MealieModel):
model_config = ConfigDict(extra="forbid")
name: str = Field(min_length=1)
kind: Literal["text", "number", "boolean", "range"] = "text"
value: FiniteFloat | str | StrictBool | None = None
unit: str | None = None
minimum: float | None = Field(default=None, strict=True, allow_inf_nan=False)
maximum: float | None = Field(default=None, strict=True, allow_inf_nan=False)
@model_validator(mode="after")
def validate_bounds(self) -> Self:
if self.value is not None:
if self.kind == "number" and (isinstance(self.value, bool) or not isinstance(self.value, (int, float))):
raise ValueError("A numeric parameter requires a number")
if self.kind == "boolean" and not isinstance(self.value, bool):
raise ValueError("A boolean parameter requires a boolean")
if self.kind == "text" and not isinstance(self.value, str):
raise ValueError("A text parameter requires text")
if self.kind == "range":
raise ValueError("A range parameter uses minimum/maximum, not a fixed value")
if self.kind != "range" and (self.minimum is not None or self.maximum is not None):
raise ValueError("Only range parameters accept minimum/maximum")
if self.kind == "range" and self.minimum is None and self.maximum is None:
raise ValueError("A range parameter requires at least one bound")
if self.minimum is not None and self.maximum is not None and self.minimum > self.maximum:
raise ValueError("Parameter minimum must not exceed maximum")
return self
class StepReviewEvent(MealieModel):
model_config = ConfigDict(extra="forbid")
at: datetime
status: Literal["unresolved", "resolved"]
resolution: str | None = None
content: str
@field_serializer("at")
def serialize_at(self, value: datetime) -> str:
return value.isoformat()
class StepReview(MealieModel):
model_config = ConfigDict(extra="forbid")
id: UUID4 = Field(default_factory=uuid4)
category: Literal["ingredient", "operation", "schema", "unsupported"]
source: str = ""
reason: str = ""
candidate_ingredient_ids: list[UUID4] = Field(default_factory=list)
status: Literal["unresolved", "resolved"] = "unresolved"
resolution: str | None = None
approved_content: str | None = None
history: list[StepReviewEvent] = Field(default_factory=list)
@field_serializer("id")
def serialize_id(self, value: UUID) -> str:
return str(value)
@field_serializer("candidate_ingredient_ids")
def serialize_candidates(self, value: list[UUID]) -> list[str]:
return [str(candidate) for candidate in value]
@model_validator(mode="after")
def validate_resolution(self) -> Self:
if self.status == "resolved" and not (self.resolution and self.resolution.strip()):
raise ValueError("Resolving a review requires an explanation")
return self
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
reverse: StrictBool | None = None
mode: str | None = None
appliance_instance: str | None = None
action_type: Literal["manual", "machine", "oven", "waiting", "weighing"] | None = None
timer_type: Literal["machine", "manual", "oven", "resting"] | None = None
duration_kind: Literal["fixed", "range", "userSelected", "condition"] | None = None
accessories: list[StepAccessory] = Field(default_factory=list)
duration_range_seconds: StepRange | None = None
duration_condition: str | None = None
speed_range: StepRange | None = None
speed_kind: Literal["fixed", "range", "progression"] | None = None
speed_progression: list[Annotated[float, Field(strict=True, allow_inf_nan=False)]] = Field(default_factory=list)
mode_parameters: list[StepParameter] = Field(default_factory=list)
optional: StrictBool | None = None
condition: str | None = None
requires_confirmation: StrictBool | None = None
depends_on_step_ids: list[UUID] = Field(default_factory=list)
repetitions: int | None = Field(default=None, ge=1, strict=True)
repetition_range: StepRange | None = None
reviews: list[StepReview] = Field(default_factory=list)
@field_serializer("depends_on_step_ids")
def serialize_dependencies(self, value: list[UUID]) -> list[str]:
return [str(dependency) for dependency in value]
@model_validator(mode="after")
def validate_timing(self) -> Self:
if self.duration_kind == "range" and not self.duration_range_seconds:
raise ValueError("A duration range requires bounds")
if self.duration_kind == "condition" and not self.duration_condition:
raise ValueError("Condition-controlled duration requires a description")
if self.speed_kind == "range" and not self.speed_range:
raise ValueError("A speed range requires bounds")
if self.speed_kind == "progression" and len(self.speed_progression) < 2:
raise ValueError("A speed progression requires at least two speeds")
parameter_names = [parameter.name for parameter in self.mode_parameters]
if len(set(parameter_names)) != len(parameter_names):
raise ValueError("Mode parameter names must be unique within an operation")
if self.duration_range_seconds:
for value in (self.duration_range_seconds.minimum, self.duration_range_seconds.maximum):
if value is not None and value <= 0:
raise ValueError("Duration range must be positive")
if value is not None:
if value > 2147483647 or Decimal(str(value)) % Decimal("0.001") != 0:
raise ValueError("Duration bounds require millisecond precision within the supported range")
if self.repetition_range:
for value in (self.repetition_range.minimum, self.repetition_range.maximum):
if value is not None and (value < 1 or not value.is_integer()):
raise ValueError("Repetition bounds must be positive whole numbers")
return self
@field_validator("temperature_celsius", "speed", mode="before")
@classmethod
def reject_boolean_settings(cls, value: Any) -> Any:
if isinstance(value, bool):
raise ValueError("A cooking setting cannot be a boolean")
return value
class RecipeStep(MealieModel):
id: UUID | None = Field(default_factory=uuid4)
title: str | None = "" # This is the section title!!!
@@ -29,16 +238,28 @@ class RecipeStep(MealieModel):
note_references: list[NoteReference] = []
model_config = ConfigDict(from_attributes=True)
duration_seconds: int | None = Field(default=None, ge=1, le=2147483647, strict=True)
duration_seconds: float | None = Field(default=None, ge=0.001, le=2147483647, strict=True, allow_inf_nan=False)
cooking: StepCooking | None = None
@model_validator(mode="after")
def legacy_allocation_identities(self) -> Self:
# Older rows have no allocation ID yet. Derive a stable one on read and
# persist it at the next save, without changing their quantities.
if self.id:
for index, reference in enumerate(self.ingredient_references):
if reference.allocation_id is None:
reference.allocation_id = uuid5(self.id, f"{index}:{reference.reference_id}")
return self
@field_validator("duration_seconds", mode="before")
@classmethod
def normalize_duration(cls, value: Any) -> Any:
if isinstance(value, bool):
raise ValueError("Duration must be a whole number of seconds, not a boolean")
raise ValueError("Duration must be a number of seconds, not a boolean")
if value == 0:
return None
# JSON 1, 1.0 and 1e0 express the same whole number. Never round a fraction.
if isinstance(value, float) and 1 <= value <= 2147483647 and value.is_integer():
return int(value)
if isinstance(value, (int, float)):
seconds = Decimal(str(value))
if seconds.is_finite() and 0 < seconds <= 2147483647 and seconds % Decimal("0.001") != 0:
raise ValueError("Duration must have at most millisecond precision")
return value
@@ -68,17 +68,29 @@ 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.model_dump(exclude={"reference_id", "allocation_id"}, exclude_none=True)
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)):
has_timing_context = step.cooking and (
step.cooking.duration_kind or step.cooking.duration_range_seconds or step.cooking.duration_condition
)
if (
step.duration_seconds is None
and not has_timing_context
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:
+53 -7
View File
@@ -41,6 +41,7 @@ from mealie.services.household_services.household_service import HouseholdServic
from mealie.services.parser_services._base import DataMatcher
from mealie.services.recipe.mealie_export import InvalidMealieExportError
from mealie.services.recipe.recipe_data_service import RecipeDataService
from mealie.services.recipe.step_review import reconcile_step_reviews
from .template_service import TemplateService
@@ -222,6 +223,7 @@ class RecipeService(RecipeServiceBase):
data.settings = RecipeSettings()
rating_input = data.rating
reconcile_step_reviews(None, data)
new_recipe = self.repos.recipes.create(data)
# convert rating into user rating
@@ -410,9 +412,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
@@ -468,9 +469,23 @@ class RecipeService(RecipeServiceBase):
def clean_recipe_dict(self, recipe: dict[str, Any]) -> dict[str, Any]:
# The checks below only recognise snake_case keys. camelCase input would skip them, and its
# `groupId` would win over the group stamped on each object, so normalise the keys first.
recipe = RecipeDraft.model_validate(recipe).model_dump(mode="json")
draft = RecipeDraft.model_validate(recipe)
self._remap_step_identities(draft)
recipe = draft.model_dump(mode="json")
return self._process_recipe_data("recipe", self._replace_taken_id(recipe))
@staticmethod
def _remap_step_identities(draft: RecipeDraft) -> None:
step_ids = {step.id: uuid4() for step in draft.recipe_instructions if step.id is not None}
for step in draft.recipe_instructions:
step.id = step_ids[step.id] if step.id is not None else uuid4()
for reference in step.ingredient_references:
reference.allocation_id = uuid4()
if step.cooking:
step.cooking.depends_on_step_ids = [
step_ids.get(dependency, dependency) for dependency in step.cooking.depends_on_step_ids
]
def _apply_household_visibility(self, recipe: RecipeDraft) -> None:
"""Make an imported recipe follow the household's `recipe_public` preference.
@@ -556,17 +571,46 @@ 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
}
step_reference_map = {step.id: uuid4() for step in old_recipe.recipe_instructions}
# 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_id = step_reference_map[step.id]
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),
"allocation_id": uuid4(),
}
)
for ref in step.ingredient_references
]
cooking = step.cooking.model_copy(deep=True) if step.cooking else None
if cooking:
cooking.depends_on_step_ids = [
step_reference_map.get(dependency, dependency) for dependency in cooking.depends_on_step_ids
]
for review in cooking.reviews:
review.id = uuid4()
review.candidate_ingredient_ids = [
ingredient_reference_map.get(candidate, candidate)
for candidate in review.candidate_ingredient_ids
]
new_step = step.model_copy(
update={"id": new_id, "text": new_text, "ingredient_references": refs, "cooking": cooking}
)
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
@@ -576,6 +620,7 @@ class RecipeService(RecipeServiceBase):
draft.image = cache.cache_key.new_key() if old_recipe.image else None
draft.recipe_instructions = list(map(replace_recipe_step, old_recipe.recipe_instructions))
draft.recipe_ingredient = list(map(copy_recipe_ingredient, old_recipe.recipe_ingredient))
reconcile_step_reviews(None, draft)
new_recipe = self.repos.recipes.create(
self._recipe_creation_factory(new_name, additional_attrs=draft.model_dump())
@@ -781,6 +826,7 @@ class RecipeService(RecipeServiceBase):
update_data = self._remove_non_existent_note_references(update_data)
update_data = self._resolve_ingredient_sub_recipes(update_data)
update_data = self._validate_reassignment(recipe, update_data)
reconcile_step_reviews(recipe, update_data)
new_data = self.group_recipes.update(recipe.slug, update_data)
self.check_assets(new_data, recipe.slug)
+61
View File
@@ -0,0 +1,61 @@
"""Native, appliance-independent review provenance. No bridge metadata is read here."""
import json
from datetime import UTC, datetime
from mealie.schema.recipe.recipe import RecipeDraft, RecipeOut
from mealie.schema.recipe.recipe_step import RecipeStep, StepCooking, StepReviewEvent
def step_content(step: RecipeStep, recipe: RecipeDraft | RecipeOut) -> str:
content = step.model_dump(mode="json", exclude={"cooking": {"reviews"}})
# Recipe quantities/identities also affect inherited allocations.
content["ingredients"] = [
{
"referenceId": str(ingredient.reference_id),
"quantity": ingredient.quantity,
"unitId": str(ingredient.unit.id) if ingredient.unit else None,
"foodId": str(ingredient.food.id) if ingredient.food else None,
"note": ingredient.note,
}
for ingredient in recipe.recipe_ingredient
]
return json.dumps(content, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
def reconcile_step_reviews(previous: RecipeOut | None, updated: RecipeDraft) -> None:
old_steps = {step.id: step for step in previous.recipe_instructions} if previous else {}
for step in updated.recipe_instructions:
old_step = old_steps.get(step.id)
old_reviews = (
{review.id: review for review in old_step.cooking.reviews} if old_step and old_step.cooking else {}
)
if old_reviews:
step.cooking = step.cooking or StepCooking()
incoming_ids = {review.id for review in step.cooking.reviews}
# Editing with an older client must not erase unresolved provenance.
step.cooking.reviews.extend(
review.model_copy(deep=True) for rid, review in old_reviews.items() if rid not in incoming_ids
)
if not step.cooking:
continue
current = step_content(step, updated)
for review in step.cooking.reviews:
old_review = old_reviews.get(review.id)
if old_review:
# The original evidence and prior history are not editable approvals.
review.source = old_review.source
review.reason = old_review.reason
review.candidate_ingredient_ids = list(old_review.candidate_ingredient_ids)
review.history = list(old_review.history)
review.approved_content = old_review.approved_content
if old_review.status == "resolved" and old_review.approved_content != current:
review.status = "unresolved"
if review.status == "resolved":
review.approved_content = current
if old_review is None or (review.status != old_review.status or review.resolution != old_review.resolution):
review.history.append(
StepReviewEvent(
at=datetime.now(UTC), status=review.status, resolution=review.resolution, content=current
)
)
@@ -64,8 +64,16 @@ 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",
"reverse": True,
"mode": "steaming",
},
}
],
}
@@ -91,6 +99,67 @@ 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
@pytest.mark.parametrize("reverse", [True, False, None])
def test_update_rotation_direction(api_client: TestClient, unique_user: TestUser, reverse: bool | None):
recipe = create_populated_recipe(api_client, unique_user)
recipe["recipeInstructions"][0]["cooking"]["reverse"] = reverse
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]["cooking"]["reverse"] is reverse
assert saved["recipeInstructions"][0]["cooking"]["speed"] == "spoon"
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 +204,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)
@@ -29,13 +29,13 @@ def test_duration_persists_edits_clears_and_exports_for_zip_import(api_client, u
assert [step["durationSeconds"] for step in reloaded["recipeInstructions"]] == [None, None, 3661]
# Fresh GET crosses the request-scoped session boundary, rather than reading a mock ORM object.
reloaded["recipeInstructions"][2]["durationSeconds"] = 42
reloaded["recipeInstructions"][2]["durationSeconds"] = 0.5
assert api_client.put(route, json=reloaded, headers=unique_user.token).status_code == 200
reloaded = api_client.get(route, headers=unique_user.token).json()
assert reloaded["recipeInstructions"][2]["durationSeconds"] == 42
assert reloaded["recipeInstructions"][2]["durationSeconds"] == 0.5
exported = TemplateService(temp=tmp_path).render(RecipeDraft.model_validate(reloaded), "raw")
imported = json.loads(exported.read_text())
assert [step["durationSeconds"] for step in imported["recipeInstructions"]] == [None, None, 42]
assert [step["durationSeconds"] for step in imported["recipeInstructions"]] == [None, None, 0.5]
imported["id"] = str(uuid4())
imported["name"] = imported["slug"] = f"duration-import-{uuid4()}"
for step in imported["recipeInstructions"]:
@@ -49,7 +49,7 @@ def test_duration_persists_edits_clears_and_exports_for_zip_import(api_client, u
assert response.status_code == 201
restored = api_client.get(api_routes.recipes_slug(imported["slug"]), headers=unique_user.token)
assert restored.status_code == 200
assert [step["durationSeconds"] for step in restored.json()["recipeInstructions"]] == [None, None, 42]
assert [step["durationSeconds"] for step in restored.json()["recipeInstructions"]] == [None, None, 0.5]
reloaded["recipeInstructions"][2]["durationSeconds"] = clear_value
assert api_client.put(route, json=reloaded, headers=unique_user.token).status_code == 200
@@ -67,11 +67,11 @@ def test_api_persists_whole_numeric_spellings(api_client, unique_user, random_re
response = api_client.put(route, content=body, headers={**unique_user.token, "Content-Type": "application/json"})
assert response.status_code == 200
restored = api_client.get(route, headers=unique_user.token).json()["recipeInstructions"][0]
assert type(restored["durationSeconds"]) is int
assert type(restored["durationSeconds"]) is float
assert restored["durationSeconds"] == int(float(number))
@pytest.mark.parametrize("value", [True, False, "90", -1, 1.5, 2147483647.5, "", " ", 2147483648])
@pytest.mark.parametrize("value", [True, False, "90", -1, 0.0001, 1.2345, 2147483647.5, "", " ", 2147483648])
def test_api_rejects_invalid_duration_without_saving(api_client, unique_user, random_recipe, value):
route = api_routes.recipes_slug(random_recipe.slug)
before = api_client.get(route, headers=unique_user.token).json()
@@ -0,0 +1,199 @@
import json
from uuid import uuid4
from mealie.schema.recipe.recipe_step import IngredientReferences, StepCooking
from tests.utils import api_routes
def operation_recipe(api_client, unique_user):
slug = api_client.post(api_routes.recipes, json={"name": f"Operations {uuid4()}"}, headers=unique_user.token).json()
route = api_routes.recipes_slug(slug)
recipe = api_client.get(route, headers=unique_user.token).json()
ref_id, step_id = str(uuid4()), str(uuid4())
recipe["recipeIngredient"] = [{"referenceId": ref_id, "quantity": 100, "note": "flour"}]
recipe["recipeInstructions"] = [
{
"id": step_id,
"text": "Mix and check consistency",
"durationSeconds": 0.5,
"ingredientReferences": [
{
"referenceId": ref_id,
"quantityKind": "partial",
"quantity": 20,
"weighing": "weigh",
"role": "addition",
"destination": "bowl",
"quantityMinimum": 19,
"quantityMaximum": 21,
"approximate": True,
"containerCount": 2,
"sourceText": "two portions",
}
],
"cooking": {
"appliance": "mixer",
"applianceInstance": "left",
"actionType": "machine",
"timerType": "machine",
"durationKind": "range",
"temperatureCelsius": 37.5,
"speed": 1.5,
"reverse": False,
"mode": "pulse",
"durationRangeSeconds": {"minimum": 0.5, "maximum": 2.5},
"durationCondition": "Until combined",
"speedKind": "progression",
"speedRange": {"minimum": 1, "maximum": 5},
"speedProgression": [1, 3, 5],
"accessories": [
{"name": name, "state": state}
for name, state in [
("steamer", "installed"),
("basket", "removed"),
("whisk", "unknown"),
("lid", "closed"),
]
],
"modeParameters": [
{"name": "thickness", "kind": "text", "value": "coarse"},
{"name": "doneness", "kind": "text", "value": "medium soft"},
{"name": "pulses", "kind": "number", "value": 3},
{"name": "cover", "kind": "boolean", "value": False},
{"name": "pulseRange", "kind": "range", "minimum": 2, "maximum": 4},
],
"optional": True,
"condition": "If too coarse",
"requiresConfirmation": True,
"repetitions": 3,
"repetitionRange": {"minimum": 2, "maximum": 4},
"reviews": [
{
"category": "ingredient",
"source": "add some flour",
"reason": "Ambiguous portion",
"candidateIngredientIds": [ref_id],
}
],
},
},
{
"text": "Reuse mixture",
"ingredientReferences": [{"referenceId": ref_id, "quantityKind": "prepared"}],
"cooking": {"actionType": "manual", "dependsOnStepIds": [step_id]},
},
]
response = api_client.put(route, json=recipe, headers=unique_user.token)
assert response.status_code == 200, response.text
saved = api_client.get(route, headers=unique_user.token).json()
desired = StepCooking.model_validate(recipe["recipeInstructions"][0]["cooking"]).model_dump(
mode="json", by_alias=True
)
actual = saved["recipeInstructions"][0]["cooking"]
assert {key: value for key, value in actual.items() if key != "reviews"} == {
key: value for key, value in desired.items() if key != "reviews"
}
desired_reference = IngredientReferences.model_validate(
recipe["recipeInstructions"][0]["ingredientReferences"][0]
).model_dump(mode="json", by_alias=True)
assert {
key: value
for key, value in saved["recipeInstructions"][0]["ingredientReferences"][0].items()
if key != "allocationId"
} == {key: value for key, value in desired_reference.items() if key != "allocationId"}
return saved
def test_full_operations_round_trip_edit_duplicate_and_export(api_client, unique_user):
recipe = operation_recipe(api_client, unique_user)
step = recipe["recipeInstructions"][0]
assert step["durationSeconds"] == 0.5
assert step["ingredientReferences"][0]["weighing"] == "weigh"
assert step["cooking"]["modeParameters"][3]["value"] is False
allocation_id = step["ingredientReferences"][0]["allocationId"]
review = step["cooking"]["reviews"][0]
assert review["history"] and review["status"] == "unresolved"
review["resolution"], review["status"] = "Confirmed portion and manual check", "resolved"
route = api_routes.recipes_slug(recipe["slug"])
assert api_client.put(route, json=recipe, headers=unique_user.token).status_code == 200
saved = api_client.get(route, headers=unique_user.token).json()
assert saved["recipeInstructions"][0]["ingredientReferences"][0]["allocationId"] == allocation_id
assert saved["recipeInstructions"][0]["cooking"]["reviews"][0]["approvedContent"]
assert saved["recipeInstructions"][0]["id"] == step["id"]
# Reordering never renumbers instruction/allocation identities or loses dependencies.
saved["recipeInstructions"].reverse()
assert api_client.put(route, json=saved, headers=unique_user.token).status_code == 200
reordered = api_client.get(route, headers=unique_user.token).json()
assert reordered["recipeInstructions"][1]["id"] == step["id"]
assert reordered["recipeInstructions"][1]["ingredientReferences"][0]["allocationId"] == allocation_id
saved["recipeInstructions"].reverse()
assert api_client.put(route, json=saved, headers=unique_user.token).status_code == 200
duplicated = api_client.post(
api_routes.recipes_slug_duplicate(recipe["slug"]), json={"name": f"Copy {uuid4()}"}, headers=unique_user.token
)
assert duplicated.status_code == 201, duplicated.text
copy = duplicated.json()
copied_step = copy["recipeInstructions"][0]
assert copied_step["id"] != step["id"]
assert copied_step["ingredientReferences"][0]["allocationId"] != allocation_id
assert copy["recipeInstructions"][1]["cooking"]["dependsOnStepIds"] == [copied_step["id"]]
assert copied_step["cooking"]["reviews"][0]["candidateIngredientIds"] == [
copy["recipeIngredient"][0]["referenceId"]
]
assert copied_step["cooking"]["modeParameters"] == step["cooking"]["modeParameters"]
response = api_client.post(
api_routes.recipes_create_html_or_json,
json={"data": json.dumps(saved), "include_tags": True, "include_categories": True},
headers=unique_user.token,
)
assert response.status_code == 201, response.text
imported = api_client.get(api_routes.recipes_slug(response.json()), headers=unique_user.token).json()
assert imported["recipeInstructions"][0]["cooking"]["modeParameters"] == step["cooking"]["modeParameters"]
assert imported["recipeInstructions"][0]["ingredientReferences"][0]["quantityKind"] == "partial"
assert imported["recipeInstructions"][1]["cooking"]["dependsOnStepIds"] == [imported["recipeInstructions"][0]["id"]]
def test_changed_native_content_reopens_review_without_erasing_history(api_client, unique_user):
recipe = operation_recipe(api_client, unique_user)
route = api_routes.recipes_slug(recipe["slug"])
review = recipe["recipeInstructions"][0]["cooking"]["reviews"][0]
review.update(status="resolved", resolution="Checked")
assert api_client.put(route, json=recipe, headers=unique_user.token).status_code == 200
saved = api_client.get(route, headers=unique_user.token).json()
history = saved["recipeInstructions"][0]["cooking"]["reviews"][0]["history"]
saved["recipeInstructions"][0]["cooking"]["speed"] = 2
assert api_client.put(route, json=saved, headers=unique_user.token).status_code == 200
changed = api_client.get(route, headers=unique_user.token).json()
review = changed["recipeInstructions"][0]["cooking"]["reviews"][0]
assert review["status"] == "unresolved"
assert review["history"][: len(history)] == history
assert review["source"] == "add some flour"
changed["recipeInstructions"][0]["cooking"] = None
assert api_client.put(route, json=changed, headers=unique_user.token).status_code == 200
assert api_client.get(route, headers=unique_user.token).json()["recipeInstructions"][0]["cooking"]["reviews"]
def test_all_allocation_kinds_survive_readback(api_client, unique_user):
recipe = operation_recipe(api_client, unique_user)
reference_id = recipe["recipeIngredient"][0]["referenceId"]
kinds = ["full", "partial", "remaining", "unknown", "prepared", "asNeeded", "referenceOnly"]
recipe["recipeInstructions"] = [
{
"text": kind,
"ingredientReferences": [
{"referenceId": reference_id, "quantityKind": kind, "quantity": 0 if kind == "partial" else None}
],
}
for kind in kinds
]
route = api_routes.recipes_slug(recipe["slug"])
response = api_client.put(route, json=recipe, headers=unique_user.token)
assert response.status_code == 200, response.text
saved = api_client.get(route, headers=unique_user.token).json()
refs = [step["ingredientReferences"][0] for step in saved["recipeInstructions"]]
assert [ref["quantityKind"] for ref in refs] == kinds
assert [ref["quantity"] for ref in refs] == [None, 0, 0, 0, 0, 0, 0]
assert saved["recipeIngredient"][0]["quantity"] == 100
assert all(ref["weighing"] is None for ref in refs)
@@ -0,0 +1,104 @@
"""Upgrade a populated, pre-feature database using the actual Alembic chain."""
from pathlib import Path
from types import SimpleNamespace
from uuid import uuid4
from alembic import command
from alembic.config import Config
from sqlalchemy import MetaData, create_engine, inspect, select, text
from sqlalchemy.engine import make_url
from mealie.core import config as app_config
from mealie.core.config import get_app_settings
def test_upgrade_existing_database_preserves_legacy_recipes(tmp_path, monkeypatch):
settings = get_app_settings()
admin_engine = create_engine(settings.DB_URL)
database = f"guided_migration_{uuid4().hex}"
if admin_engine.dialect.name == "postgresql":
with admin_engine.connect().execution_options(isolation_level="AUTOCOMMIT") as connection:
connection.execute(text(f'CREATE DATABASE "{database}"'))
url = make_url(settings.DB_URL).set(database=database)
else:
url = make_url(f"sqlite:///{tmp_path / 'legacy.db'}")
engine = create_engine(url)
monkeypatch.setattr(
app_config,
"get_app_settings",
lambda: SimpleNamespace(DB_URL=url.render_as_string(hide_password=False), DEFAULT_HOUSEHOLD="Test"),
)
config = Config(str(Path(__file__).parents[3] / "mealie/alembic/alembic.ini"))
try:
command.upgrade(config, "c981d7e62b11")
metadata = MetaData()
metadata.reflect(engine)
with engine.begin() as connection:
instruction_id, reference_id = str(uuid4()), str(uuid4())
connection.execute(
metadata.tables["recipe_instructions"].insert(),
{
"id": instruction_id,
"text": "Legacy instruction",
"duration_seconds": 90,
"cooking": {"appliance": "mixer", "speed": 2, "reverse": True},
},
)
connection.execute(
metadata.tables["recipe_ingredient_ref_link"].insert(),
{
"instruction_id": instruction_id,
"reference_id": reference_id,
"quantity": 12,
},
)
with engine.connect() as connection:
before = {
name: sorted([tuple(row) for row in connection.execute(select(table))], key=repr)
for name, table in metadata.tables.items()
if name != "alembic_version"
}
assert before["recipe_instructions"]
command.upgrade(config, "head")
with engine.connect() as connection:
for name, table in metadata.tables.items():
if name == "alembic_version":
continue
assert sorted([tuple(row) for row in connection.execute(select(table))], key=repr) == before[name], name
assert (
connection.scalar(
text("SELECT COUNT(*) FROM recipe_ingredient_ref_link WHERE quantity_kind IS NOT NULL")
)
== 0
)
columns = {column["name"]: column for column in inspect(engine).get_columns("recipe_ingredient_ref_link")}
for name in (
"allocation_id",
"quantity_kind",
"weighing",
"role",
"destination",
"quantity_minimum",
"quantity_maximum",
"approximate",
"container_count",
"source_text",
):
assert columns[name]["nullable"]
with engine.begin() as connection:
connection.execute(text("UPDATE recipe_instructions SET duration_seconds = 0.5"))
assert connection.scalar(text("SELECT MIN(duration_seconds) FROM recipe_instructions")) == 0.5
connection.execute(text("UPDATE recipe_instructions SET duration_seconds = 90"))
command.downgrade(config, "c981d7e62b11")
with engine.connect() as connection:
for name, table in metadata.tables.items():
if name != "alembic_version":
assert sorted([tuple(row) for row in connection.execute(select(table))], key=repr) == before[name]
command.upgrade(config, "head")
finally:
engine.dispose()
if admin_engine.dialect.name == "postgresql":
with admin_engine.connect().execution_options(isolation_level="AUTOCOMMIT") as connection:
connection.execute(text(f'DROP DATABASE "{database}"'))
admin_engine.dispose()
@@ -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,52 @@
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
def load_migration():
path = (
Path(__file__).parents[2]
/ "mealie/alembic/versions/2026-12-01-00.00.00_e274a9d13c50_fractional_step_duration.py"
)
spec = spec_from_file_location("fractional_step_duration_migration", path)
module = module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_postgresql_upgrade_sql():
output = StringIO()
context = MigrationContext.configure(dialect_name="postgresql", opts={"as_sql": True, "output_buffer": output})
with Operations.context(context):
load_migration().upgrade()
assert "ALTER COLUMN DURATION_SECONDS TYPE FLOAT" in output.getvalue().upper()
def test_sqlite_migration_and_safe_downgrade():
engine = create_engine("sqlite://")
migration = load_migration()
with engine.begin() as connection:
connection.execute(text("CREATE TABLE recipe_instructions (id INTEGER PRIMARY KEY, duration_seconds INTEGER)"))
connection.execute(text("INSERT INTO recipe_instructions VALUES (1, 90), (2, NULL)"))
with Operations.context(MigrationContext.configure(connection)):
migration.upgrade()
assert str(inspect(connection).get_columns("recipe_instructions")[1]["type"]) == "FLOAT"
durations = connection.execute(text("SELECT duration_seconds FROM recipe_instructions ORDER BY id"))
assert durations.scalars().all() == [
90,
None,
]
connection.execute(text("UPDATE recipe_instructions SET duration_seconds = 0.5 WHERE id = 1"))
with pytest.raises(RuntimeError, match="fractional durations"):
migration.downgrade()
assert connection.scalar(text("SELECT duration_seconds FROM recipe_instructions WHERE id = 1")) == 0.5
connection.execute(text("UPDATE recipe_instructions SET duration_seconds = 90 WHERE id = 1"))
migration.downgrade()
assert str(inspect(connection).get_columns("recipe_instructions")[1]["type"]) == "INTEGER"
assert connection.scalar(text("SELECT duration_seconds FROM recipe_instructions WHERE id = 1")) == 90
engine.dispose()
@@ -5,7 +5,7 @@ from uuid import uuid4
import pytest
from pydantic import ValidationError
from sqlalchemy import Integer
from sqlalchemy import Float
from sqlalchemy.orm import Session
from mealie.db.models import _all_models # noqa: F401 - register ORM relationships without DB startup
@@ -27,7 +27,7 @@ def test_legacy_step_is_not_assigned_a_time():
assert step.text == "Bake for a while"
@pytest.mark.parametrize("seconds", [1, 90, 3661, 172801, 2147483647])
@pytest.mark.parametrize("seconds", [0.001, 0.5, 1, 1.234, 90, 3661, 172801, 2147483647])
def test_exact_duration_survives_model_and_recipe_json(seconds):
step = RecipeStep(text="Rest", durationSeconds=seconds)
# Exercise the existing create mapping, without connecting or writing to a DB.
@@ -44,7 +44,7 @@ def test_exact_duration_survives_model_and_recipe_json(seconds):
@pytest.mark.parametrize("number", ["1", "1.0", "1e0", "2147483647.0"])
def test_whole_numeric_json_spellings_are_equivalent(number):
step = RecipeStep.model_validate_json('{"text":"Rest","durationSeconds":' + number + "}")
assert type(step.duration_seconds) is int
assert type(step.duration_seconds) is float
assert step.duration_seconds == int(float(number))
@@ -54,8 +54,8 @@ def test_whole_numeric_json_spellings_are_equivalent(number):
True,
False,
-1,
1.5,
0.5,
0.0001,
1.2345,
2147483647.5,
float("inf"),
float("-inf"),
@@ -77,7 +77,7 @@ def test_duration_rejects_lossy_or_out_of_range_input(value):
def test_duration_column_is_nullable_without_a_zero_default():
column = RecipeInstruction.__table__.c.duration_seconds
assert isinstance(column.type, Integer)
assert isinstance(column.type, Float)
assert column.nullable
assert column.default is None
assert column.server_default is None
@@ -138,13 +138,13 @@ def test_existing_instruction_update_and_clear_without_database():
assert instruction.text == "Rest"
def test_api_schema_documents_optional_integer_seconds():
def test_api_schema_documents_optional_decimal_seconds():
schema = RecipeStep.model_json_schema(by_alias=True)
duration = schema["properties"]["durationSeconds"]
assert "durationSeconds" not in schema["required"]
assert duration["default"] is None
assert duration["anyOf"] == [
{"maximum": 2147483647, "minimum": 1, "type": "integer"},
{"maximum": 2147483647, "minimum": 0.001, "type": "number"},
{"type": "null"},
]
@@ -0,0 +1,47 @@
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, "unknownSetting": True})
assert "reverse" in StepCooking.model_json_schema(by_alias=True)["properties"]
@pytest.mark.parametrize("reverse", [True, False, None])
def test_rotation_direction_round_trip(reverse):
step = RecipeStep.model_validate({"text": "Mix", "cooking": {"speed": "spoon", "reverse": reverse}})
saved = RecipeStep.model_validate_json(step.model_dump_json(by_alias=True))
assert saved.cooking.reverse is reverse
assert StepCooking().reverse is None
@pytest.mark.parametrize("reverse", ["false", "true", 0, 1, "inversa"])
def test_invalid_rotation_direction_rejected(reverse):
with pytest.raises(ValidationError):
StepCooking(reverse=reverse)
@@ -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()
+107
View File
@@ -0,0 +1,107 @@
from uuid import uuid4
import pytest
from pydantic import ValidationError
from mealie.schema.recipe.recipe import RecipeDraft
from mealie.schema.recipe.recipe_step import IngredientReferences, RecipeStep, StepCooking, StepParameter
@pytest.mark.parametrize("kind", ["remaining", "unknown", "prepared", "asNeeded", "referenceOnly"])
def test_non_numeric_allocations_never_expose_legacy_full_quantity(kind):
ref = IngredientReferences(quantity_kind=kind)
assert ref.quantity == 0
assert IngredientReferences.model_validate_json(ref.model_dump_json()).quantity_kind == kind
@pytest.mark.parametrize(
"payload",
[
{"quantityKind": "partial"},
{"quantityKind": "full", "quantity": 1},
{"quantityKind": "unknown", "quantity": 1},
{"quantityKind": "prepared", "weighing": "weigh"},
{"quantityMinimum": 10, "quantityMaximum": 2},
{"containerCount": 0},
],
)
def test_invalid_allocations_are_not_coerced(payload):
with pytest.raises(ValidationError):
IngredientReferences.model_validate(payload)
def test_optional_legacy_allocations_and_appliance_data():
step = RecipeStep(text="Hand mix", ingredient_references=[IngredientReferences()])
assert step.cooking is None
assert step.ingredient_references[0].quantity is None
assert step.ingredient_references[0].weighing is None
@pytest.mark.parametrize(
"payload",
[
{"durationRangeSeconds": {"minimum": 5, "maximum": 2}},
{"durationRangeSeconds": {"minimum": 0}},
{"durationRangeSeconds": {"minimum": 0.0001}},
{"speedRange": {"minimum": float("inf")}},
{"speedProgression": [1, float("nan")]},
{"repetitions": 1.5},
{"repetitions": True},
{"repetitionRange": {"minimum": 1.5}},
{"optional": "true"},
{"accessories": [{"name": "basket", "state": "guessed"}]},
],
)
def test_invalid_operation_settings_are_rejected(payload):
with pytest.raises(ValidationError):
StepCooking.model_validate(payload)
@pytest.mark.parametrize(
"payload",
[
{"kind": "number", "value": "2"},
{"kind": "number", "value": True},
{"kind": "boolean", "value": "false"},
{"kind": "text", "value": 2},
{"kind": "range", "value": 2},
{"kind": "range", "minimum": 5, "maximum": 2},
{"kind": "text", "minimum": 1},
],
)
def test_parameter_discriminator_is_validated(payload):
with pytest.raises(ValidationError):
StepParameter(name="setting", **payload)
def test_dependencies_are_declarative_and_cannot_form_cycles():
first, second = uuid4(), uuid4()
with pytest.raises(ValidationError, match="cycle"):
RecipeDraft(
recipe_instructions=[
RecipeStep(id=first, text="First", cooking=StepCooking(depends_on_step_ids=[second])),
RecipeStep(id=second, text="Second", cooking=StepCooking(depends_on_step_ids=[first])),
]
)
with pytest.raises(ValidationError, match="reference an instruction"):
RecipeDraft(recipe_instructions=[RecipeStep(text="Wait", cooking=StepCooking(depends_on_step_ids=[uuid4()]))])
def test_cooking_json_is_serializable_without_custom_database_encoders():
import json
from datetime import UTC, datetime
from mealie.schema.recipe.recipe_step import StepReview, StepReviewEvent
cooking = StepCooking(
depends_on_step_ids=[uuid4()],
reviews=[
StepReview(
category="operation",
history=[
StepReviewEvent(at=datetime.now(UTC), status="unresolved", content="Original content"),
],
),
],
)
assert StepCooking.model_validate(json.loads(json.dumps(cooking.model_dump()))) == cooking