feat: weekly meal planning (#8836)

This commit is contained in:
Michael Genson authored and GitHub committed 2026-10-27 13:48:42 +00:00
1 parent 6104e3aef7
commit 3a9d78ef43
34 files changed
+761 -250

No files matched your search

@@ -45,7 +45,23 @@
</v-btn>
</v-btn-toggle>
<MealPlanDatePicker v-model="selectedDate" :entry-type="entryType" />
<MealPlanDatePicker v-model="pickerModel" :multiple="pickerMultiple" :entry-type="entryType" />
<!-- the dates are part of the label, so they stay with the switch instead of floating above the next field -->
<v-switch
v-model="isWeekEntry"
color="primary"
hide-details
>
<template #label>
<div>
<div>{{ $t("meal-plan.plan-for-the-whole-week") }}</div>
<div v-if="isWeekEntry" class="text-caption text-medium-emphasis">
{{ $d(weekRange.start, "short") }} - {{ $d(weekRange.end, "short") }}
</div>
</div>
</template>
</v-switch>
<v-select
v-model="entryType"
@@ -137,10 +153,9 @@
</template>
<script setup lang="ts">
import { format } from "date-fns";
import RecipeScaleEditButton from "~/components/Domain/Recipe/RecipeScaleEditButton.vue";
import RecipeSelector from "~/components/Domain/Recipe/RecipeSelector.vue";
import { usePlanTypeOptions } from "~/composables/use-group-mealplan";
import { useMealPlanEntryDates, usePlanTypeOptions } from "~/composables/use-group-mealplan";
import { buildRuleQueryFilter, useMealplanRules } from "~/composables/use-mealplan-rules";
import { validators } from "~/composables/use-validators";
import type { CreatePlanEntry, PlanEntryType, ReadPlanEntry, UpdatePlanEntry } from "~/lib/api/types/meal-plan";
@@ -149,10 +164,13 @@ import type { RecipeSummary } from "~/lib/api/types/recipe";
interface Props {
entry?: ReadPlanEntry | null;
date?: Date | null;
/** Set when creating an entry for a week rather than a specific day */
endDate?: Date | null;
}
const props = withDefaults(defineProps<Props>(), {
entry: null,
date: null,
endDate: null,
});
const emit = defineEmits<{
@@ -168,7 +186,8 @@ const planTypeOptions = usePlanTypeOptions();
const selector = ref<InstanceType<typeof RecipeSelector> | null>(null);
const entryMode = ref<"recipe" | "note">("recipe");
const selectedDate = ref(new Date());
const { selectedDate, isWeekEntry, weekRange, entryDates, entryDatesPayload, pickerModel, pickerMultiple }
= useMealPlanEntryDates();
const entryType = ref<PlanEntryType>("dinner");
const recipe = ref<RecipeSummary | null>(null);
const recipeScale = ref(1);
@@ -178,7 +197,12 @@ const ignoreRules = ref(false);
const isRecipe = computed(() => entryMode.value === "recipe");
const applicableRuleFilter = computed(() => buildRuleQueryFilter(rules.value, selectedDate.value, entryType.value));
const applicableRuleFilter = computed(() => buildRuleQueryFilter(
rules.value,
entryDates.value.date,
entryType.value,
entryDates.value.endDate,
));
const ruleQueryFilter = computed(() => ignoreRules.value ? null : applicableRuleFilter.value);
const recipeServings = computed(() => recipe.value?.recipeServings || recipe.value?.recipeYieldQuantity || 1);
@@ -198,6 +222,7 @@ function parseEntryDate(date: string) {
function initialize() {
entryMode.value = props.entry && !props.entry.recipeId ? "note" : "recipe";
selectedDate.value = props.entry ? parseEntryDate(props.entry.date) : props.date ?? new Date();
isWeekEntry.value = props.entry ? !!props.entry.endDate : !!props.endDate;
entryType.value = props.entry?.entryType ?? "dinner";
recipe.value = props.entry?.recipe ?? null;
recipeScale.value = props.entry?.recipeScale ?? 1;
@@ -209,7 +234,7 @@ function initialize() {
function submit() {
const payload = {
date: format(selectedDate.value, "yyyy-MM-dd"),
...entryDatesPayload.value,
entryType: entryType.value,
title: isRecipe.value ? "" : title.value,
text: isRecipe.value ? "" : text.value,
@@ -13,6 +13,8 @@
v-model="day"
:items="MEAL_DAY_OPTIONS"
:label="$t('meal-plan.rule-day')"
:hint="day === 'unset' ? '' : $t('meal-plan.weekday-rules-skip-week-entries')"
persistent-hint
/>
<v-select
v-model="entryType"
@@ -9,7 +9,23 @@
@confirm="addRecipeToPlan"
>
<v-card-text>
<MealPlanDatePicker v-model="newMealdate" :entry-type="newMealType" />
<MealPlanDatePicker v-model="pickerModel" :multiple="pickerMultiple" :entry-type="newMealType" />
<!-- the dates are part of the label, so they stay with the switch instead of floating above the next field -->
<v-switch
v-model="isWeekEntry"
color="primary"
hide-details
class="mb-2"
>
<template #label>
<div>
<div>{{ $t("meal-plan.plan-for-the-whole-week") }}</div>
<div v-if="isWeekEntry" class="text-caption text-medium-emphasis">
{{ $d(weekRange.start, "short") }} - {{ $d(weekRange.end, "short") }}
</div>
</div>
</template>
</v-switch>
<v-select
v-model="newMealType"
:return-object="false"
@@ -24,6 +40,7 @@
<script setup lang="ts">
import { useUserApi } from "~/composables/api";
import { useMealPlanEntryDates } from "~/composables/use-group-mealplan";
import { alert } from "~/composables/use-toast";
import type { PlanEntryType } from "~/lib/api/types/meal-plan";
@@ -44,19 +61,11 @@ const planTypeOptions = usePlanTypeOptions();
const router = useRouter();
const newMealType = ref<PlanEntryType>("dinner");
const newMealdate = ref(new Date());
const newMealdateString = computed(() => {
// Format the date to YYYY-MM-DD in the same timezone as newMealdate
const year = newMealdate.value.getFullYear();
const month = String(newMealdate.value.getMonth() + 1).padStart(2, "0");
const day = String(newMealdate.value.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
});
const { isWeekEntry, weekRange, entryDatesPayload, pickerModel, pickerMultiple } = useMealPlanEntryDates();
async function addRecipeToPlan() {
const { response } = await api.mealplans.createOne({
date: newMealdateString.value,
...entryDatesPayload.value,
entryType: newMealType.value,
title: "",
text: "",
@@ -65,7 +65,8 @@ function updateYear(year: number) {
function hasMealPlanned(date: string): DatePickerEventColorValue {
const planned = mealplans.value ?? [];
const dateMatched = planned.filter(meal => meal.date === date);
// date range entries (e.g. a week) aren't on a specific day
const dateMatched = planned.filter(meal => meal.date === date && !meal.endDate);
const typeMatched = dateMatched.filter(meal => !props.entryType || meal.entryType === props.entryType);
const earlierDate = isDate(selectedDate.value) ? selectedDate.value : selectedDate.value?.[0];
const laterDate = isDate(selectedDate.value) ? selectedDate.value : selectedDate.value?.[1];
@@ -9,11 +9,12 @@
v-model="dialog.open"
:entry="dialog.entry"
:date="dialog.date"
:end-date="endDate"
@create="actions.createOne($event)"
@update="actions.updateOne($event)"
/>
<template v-if="inlineActions">
<MealPlanDayHeader :day="day" />
<MealPlanDayHeader :day="day" :end-date="endDate" />
<slot />
<!-- Day Column Actions -->
<div class="d-flex justify-end">
@@ -24,7 +25,7 @@
</div>
</template>
<template v-else>
<MealPlanDayHeader :day="day">
<MealPlanDayHeader :day="day" :end-date="endDate">
<BaseButtonGroup
v-bind="bindings"
:buttons="[{
@@ -33,7 +34,7 @@
text: '',
children: [
{
text: $t('meal-plan.add-day-to-list'),
text: endDate ? $t('meal-plan.add-week-to-list') : $t('meal-plan.add-day-to-list'),
icon: $globals.icons.cartCheck,
event: 'shopping-list',
loading: addAllLoading,
@@ -59,6 +60,8 @@ import type { PlanEntryType, ReadPlanEntry } from "~/lib/api/types/meal-plan";
interface Props {
recipes?: ScaledRecipe[];
day: Date;
/** Set for a week, whose meals aren't planned for a specific day */
endDate?: Date | null;
actions: ReturnType<typeof useMealplans>["actions"];
inlineActions?: boolean;
}
@@ -69,6 +72,7 @@ const i18n = useI18n();
const api = useUserApi();
const props = withDefaults(defineProps<Props>(), {
recipes: () => [],
endDate: null,
meal: () => ({}),
});
@@ -133,6 +137,7 @@ const inlineButtons = [
async function randomMeal(date: Date, type: PlanEntryType) {
const { data } = await api.mealplans.setRandom({
date: format(date, "yyyy-MM-dd"),
endDate: props.endDate ? format(props.endDate, "yyyy-MM-dd") : null,
entryType: type,
});
@@ -1,8 +1,16 @@
<template>
<v-card border="primary s-lg opacity-100" class="rounded-sm px-2" style="z-index: 2;">
<v-card
border="primary s-lg opacity-100"
class="rounded-sm px-2"
style="z-index: 2;"
:color="endDate ? 'primary' : undefined"
:variant="endDate ? 'tonal' : undefined"
>
<v-container class="px-0 d-flex align-center justify-space-between" height="56px">
<p :class="`pl-2 ${isToday(day) ? 'text-primary font-weight-bold' : ''}`">
{{ $d(day, "short") }}
<p :class="`pl-2 ${isCurrent ? 'text-primary font-weight-bold' : ''}`">
{{ $d(day, "short") }}<template v-if="endDate">
- {{ $d(endDate, "short") }}
</template>
</p>
<slot />
</v-container>
@@ -10,14 +18,19 @@
</template>
<script setup lang="ts">
import { isSameDay } from "date-fns";
import { endOfDay, isSameDay, isWithinInterval, startOfDay } from "date-fns";
interface Props {
day: Date;
/** Set for a week, whose meals aren't planned for a specific day */
endDate?: Date | null;
};
defineProps<Props>();
const props = defineProps<Props>();
const isToday = (date: Date) => {
return isSameDay(date, new Date());
};
const isCurrent = computed(() => {
const today = new Date();
return props.endDate
? isWithinInterval(today, { start: startOfDay(props.day), end: endOfDay(props.endDate) })
: isSameDay(props.day, today);
});
</script>
@@ -1,15 +1,12 @@
<template>
<v-row>
<!-- weeks span the full row, so each week's days start on a new row below it -->
<v-col
v-for="(plan, index) in mealplans"
:key="index"
cols="12"
sm="12"
md="12"
lg="6"
xl="4"
xxl="4"
v-bind="plan.endDate ? WEEK_COLS : DAY_COLS"
class="col-borders my-1 d-flex flex-column"
:class="{ 'week-section': plan.endDate, 'mt-6': plan.endDate && index > 0 }"
>
<slot v-bind="{ plan, index, day: getDay(plan) }" />
</v-col>
@@ -24,10 +21,14 @@ defineProps<{
}>();
const planTypeOptions = usePlanTypeOptions();
const DAY_COLS = { cols: 12, sm: 12, md: 12, lg: 6, xl: 4, xxl: 4 };
const WEEK_COLS = { cols: 12 };
function getDay(day: MealsByDate): Days {
const forSection = (key: PlanEntryType) => day.meals.filter(({ entryType }) => entryType === key);
return {
date: day.date,
endDate: day.endDate,
sections: planTypeOptions
.map(({ text, value }) => ({ title: text, meals: forSection(value) }))
.filter(({ meals }) => meals.length > 0),
@@ -35,3 +36,18 @@ function getDay(day: MealsByDate): Days {
};
}
</script>
<style scoped>
/* a light tint of the week header's color, so the whole week reads as one block apart from the days */
.week-section {
background-color: rgba(var(--v-theme-primary), 0.08);
border-radius: 4px;
}
/* a week spans the full row, so its meals are laid out side by side instead of in one long column */
:deep(.week-meals) {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
column-gap: 8px;
}
</style>
@@ -1,5 +1,5 @@
import { describe, expect, test, vi } from "vitest";
import { getScaledRecipes } from "../use-group-mealplan";
import { getScaledRecipes, getWeekRange } from "../use-group-mealplan";
import type { ReadPlanEntry } from "~/lib/api/types/meal-plan";
vi.mock("~/composables/api", () => ({
@@ -55,3 +55,16 @@ describe("getScaledRecipes", () => {
])).toEqual([]);
});
});
describe("getWeekRange", () => {
// 2026-08-19 is a Wednesday
const wednesday = new Date(2026, 7, 19);
test.each([
[0, new Date(2026, 7, 16), new Date(2026, 7, 22)],
[1, new Date(2026, 7, 17), new Date(2026, 7, 23)],
[4, new Date(2026, 7, 13), new Date(2026, 7, 19)],
])("starts the week on day %i", (firstDayOfWeek, start, end) => {
expect(getWeekRange(wednesday, firstDayOfWeek)).toEqual({ start, end });
});
});
@@ -64,6 +64,14 @@ describe("getApplicableRules", () => {
expect(getApplicableRules([otherDay, otherType], wednesday, "dinner")).toEqual([]);
});
test("skips weekday-specific rules for date range entries", () => {
const anyDay = createRule("unset", "dinner");
const sameDay = createRule("wednesday", "dinner");
const endDate = new Date(2026, 7, 25);
expect(getApplicableRules([anyDay, sameDay], wednesday, "dinner", endDate)).toEqual([anyDay]);
});
});
describe("buildRuleQueryFilter", () => {
+67 -3
View File
@@ -1,4 +1,6 @@
import { format } from "date-fns";
import { addDays, format, startOfWeek } from "date-fns";
import type { Day } from "date-fns";
import { useHouseholdSelf } from "./use-households";
import { useAsyncKey } from "./use-utils";
import { useUserApi } from "~/composables/api";
import type { CreatePlanEntry, PlanEntryType, ReadPlanEntry, RecipeSummary, UpdatePlanEntry } from "~/lib/api/types/meal-plan";
@@ -29,6 +31,56 @@ export interface DateRange {
start: Date;
end: Date;
}
/**
* The week containing `date`, used as the `date` and `endDate` of a meal plan entry planned for that week.
* `firstDayOfWeek` is the household preference (0 is Sunday).
*/
export function getWeekRange(date: Date, firstDayOfWeek: number): DateRange {
const start = startOfWeek(date, { weekStartsOn: firstDayOfWeek as Day });
return { start, end: addDays(start, 6) };
}
/**
* Date state for a meal plan entry form: either the selected day, or the week containing it.
*/
export function useMealPlanEntryDates() {
const { household } = useHouseholdSelf();
const selectedDate = ref(new Date());
const isWeekEntry = ref(false);
const weekRange = computed(() => getWeekRange(selectedDate.value, household.value?.preferences?.firstDayOfWeek || 0));
const entryDates = computed(() => isWeekEntry.value
? { date: weekRange.value.start, endDate: weekRange.value.end }
: { date: selectedDate.value, endDate: null },
);
/** `date` and `endDate` formatted for the API */
const entryDatesPayload = computed(() => ({
date: format(entryDates.value.date, "yyyy-MM-dd"),
endDate: entryDates.value.endDate ? format(entryDates.value.endDate, "yyyy-MM-dd") : null,
}));
/**
* `v-model` for `MealPlanDatePicker`, used with `pickerMultiple`. For a week entry it's the whole week, so the
* picker highlights it as a range. Clicking a day in range mode replaces the range with just that day, which
* selects the week containing it.
*/
const pickerModel = computed<Date | [Date, Date]>({
get: () => isWeekEntry.value ? [weekRange.value.start, weekRange.value.end] : selectedDate.value,
set: (value) => {
const date = Array.isArray(value) ? value[0] : value;
if (date) {
selectedDate.value = date;
}
},
});
const pickerMultiple = computed(() => isWeekEntry.value ? "range" as const : false);
return { selectedDate, isWeekEntry, weekRange, entryDates, entryDatesPayload, pickerModel, pickerMultiple };
}
export type DaySection = {
title: string;
meals: ReadPlanEntry[];
@@ -38,6 +90,8 @@ export type ScaledRecipe = RecipeSummary & { scale: number };
export type Days = {
date: Date;
/** Set for a week, whose meals aren't planned for a specific day */
endDate?: Date | null;
sections: DaySection[];
recipes: ScaledRecipe[];
};
@@ -52,6 +106,8 @@ export function getScaledRecipes(meals: ReadPlanEntry[]): ScaledRecipe[] {
export type MealsByDate = {
date: Date;
/** Set for a week, whose meals aren't planned for a specific day */
endDate?: Date | null;
meals: ReadPlanEntry[];
};
@@ -81,7 +137,11 @@ export const useMealplans = function (range: Ref<DateRange>) {
start_date: format(range.value.start, "yyyy-MM-dd"),
end_date: format(range.value.end, "yyyy-MM-dd"),
};
const { data } = await api.mealplans.getAll(1, -1, { start_date: query.start_date, end_date: query.end_date });
const { data } = await api.mealplans.getAll(1, -1, {
start_date: query.start_date,
end_date: query.end_date,
include_week_entries: true,
});
if (data) {
return data.items;
@@ -100,7 +160,11 @@ export const useMealplans = function (range: Ref<DateRange>) {
start_date: format(range.value.start, "yyyy-MM-dd"),
end_date: format(range.value.end, "yyyy-MM-dd"),
};
const { data } = await api.mealplans.getAll(1, -1, { start_date: query.start_date, end_date: query.end_date });
const { data } = await api.mealplans.getAll(1, -1, {
start_date: query.start_date,
end_date: query.end_date,
include_week_entries: true,
});
if (data && data.items) {
mealplans.value = data.items;
+12 -2
View File
@@ -15,12 +15,21 @@ export function getDayOfWeek(date: Date): PlanRulesDay {
return DAYS_OF_WEEK[date.getDay()] ?? "unset";
}
/**
* The rules that apply to a meal plan entry: rules for its weekday, plus rules that apply to all days.
*
* Entries with an `endDate` span a date range (e.g. a week) rather than falling on a specific weekday,
* so they're looked up as day "unset", which only matches rules that apply to all days. Applying every
* weekday's rule to them would combine unrelated rules into one overly strict filter.
* This mirrors the server's rule lookup.
*/
export function getApplicableRules(
rules: PlanRulesOut[],
date: Date,
entryType: PlanEntryType,
endDate: Date | null = null,
): PlanRulesOut[] {
const day = getDayOfWeek(date);
const day: PlanRulesDay = endDate ? "unset" : getDayOfWeek(date);
return rules.filter((rule) => {
const dayMatches = !rule.day || rule.day === "unset" || rule.day === day;
@@ -33,8 +42,9 @@ export function buildRuleQueryFilter(
rules: PlanRulesOut[],
date: Date,
entryType: PlanEntryType,
endDate: Date | null = null,
): string | null {
const queryFilters = getApplicableRules(rules, date, entryType)
const queryFilters = getApplicableRules(rules, date, entryType, endDate)
.map(rule => rule.queryFilterString)
.filter(queryFilterString => !!queryFilterString)
.map(queryFilterString => `(${queryFilterString})`);
@@ -24,8 +24,9 @@ export enum ImagePosition {
}
export interface UserMealPlanPreferences {
numberOfDaysPast: number;
numberOfDays: number;
numberOfWeeksPast: number;
/** Includes the current week */
numberOfWeeks: number;
}
export interface UserRecipePreferences {
@@ -87,8 +88,8 @@ export function useUserMealPlanPreferences(): Ref<UserMealPlanPreferences> {
const fromStorage = useLocalStorage(
"meal-planner-preferences",
{
numberOfDaysPast: 0,
numberOfDays: 7,
numberOfWeeksPast: 0,
numberOfWeeks: 1,
},
{ mergeDefaults: true },
);
+8 -4
View File
@@ -330,10 +330,10 @@
"any-category": "Any Category",
"any-tag": "Any Tag",
"any-household": "Any Household",
"numberOfDaysPast-hint": "Number of days in the past on page load",
"numberOfDaysPast-label": "Default Days in the Past",
"numberOfDays-hint": "Number of days on page load",
"numberOfDays-label": "Default Days",
"numberOfWeeksPast-hint": "Number of weeks in the past on page load",
"numberOfWeeksPast-label": "Default Weeks in the Past",
"numberOfWeeks-hint": "Number of weeks on page load, including the current week",
"numberOfWeeks-label": "Default Weeks",
"side": "Side",
"rule-day": "Rule Day",
"meal-type": "Meal Type",
@@ -349,6 +349,9 @@
"meal-note": "Meal Note",
"note": "Note",
"ignore-rules": "Ignore Planner Rules",
"plan-for-the-whole-week": "Plan for the whole week",
"cooking-it-today": "Cooking It Today",
"weekday-rules-skip-week-entries": "Rules for a specific day don't apply to meals planned for a whole week.",
"no-recipes-match-your-rules": "No recipes match your meal plan rules",
"random-meal": "Random Meal",
"random-dinner": "Random Dinner",
@@ -368,6 +371,7 @@
"meal-plan-settings": "Meal Plan Settings",
"add-all-to-list": "Add All to List",
"add-day-to-list": "Add Day to List",
"add-week-to-list": "Add Week to List",
"randomize-recipe": "Randomize Recipe",
"calendar-feed": "Subscribe to Calendar",
"calendar-feed-description": "Subscribe to your household's meal plan from Google Calendar, Apple Calendar, Home Assistant or any other app that supports iCal links. Anyone with the link can see your meal plan.",
+5
View File
@@ -14,6 +14,7 @@ export type RelationalOperator = "=" | "<>" | ">" | "<" | ">=" | "<=";
export interface CreatePlanEntry {
date: string;
endDate?: string | null;
entryType?: PlanEntryType;
title?: string;
text?: string;
@@ -22,6 +23,7 @@ export interface CreatePlanEntry {
}
export interface CreateRandomEntry {
date: string;
endDate?: string | null;
entryType?: PlanEntryType;
}
export interface ListItem {
@@ -69,6 +71,7 @@ export interface ReadMealPlanICalToken {
}
export interface ReadPlanEntry {
date: string;
endDate?: string | null;
entryType?: PlanEntryType;
title?: string;
text?: string;
@@ -133,6 +136,7 @@ export interface RecipeTool {
}
export interface SavePlanEntry {
date: string;
endDate?: string | null;
entryType?: PlanEntryType;
title?: string;
text?: string;
@@ -154,6 +158,7 @@ export interface ShoppingListOut {
}
export interface UpdatePlanEntry {
date: string;
endDate?: string | null;
entryType?: PlanEntryType;
title?: string;
text?: string;
+61 -61
View File
@@ -343,6 +343,13 @@ export interface RecipeIngredientSubstitution {
note?: string | null;
substituteFood?: IngredientFoodSummary | null;
}
export interface RecipeCategoryIn {
id?: string | null;
groupId?: string | null;
name: string;
slug?: string | null;
recipeCount?: number;
}
export interface RecipeCategoryResponse {
name: string;
id: string;
@@ -395,6 +402,60 @@ export interface RecipeCommentUpdate {
export interface RecipeDuplicate {
name?: string | null;
}
export interface RecipeIn {
id?: string | null;
userId?: string;
householdId?: string;
groupId?: string;
name?: string | null;
slug?: string;
image?: unknown;
recipeServings?: number;
recipeYieldQuantity?: number;
recipeYield?: string | null;
totalTime?: string | null;
prepTime?: string | null;
cookTime?: string | null;
performTime?: string | null;
totalTimeSeconds?: number | null;
prepTimeSeconds?: number | null;
performTimeSeconds?: number | null;
description?: string | null;
recipeCategory?: RecipeCategoryIn[] | null;
tags?: RecipeTagIn[] | null;
tools?: RecipeToolIn[];
rating?: number | null;
orgURL?: string | null;
dateAdded?: string | null;
dateUpdated?: string | null;
createdAt?: string | null;
updatedAt?: string | null;
recipeIngredient?: RecipeIngredient[];
recipeInstructions?: RecipeStep[] | null;
nutrition?: Nutrition | null;
settings?: RecipeSettings | null;
assets?: RecipeAsset[] | null;
notes?: RecipeNote[] | null;
extras?: {
[k: string]: unknown;
} | null;
comments?: RecipeCommentOut[] | null;
}
export interface RecipeTagIn {
id?: string | null;
groupId?: string | null;
name: string;
slug?: string | null;
recipeCount?: number;
}
export interface RecipeToolIn {
id?: string | null;
groupId?: string | null;
name: string;
slug?: string | null;
recipeCount?: number;
householdsWithTool?: string[];
}
export interface RecipeIngredientBase {
quantity?: number | null;
unit?: IngredientUnit | CreateIngredientUnit | null;
@@ -624,67 +685,6 @@ export interface UnitFoodBase {
export interface UpdateImageResponse {
image: string;
}
export interface RecipeCategoryIn {
id?: string | null;
groupId?: string | null;
name: string;
slug?: string | null;
recipeCount?: number;
}
export interface RecipeIn {
id?: string | null;
userId?: string;
householdId?: string;
groupId?: string;
name?: string | null;
slug?: string;
image?: unknown;
recipeServings?: number;
recipeYieldQuantity?: number;
recipeYield?: string | null;
totalTime?: string | null;
prepTime?: string | null;
cookTime?: string | null;
performTime?: string | null;
totalTimeSeconds?: number | null;
prepTimeSeconds?: number | null;
performTimeSeconds?: number | null;
description?: string | null;
recipeCategory?: RecipeCategoryIn[] | null;
tags?: RecipeTagIn[] | null;
tools?: RecipeToolIn[];
rating?: number | null;
orgURL?: string | null;
dateAdded?: string | null;
dateUpdated?: string | null;
createdAt?: string | null;
updatedAt?: string | null;
recipeIngredient?: RecipeIngredient[];
recipeInstructions?: RecipeStep[] | null;
nutrition?: Nutrition | null;
settings?: RecipeSettings | null;
assets?: RecipeAsset[] | null;
notes?: RecipeNote[] | null;
extras?: {
[k: string]: unknown;
} | null;
comments?: RecipeCommentOut[] | null;
}
export interface RecipeTagIn {
id?: string | null;
groupId?: string | null;
name: string;
slug?: string | null;
recipeCount?: number;
}
export interface RecipeToolIn {
id?: string | null;
groupId?: string | null;
name: string;
slug?: string | null;
recipeCount?: number;
householdsWithTool?: string[];
}
export interface RequestQuery {
orderBy?: string | null;
orderByNullPosition?: OrderByNullPosition | null;
@@ -8,7 +8,8 @@
@list-created="addShoppingList"
/>
<GroupMealPlanCalendarDialog v-model="calendarDialog" />
<div :class="`d-flex ga-2 ${$vuetify.display.xs ? 'justify-center' : 'justify-start'}`">
<!-- range navigation and page actions share one toolbar, kept apart from the plan below -->
<div class="d-flex flex-wrap align-center ga-2">
<v-btn :icon="$globals.icons.chevronLeft" flat rounded="md" density="comfortable" @click="() => changeWeek(-1)" />
<v-menu
v-model="state.picker"
@@ -20,7 +21,6 @@
<template #activator="{ props }">
<v-btn
color="primary"
class="mb-2"
v-bind="props"
>
<v-icon start>
@@ -41,32 +41,30 @@
<v-card-text>
<v-number-input
v-model="numberOfDaysPast"
v-model="numberOfWeeksPast"
:min="0"
inset
:label="$t('meal-plan.numberOfDaysPast-label')"
:hint="$t('meal-plan.numberOfDaysPast-hint')"
:label="$t('meal-plan.numberOfWeeksPast-label')"
:hint="$t('meal-plan.numberOfWeeksPast-hint')"
persistent-hint
/>
</v-card-text>
<v-card-text>
<v-number-input
v-model="numberOfDays"
v-model="numberOfWeeks"
:min="1"
inset
:label="$t('meal-plan.numberOfDays-label')"
:hint="$t('meal-plan.numberOfDays-hint')"
:label="$t('meal-plan.numberOfWeeks-label')"
:hint="$t('meal-plan.numberOfWeeks-hint')"
persistent-hint
/>
</v-card-text>
</v-card>
</v-menu>
<v-btn :icon="$globals.icons.chevronRight" flat rounded="md" density="comfortable" @click="() => changeWeek(1)" />
</div>
<div class="d-flex justify-end">
<BaseButtonGroup
class="d-flex"
class="d-flex ms-auto"
:buttons="[
edit ? {
icon: $globals.icons.calendar,
@@ -108,9 +106,10 @@
@calendar-feed="calendarDialog = true"
/>
</div>
<v-divider class="my-4" />
<div>
<NuxtPage
:mealplans="mealsByDate"
:mealplans="plans"
:actions="actions"
/>
</div>
@@ -120,11 +119,12 @@
</template>
<script setup lang="ts">
import { addDays, differenceInCalendarDays, format, isSameDay, isValid, parseISO } from "date-fns";
import { addDays, addWeeks, differenceInCalendarDays, format, isSameDay, isValid, parseISO } from "date-fns";
import GroupMealPlanCalendarDialog from "~/components/Domain/Household/GroupMealPlanCalendarDialog.vue";
import RecipeDialogAddToShoppingList from "~/components/Domain/Recipe/RecipeDialogAddToShoppingList.vue";
import { useAddToShoppingListDialog } from "~/composables/shopping-list-page/use-add-to-shopping-list-dialog";
import { getScaledRecipes, useMealplans } from "~/composables/use-group-mealplan";
import type { MealsByDate } from "~/composables/use-group-mealplan";
import { getScaledRecipes, getWeekRange, useMealplans } from "~/composables/use-group-mealplan";
import { useHouseholdSelf } from "~/composables/use-households";
import { useUserMealPlanPreferences } from "~/composables/use-users/preferences";
@@ -157,13 +157,13 @@ onMounted(() => {
});
const mealPlanPreferences = useUserMealPlanPreferences();
const numberOfDaysPast = ref<number>(mealPlanPreferences.value.numberOfDaysPast || 0);
const numberOfDays = ref<number>(mealPlanPreferences.value.numberOfDays || 7);
watch(numberOfDaysPast, (val) => {
mealPlanPreferences.value.numberOfDaysPast = Number(val);
const numberOfWeeksPast = ref<number>(mealPlanPreferences.value.numberOfWeeksPast || 0);
const numberOfWeeks = ref<number>(mealPlanPreferences.value.numberOfWeeks || 1);
watch(numberOfWeeksPast, (val) => {
mealPlanPreferences.value.numberOfWeeksPast = Number(val);
});
watch(numberOfDays, (val) => {
mealPlanPreferences.value.numberOfDays = Number(val);
watch(numberOfWeeks, (val) => {
mealPlanPreferences.value.numberOfWeeks = Number(val);
});
// Force to /view if current route is /planner
@@ -188,9 +188,18 @@ function safeParseISO(date: string, fallback: Date | undefined = undefined) {
}
}
// A day in the first and last week of the default range; `weekRange` rounds them out to whole weeks
function defaultStartDate() {
return addWeeks(new Date(), -numberOfWeeksPast.value);
}
function defaultEndDate() {
return addWeeks(new Date(), numberOfWeeks.value - 1);
}
// Initialize dates from query parameters or defaults
const initialStartDate = safeParseISO(route.query.start as string, addDays(new Date(), adjustForToday(-numberOfDaysPast.value)));
const initialEndDate = safeParseISO(route.query.end as string, addDays(new Date(), adjustForToday(numberOfDays.value)));
const initialStartDate = safeParseISO(route.query.start as string, defaultStartDate());
const initialEndDate = safeParseISO(route.query.end as string, defaultEndDate());
const state = ref({
range: [initialStartDate, initialEndDate] as [Date, Date],
@@ -212,21 +221,28 @@ function changeWeek(step: number) {
];
}
// The planner always shows whole weeks, so the selected range is rounded out to the weeks it touches
const weekRange = computed(() => {
const sorted = [...state.value.range].sort((a, b) => a.getTime() - b.getTime());
const start = sorted[0];
const end = sorted[sorted.length - 1];
const start = sorted[0] ?? defaultStartDate();
const end = sorted[sorted.length - 1] ?? defaultEndDate();
if (start && end) {
return { start, end };
}
return {
start: addDays(new Date(), adjustForToday(-numberOfDaysPast.value)),
end: addDays(new Date(), adjustForToday(numberOfDays.value)),
start: getWeekRange(start, firstDayOfWeek.value).start,
end: getWeekRange(end, firstDayOfWeek.value).end,
};
});
// Once a range is fully picked, show the whole weeks in the picker too. A half-picked range (one date)
// is left alone, so the picker can still take the second click.
watch(weekRange, ({ start, end }) => {
const [first, last] = state.value.range;
if (state.value.range.length === 2 && !(first && last && isSameDay(first, start) && isSameDay(last, end))) {
state.value.range = [start, end];
}
});
// Update query parameters when date range changes
watch(weekRange, (newRange) => {
// Keep current route name and params, just update the query
@@ -246,17 +262,14 @@ const { mealplans, actions } = useMealplans(weekRange);
function filterMealByDate(date: Date) {
if (!mealplans.value) return [];
return mealplans.value.filter((meal) => {
// week entries aren't planned for a specific day
if (meal.endDate) return false;
const mealDate = parseISO(meal.date);
return isSameDay(mealDate, date);
});
}
function adjustForToday(days: number) {
// e.g. If the user wants 7 days, we subtract one to do "today + 6"
// e.g. If the user wants 2 days in the past, we keep it the same to do "today - 2"
return days > 0 ? days - 1 : days;
}
const days = computed(() => {
const numDays
= Math.floor((weekRange.value.end.getTime() - weekRange.value.start.getTime()) / (1000 * 60 * 60 * 24)) + 1;
@@ -279,11 +292,45 @@ const mealsByDate = computed(() => {
});
});
/**
* The visible days grouped by week, each with that week's entries, so meals can be planned for any visible week.
* Week entries are grouped by their own dates rather than the current weeks, so they still show up (as a week
* without days) if the household's first day of the week has changed since they were planned.
*/
const mealsByWeek = computed(() => {
const weeks = new Map<string, { week: MealsByDate; days: MealsByDate[] }>();
const getWeek = (start: Date, end: Date) => {
const key = format(start, "yyyy-MM-dd");
if (!weeks.has(key)) {
weeks.set(key, { week: { date: start, endDate: end, meals: [] }, days: [] });
}
return weeks.get(key)!;
};
for (const day of mealsByDate.value) {
const { start, end } = getWeekRange(day.date, firstDayOfWeek.value);
getWeek(start, end).days.push(day);
}
for (const meal of mealplans.value ?? []) {
if (meal.endDate) {
getWeek(parseISO(meal.date), parseISO(meal.endDate)).week.meals.push(meal);
}
}
return [...weeks.values()].sort((a, b) => a.week.date.getTime() - b.week.date.getTime());
});
/** Each week followed by its days, the order the planner pages lay them out in */
const plans = computed(() => mealsByWeek.value.flatMap(({ week, days }) => [week, ...days]));
const allMeals = computed(() => plans.value.flatMap(({ meals }) => meals));
const hasRecipes = computed(() => {
return mealsByDate.value.some(day => day.meals.some(meal => meal.recipe));
return allMeals.value.some(meal => meal.recipe);
});
const weekRecipesWithScales = computed(() => {
return getScaledRecipes(mealsByDate.value.flatMap(({ meals }) => meals));
return getScaledRecipes(allMeals.value);
});
</script>
@@ -9,9 +9,9 @@
/>
<MealPlanLayout :mealplans="mealplans">
<template #default="{ plan, index, day }">
<MealPlanDay :day="day.date" :recipes="day.recipes" :actions="actions" inline-actions>
<MealPlanDay :day="day.date" :end-date="day.endDate" :recipes="day.recipes" :actions="actions" inline-actions>
<VueDraggable
v-model="mealplansByDate[plan.date.toString()]!"
v-model="mealplansByDate[planKey(plan)]!"
tag="div"
handle=".handle"
:delay="250"
@@ -19,12 +19,13 @@
group="meals"
:data-index="index"
:data-box="plan.date"
style="min-height: 150px"
:class="{ 'week-meals': plan.endDate }"
:style="{ minHeight: plan.endDate ? '48px' : '150px' }"
@end="onMoveCallback"
>
<SpinTransition>
<v-card
v-for="mealplan in mealplansByDate[plan.date.toString()]"
v-for="mealplan in mealplansByDate[planKey(plan)]"
:key="mealplan.id"
class="my-2 ml-4 mr-1"
:class="{ handle: $vuetify.display.smAndUp }"
@@ -140,18 +141,23 @@ const props = defineProps<{
const api = useUserApi();
const planTypeOptions = usePlanTypeOptions();
// a week and the day it starts on share a date, so weeks get their own keys
function planKey(plan: MealsByDate) {
return `${plan.endDate ? "week-" : ""}${plan.date.toString()}`;
}
// Local mutable meals object
const mealplansByDate = reactive<{ [date: string]: ReadPlanEntry[] }>({});
const mealplansByDate = reactive<{ [key: string]: ReadPlanEntry[] }>({});
watch(
() => props.mealplans,
(plans) => {
for (const plan of plans) {
mealplansByDate[plan.date.toString()] = plan.meals ? [...plan.meals] : [];
mealplansByDate[planKey(plan)] = plan.meals ? [...plan.meals] : [];
}
// Remove any dates that no longer exist
Object.keys(mealplansByDate).forEach((date) => {
if (!plans.find(p => p.date.toString() === date)) {
mealplansByDate[date] = [];
Object.keys(mealplansByDate).forEach((key) => {
if (!plans.find(p => planKey(p) === key)) {
mealplansByDate[key] = [];
}
});
},
@@ -164,10 +170,12 @@ function onMoveCallback(evt: SortableEvent) {
const toMealsByIndex = parseInt(evt.to.getAttribute("data-index") ?? "");
if (!isNaN(fromMealsByIndex) && !isNaN(toMealsByIndex)) {
const destDate = props.mealplans[toMealsByIndex].date;
const mealData = mealplansByDate[destDate.toString()][evt.newIndex as number];
const dest = props.mealplans[toMealsByIndex];
const mealData = mealplansByDate[planKey(dest)][evt.newIndex as number];
mealData.date = format(destDate, "yyyy-MM-dd");
// moving between a week and a day schedules or unschedules the meal
mealData.date = format(dest.date, "yyyy-MM-dd");
mealData.endDate = dest.endDate ? format(dest.endDate, "yyyy-MM-dd") : null;
props.actions.updateOne(mealData);
}
@@ -198,6 +206,7 @@ async function randomizeMeal(mealplan: ReadPlanEntry) {
// Create the new random entry first, so a failure here doesn't lose the current entry
const { data: created } = await api.mealplans.setRandom({
date: mealplan.date,
endDate: mealplan.endDate,
entryType: mealplan.entryType,
});
@@ -9,9 +9,14 @@
/>
<MealPlanLayout :mealplans="mealplans">
<template #default="{ day }">
<MealPlanDay :day="day.date" :actions="actions" :recipes="day.recipes">
<MealPlanDay :day="day.date" :end-date="day.endDate" :actions="actions" :recipes="day.recipes">
<SpinTransition>
<v-card v-if="day.sections.length" variant="flat" class="pl-4 pr-2">
<v-card
v-if="day.sections.length"
variant="flat"
class="pl-4 pr-2"
:color="day.endDate ? 'transparent' : undefined"
>
<SpinTransition>
<div v-for="section in day.sections" :key="section.title">
<div class="py-2 d-flex flex-column">
@@ -19,52 +24,63 @@
{{ section.title }}
</p>
</div>
<SpinTransition>
<div
v-for="mealplan in section.meals"
:key="mealplan.id"
class="mb-2"
>
<RecipeCardMobile
:recipe-id="mealplan.recipe ? mealplan.recipe.id! : ''"
:scale="mealplan.recipeScale ?? 1"
:rating="mealplan.recipe ? mealplan.recipe.rating! : 0"
:slug="mealplan.recipe ? mealplan.recipe.slug! : mealplan.title!"
:description="mealplan.recipe ? mealplan.recipe.description! : mealplan.text!"
:name="mealplan.recipe ? mealplan.recipe.name! : mealplan.title!"
:image="mealplan.recipe ? mealplan.recipe.image! : undefined"
:tags="mealplan.recipe ? mealplan.recipe.tags! : []"
:context-menu-leading-items="[
{
title: $t('meal-plan.remove-from-plan'),
icon: $globals.icons.calendarRemove,
color: undefined,
event: 'mealplanRemove',
isPublic: false,
},
{
title: $t('meal-plan.edit-meal-plan'),
icon: $globals.icons.calendarEdit,
color: undefined,
event: 'mealplanEdit',
isPublic: false,
},
]"
@mealplan-remove="actions.deleteOne(mealplan.id)"
@mealplan-edit="editMeal(mealplan)"
<div :class="{ 'week-meals': day.endDate }">
<SpinTransition>
<div
v-for="mealplan in section.meals"
:key="mealplan.id"
class="mb-2"
>
<template v-if="!mealplan.recipe" #context-menu>
<MealPlanNoteMenu
@mealplan-remove="actions.deleteOne(mealplan.id)"
@mealplan-edit="editMeal(mealplan)"
/>
</template>
</RecipeCardMobile>
<div v-if="mealplan.recipe" class="d-flex justify-end pt-1">
<MealPlanScaleControl :meal="mealplan" :actions="actions" />
<RecipeCardMobile
:recipe-id="mealplan.recipe ? mealplan.recipe.id! : ''"
:scale="mealplan.recipeScale ?? 1"
:rating="mealplan.recipe ? mealplan.recipe.rating! : 0"
:slug="mealplan.recipe ? mealplan.recipe.slug! : mealplan.title!"
:description="mealplan.recipe ? mealplan.recipe.description! : mealplan.text!"
:name="mealplan.recipe ? mealplan.recipe.name! : mealplan.title!"
:image="mealplan.recipe ? mealplan.recipe.image! : undefined"
:tags="mealplan.recipe ? mealplan.recipe.tags! : []"
:context-menu-leading-items="[
{
title: $t('meal-plan.remove-from-plan'),
icon: $globals.icons.calendarRemove,
color: undefined,
event: 'mealplanRemove',
isPublic: false,
},
{
title: $t('meal-plan.edit-meal-plan'),
icon: $globals.icons.calendarEdit,
color: undefined,
event: 'mealplanEdit',
isPublic: false,
},
]"
@mealplan-remove="actions.deleteOne(mealplan.id)"
@mealplan-edit="editMeal(mealplan)"
>
<template v-if="!mealplan.recipe" #context-menu>
<MealPlanNoteMenu
@mealplan-remove="actions.deleteOne(mealplan.id)"
@mealplan-edit="editMeal(mealplan)"
/>
</template>
</RecipeCardMobile>
<div v-if="mealplan.recipe || mealplan.endDate" class="d-flex flex-wrap align-center ga-2 pt-1">
<v-btn
v-if="mealplan.endDate"
color="primary"
density="comfortable"
:prepend-icon="$globals.icons.potSteam"
@click="cookToday(mealplan)"
>
{{ $t("meal-plan.cooking-it-today") }}
</v-btn>
<MealPlanScaleControl v-if="mealplan.recipe" class="ms-auto flex-shrink-0" :meal="mealplan" :actions="actions" />
</div>
</div>
</div>
</SpinTransition>
</SpinTransition>
</div>
</div>
</SpinTransition>
</v-card>
@@ -76,13 +92,14 @@
</template>
<script setup lang="ts">
import { format } from "date-fns";
import MealPlanNoteMenu from "~/components/Domain/Mealplan/MealPlanNoteMenu.vue";
import MealPlanScaleControl from "~/components/Domain/Mealplan/MealPlanScaleControl.vue";
import RecipeCardMobile from "~/components/Domain/Recipe/RecipeCardMobile.vue";
import type { MealsByDate } from "~/composables/use-group-mealplan";
import type { ReadPlanEntry } from "~/lib/api/types/meal-plan";
defineProps<{
const props = defineProps<{
mealplans: MealsByDate[];
actions: ReturnType<typeof useMealplans>["actions"];
}>();
@@ -100,6 +117,11 @@ function editMeal(mealplan: ReadPlanEntry) {
dialog.date = null;
dialog.open = true;
}
/** Moves a week entry onto today, so it's treated like any other meal made today */
function cookToday(mealplan: ReadPlanEntry) {
props.actions.updateOne({ ...mealplan, date: format(new Date(), "yyyy-MM-dd"), endDate: null });
}
</script>
<style scoped>
@@ -0,0 +1,35 @@
"""'add end_date to group meal plans'
Revision ID: a9f823e9e441
Revises: afdc42353aa4
Create Date: 2026-10-22 17:35:44.318420
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "a9f823e9e441"
down_revision: str | None = "afdc42353aa4"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("group_meal_plans", schema=None) as batch_op:
batch_op.add_column(sa.Column("end_date", sa.Date(), nullable=True))
batch_op.create_index(batch_op.f("ix_group_meal_plans_end_date"), ["end_date"], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("group_meal_plans", schema=None) as batch_op:
batch_op.drop_index(batch_op.f("ix_group_meal_plans_end_date"))
batch_op.drop_column("end_date")
# ### end Alembic commands ###
+1
View File
@@ -56,6 +56,7 @@ class GroupMealPlan(SqlAlchemyBase, BaseMixins):
__tablename__ = "group_meal_plans"
date: FilterableColumn[datetime.date] = mapped_column(Date, index=True, nullable=False)
end_date: FilterableColumn[datetime.date | None] = mapped_column(Date, index=True, nullable=True)
entry_type: FilterableColumn[str] = mapped_column(String, index=True, nullable=False)
title: FilterableColumn[str] = mapped_column(String, index=True, nullable=False)
text: FilterableColumn[str] = mapped_column(String, nullable=False)
+4 -1
View File
@@ -124,7 +124,10 @@
"test-message-body": "This is a test notification from Mealie.",
"mealplan-entry-created": "Meal plan entry created for {date} for {entry_type}",
"mealplan-entry-updated": "Meal plan entry updated for {date} for {entry_type}",
"mealplan-entry-deleted": "Meal plan entry deleted for {date} for {entry_type}"
"mealplan-entry-deleted": "Meal plan entry deleted for {date} for {entry_type}",
"mealplan-range-entry-created": "Meal plan entry created for {date} to {end_date} for {entry_type}",
"mealplan-range-entry-updated": "Meal plan entry updated for {date} to {end_date} for {entry_type}",
"mealplan-range-entry-deleted": "Meal plan entry deleted for {date} to {end_date} for {entry_type}"
},
"datetime": {
"year": "year|years",
@@ -8,6 +8,16 @@ from .repository_generic import HouseholdRepositoryGeneric
class RepositoryMealPlanRules(HouseholdRepositoryGeneric[PlanRulesOut, GroupMealPlanRules]):
def get_rules(self, day: PlanRulesDay, entry_type: PlanRulesType) -> list[PlanRulesOut]:
"""
Returns the rules that apply to a meal plan entry on `day` with `entry_type`: rules for that day,
plus rules that apply to all days.
Pass `PlanRulesDay.unset` for entries that span a date range (e.g. a week) rather than falling on a
specific weekday. Since `unset` only matches rules that apply to all days, weekday-specific rules
are skipped; applying every weekday's rule to such an entry would combine unrelated rules into one
overly strict filter.
"""
stmt = select(GroupMealPlanRules).filter(
or_(
GroupMealPlanRules.day == day,
+4 -1
View File
@@ -15,7 +15,9 @@ class RepositoryMeals(HouseholdRepositoryGeneric[ReadPlanEntry, GroupMealPlan]):
today = datetime.now(tz=tz).date()
stmt = select(GroupMealPlan).filter(
GroupMealPlan.date == today, GroupMealPlan.household_id == self.household_id
GroupMealPlan.date == today,
GroupMealPlan.end_date.is_(None), # week entries aren't planned for a specific day
GroupMealPlan.household_id == self.household_id,
)
plans = self.session.execute(stmt).scalars().all()
return [self.schema.model_validate(x) for x in plans]
@@ -27,6 +29,7 @@ class RepositoryMeals(HouseholdRepositoryGeneric[ReadPlanEntry, GroupMealPlan]):
stmt = select(GroupMealPlan).filter(
GroupMealPlan.date >= start_date.date(),
GroupMealPlan.date <= end_date.date(),
GroupMealPlan.end_date.is_(None), # week entries aren't planned for a specific day
GroupMealPlan.household_id == self.household_id,
)
plans = self.session.execute(stmt).scalars().all()
+42 -33
View File
@@ -26,6 +26,13 @@ from mealie.services.query_filter.builder import QueryFilterBuilder
router = APIRouter(prefix="/households/mealplans", tags=["Households: Meal Plans"])
MEALPLAN_NOTIFICATION_KEYS: dict[EventOperation, tuple[str, str]] = {
EventOperation.create: ("notifications.mealplan-entry-created", "notifications.mealplan-range-entry-created"),
EventOperation.update: ("notifications.mealplan-entry-updated", "notifications.mealplan-range-entry-updated"),
EventOperation.delete: ("notifications.mealplan-entry-deleted", "notifications.mealplan-range-entry-deleted"),
}
"""Notification message translation keys per operation, as `(day entry key, date range entry key)`"""
@controller(router)
class GroupMealplanController(BaseCrudController):
@@ -37,6 +44,15 @@ class GroupMealplanController(BaseCrudController):
value = getattr(entry_type, "value", entry_type)
return self.t(f"mealplan.entry-type.{value}", default=str(value))
def _notification_message(self, operation: EventOperation, entry: ReadPlanEntry) -> str:
day_key, range_key = MEALPLAN_NOTIFICATION_KEYS[operation]
return self.t(
range_key if entry.end_date else day_key,
date=entry.date,
end_date=entry.end_date,
entry_type=self._translated_entry_type(entry.entry_type),
)
def registered_exceptions(self, ex: type[Exception]) -> str:
registered = {
**mealie_registered_exceptions(self.translator),
@@ -52,7 +68,7 @@ class GroupMealplanController(BaseCrudController):
)
def _get_random_recipes_from_mealplan(
self, plan_date: date, entry_type: PlanEntryType, limit: int = 1
self, plan_date: date, entry_type: PlanEntryType, limit: int = 1, end_date: date | None = None
) -> list[Recipe]:
"""
Gets rules for a mealplan and returns a list of random recipes based on the rules.
@@ -61,7 +77,9 @@ class GroupMealplanController(BaseCrudController):
Recipes from all households are included unless the rules specify a household filter.
"""
rules = self.repos.group_meal_plan_rules.get_rules(PlanRulesDay.from_date(plan_date), entry_type.value)
# date range entries (e.g. a week) aren't on a specific weekday, so only rules for all days apply to them
day = PlanRulesDay.unset if end_date else PlanRulesDay.from_date(plan_date)
rules = self.repos.group_meal_plan_rules.get_rules(day, entry_type.value)
cross_household_recipes = get_repositories(
self.session, group_id=self.group_id, household_id=None
).recipes.by_user(self.user.id)
@@ -84,19 +102,21 @@ class GroupMealplanController(BaseCrudController):
q: PaginationQuery = Depends(PaginationQuery),
start_date: date | None = None,
end_date: date | None = None,
include_week_entries: bool = False,
):
# week entries are opt-in so existing API clients, which expect every entry to be on a specific day,
# aren't handed them
week_filter = None if include_week_entries else "end_date IS NULL"
# merge start and end dates into pagination query only if either is provided
if start_date or end_date:
if not start_date:
date_filter = f"date <= {end_date}"
date_filters: list[str] = []
if start_date:
# a week entry starting before `start_date` still overlaps the range if it ends on or after it
date_filters.append(f"(date >= {start_date} OR end_date >= {start_date})")
if end_date:
date_filters.append(f"date <= {end_date}")
elif not end_date:
date_filter = f"date >= {start_date}"
else:
date_filter = f"date >= {start_date} AND date <= {end_date}"
q.query_filter = QueryFilterBuilder.combine_filters(q.query_filter, date_filter)
q.query_filter = QueryFilterBuilder.combine_filters(q.query_filter, week_filter, *date_filters)
return self.repo.page_all(pagination=q)
@@ -114,14 +134,11 @@ class GroupMealplanController(BaseCrudController):
recipe_name=result.recipe.name if result.recipe else None,
recipe_slug=result.recipe.slug if result.recipe else None,
date=data.date,
end_date=data.end_date,
),
group_id=result.group_id,
household_id=result.household_id,
message=self.t(
"notifications.mealplan-entry-created",
date=data.date,
entry_type=self._translated_entry_type(data.entry_type),
),
message=self._notification_message(EventOperation.create, result),
)
return result
@@ -141,7 +158,7 @@ class GroupMealplanController(BaseCrudController):
Refer to the meal plan settings routes for more information on how rules can be applied
to the random meal selector.
"""
random_recipes = self._get_random_recipes_from_mealplan(data.date, data.entry_type)
random_recipes = self._get_random_recipes_from_mealplan(data.date, data.entry_type, end_date=data.end_date)
if not random_recipes:
raise not_found(self.t("mealplan.no-recipes-match-your-rules"))
@@ -149,6 +166,7 @@ class GroupMealplanController(BaseCrudController):
result = self.mixins.create_one(
SavePlanEntry(
date=data.date,
end_date=data.end_date,
entry_type=data.entry_type,
recipe_id=recipe.id,
group_id=self.group_id,
@@ -165,14 +183,11 @@ class GroupMealplanController(BaseCrudController):
recipe_name=recipe.name,
recipe_slug=recipe.slug,
date=data.date,
end_date=data.end_date,
),
group_id=result.group_id,
household_id=result.household_id,
message=self.t(
"notifications.mealplan-entry-created",
date=data.date,
entry_type=self._translated_entry_type(data.entry_type),
),
message=self._notification_message(EventOperation.create, result),
)
return result
@@ -194,14 +209,11 @@ class GroupMealplanController(BaseCrudController):
recipe_name=result.recipe.name if result.recipe else None,
recipe_slug=result.recipe.slug if result.recipe else None,
date=result.date,
end_date=result.end_date,
),
group_id=result.group_id,
household_id=result.household_id,
message=self.t(
"notifications.mealplan-entry-updated",
date=result.date,
entry_type=self._translated_entry_type(result.entry_type),
),
message=self._notification_message(EventOperation.update, result),
)
return result
@@ -219,14 +231,11 @@ class GroupMealplanController(BaseCrudController):
recipe_name=result.recipe.name if result.recipe else None,
recipe_slug=result.recipe.slug if result.recipe else None,
date=result.date,
end_date=result.end_date,
),
group_id=result.group_id,
household_id=result.household_id,
message=self.t(
"notifications.mealplan-entry-deleted",
date=result.date,
entry_type=self._translated_entry_type(result.entry_type),
),
message=self._notification_message(EventOperation.delete, result),
)
return result
+21 -1
View File
@@ -1,4 +1,5 @@
from datetime import date
import datetime
from datetime import date, timedelta
from enum import StrEnum
from typing import Annotated
from uuid import UUID
@@ -26,13 +27,30 @@ class PlanEntryType(StrEnum):
dessert = "dessert"
WEEK_ENTRY_LENGTH = timedelta(days=6)
"""How far `end_date` is from `date` on an entry planned for a week instead of a specific day"""
def validate_end_date(value: date | None, info: ValidationInfo) -> date | None:
"""Only single-day entries (no `end_date`) and week entries are supported"""
start = info.data.get("date")
if value is not None and start is not None and value != start + WEEK_ENTRY_LENGTH:
raise ValueError(f"`end_date` must be empty or {WEEK_ENTRY_LENGTH.days} days after `date`")
return value
class CreateRandomEntry(MealieModel):
date: date
end_date: datetime.date | None = None
entry_type: PlanEntryType = PlanEntryType.dinner
_validate_end_date = field_validator("end_date")(validate_end_date)
class CreatePlanEntry(MealieModel):
date: date
end_date: datetime.date | None = None
entry_type: PlanEntryType = PlanEntryType.breakfast
title: str = ""
text: str = ""
@@ -47,6 +65,8 @@ class CreatePlanEntry(MealieModel):
return value
_validate_end_date = field_validator("end_date")(validate_end_date)
class UpdatePlanEntry(CreatePlanEntry):
id: int
+8
View File
@@ -15,6 +15,14 @@ logger = get_logger()
class PlanRulesDay(StrEnum):
"""
The day a meal plan rule applies to, or the weekday of the meal plan entry rules are looked up for.
On a rule, `unset` means the rule applies to all days. When looking up rules for an entry, `unset`
means the entry isn't on a specific weekday (e.g. it spans a week), so only rules that apply to all
days match it.
"""
monday = "monday"
tuesday = "tuesday"
wednesday = "wednesday"
@@ -70,7 +70,7 @@ class AlchemyExporter(BaseService):
"""Column names restored back into datetimes. Anything stored as a `NaiveDateTime` and missing
here comes back from a backup as a string; `test_every_datetime_column_survives_a_backup` guards
against forgetting to add one."""
look_for_date = {"date_added", "date"}
look_for_date = {"date_added", "date", "end_date"}
look_for_time = {"scheduled_time"}
class DateTimeParser(BaseModel):
@@ -1,5 +1,6 @@
from __future__ import annotations
import datetime as dt
import uuid
from datetime import UTC, date, datetime
from enum import Enum, auto
@@ -100,6 +101,7 @@ class EventMealplanData(EventDocumentDataBase):
document_type: EventDocumentType = EventDocumentType.mealplan
mealplan_id: int
date: date
end_date: dt.date | None = None
recipe_id: UUID4 | None = None
recipe_name: str | None = None
recipe_slug: str | None = None
@@ -177,14 +177,17 @@ class MealPlanICalService(BaseService):
f"DTSTAMP:{_format_utc(now)}",
]
start_time = query.time_for(entry.entry_type)
# date range entries (e.g. a week) aren't on a specific day, so they're always all-day events spanning the range
start_time = None if entry.end_date else query.time_for(entry.entry_type)
if start_time:
start = datetime.combine(entry.date, start_time, tzinfo=tz)
lines.append(f"DTSTART:{_format_utc(start)}")
lines.append(f"DTEND:{_format_utc(start + EVENT_DURATION)}")
else:
# DTEND is exclusive, so it's the day after the last day
last_day = entry.end_date or entry.date
lines.append(f"DTSTART;VALUE=DATE:{_format_date(entry.date)}")
lines.append(f"DTEND;VALUE=DATE:{_format_date(entry.date + timedelta(days=1))}")
lines.append(f"DTEND;VALUE=DATE:{_format_date(last_day + timedelta(days=1))}")
lines.append(f"SUMMARY:{_escape_text(f'{entry_type}: {title}')}")
if description:
@@ -1,5 +1,5 @@
import random
from datetime import UTC, datetime, timedelta
from datetime import UTC, date, datetime, timedelta
from uuid import UUID
import pytest
@@ -326,6 +326,70 @@ def test_get_mealplan_today(api_client: TestClient, unique_user: TestUser):
assert meal_plan["date"] == datetime.now(tzlocal()).date().strftime("%Y-%m-%d")
def create_entry(api_client: TestClient, unique_user: TestUser, **kwargs) -> dict:
data = CreatePlanEntry(entry_type="dinner", title=random_string(), **kwargs).model_dump(by_alias=True, mode="json")
response = api_client.post(api_routes.households_mealplans, json=data, headers=unique_user.token)
assert response.status_code == 201
return response.json()
@pytest.mark.parametrize(
"end_date_offset, status_code", [(None, 201), (6, 201), (0, 422), (5, 422), (7, 422), (-6, 422)]
)
def test_create_mealplan_end_date_must_be_a_week(
api_client: TestClient, unique_user: TestUser, end_date_offset: int | None, status_code: int
):
start = datetime.now(UTC).date()
end = start + timedelta(days=end_date_offset) if end_date_offset is not None else None
payload = {
"date": str(start),
"endDate": str(end) if end else None,
"entryType": "dinner",
"title": random_string(),
}
response = api_client.post(api_routes.households_mealplans, json=payload, headers=unique_user.token)
assert response.status_code == status_code
def test_get_slice_mealplans_week_entries(api_client: TestClient, unique_user: TestUser):
day = datetime.now(UTC).date() + timedelta(days=365)
day_entry = create_entry(api_client, unique_user, date=day)
week_start = day - timedelta(days=3)
week_entry = create_entry(api_client, unique_user, date=week_start, end_date=week_start + timedelta(days=6))
def get_ids(start: date, end: date, include_week_entries: bool) -> list[int]:
params = {"page": 1, "perPage": -1, "start_date": str(start), "end_date": str(end)}
if include_week_entries:
params["include_week_entries"] = "true"
response = api_client.get(api_routes.households_mealplans, params=params, headers=unique_user.token)
assert response.status_code == 200
return [item["id"] for item in response.json()["items"]]
# week entries are opt-in, so existing clients only see entries on a specific day
ids = get_ids(day, day, include_week_entries=False)
assert day_entry["id"] in ids
assert week_entry["id"] not in ids
# a week entry is returned for any range it overlaps, even one starting after the week does
ids = get_ids(day, day, include_week_entries=True)
assert day_entry["id"] in ids
assert week_entry["id"] in ids
# ranges entirely after or before the week don't return it
assert week_entry["id"] not in get_ids(day + timedelta(days=4), day + timedelta(days=10), True)
assert week_entry["id"] not in get_ids(day - timedelta(days=10), day - timedelta(days=4), True)
def test_get_mealplan_today_skips_week_entries(api_client: TestClient, unique_user: TestUser):
today = datetime.now(tzlocal()).date()
week_entry = create_entry(api_client, unique_user, date=today, end_date=today + timedelta(days=6))
response = api_client.get(api_routes.households_mealplans_today, headers=unique_user.token)
assert response.status_code == 200
assert week_entry["id"] not in [item["id"] for item in response.json()]
def test_get_mealplan_with_rules_categories_and_tags_filter(api_client: TestClient, unique_user: TestUser):
tags = [
unique_user.repos.tags.create(TagSave(name=random_string(), group_id=unique_user.group_id)) for _ in range(4)
@@ -442,6 +506,50 @@ def test_get_mealplan_with_rules_date_and_type_filter(api_client: TestClient, un
unique_user.repos.group_meal_plan_rules.delete(rule.id)
def test_get_rules_for_unset_day_skips_weekday_specific_rules(unique_user: TestUser):
any_day_rule = create_rule(unique_user, day=PlanRulesDay.unset, entry_type=PlanRulesType.unset)
saturday_rule = create_rule(unique_user, day=PlanRulesDay.saturday, entry_type=PlanRulesType.unset)
try:
rules = unique_user.repos.group_meal_plan_rules.get_rules(PlanRulesDay.unset, PlanRulesType.breakfast)
assert {rule.id for rule in rules} == {any_day_rule.id}
rules = unique_user.repos.group_meal_plan_rules.get_rules(PlanRulesDay.saturday, PlanRulesType.breakfast)
assert {rule.id for rule in rules} == {any_day_rule.id, saturday_rule.id}
finally:
unique_user.repos.group_meal_plan_rules.delete(any_day_rule.id)
unique_user.repos.group_meal_plan_rules.delete(saturday_rule.id)
def test_get_mealplan_with_rules_week_entry_skips_weekday_specific_rules(api_client: TestClient, unique_user: TestUser):
any_day_tag, saturday_tag = [
unique_user.repos.tags.create(TagSave(name=random_string(), group_id=unique_user.group_id)) for _ in range(2)
]
recipe = create_recipe(unique_user, tags=[any_day_tag])
[create_recipe(unique_user) for _ in range(5)]
rules = [
create_rule(unique_user, day=PlanRulesDay.unset, entry_type=PlanRulesType.breakfast, tags=[any_day_tag]),
create_rule(unique_user, day=PlanRulesDay.saturday, entry_type=PlanRulesType.breakfast, tags=[saturday_tag]),
]
try:
# a day entry on a Saturday gets both rules, which no recipe satisfies
payload = {"date": "2023-02-25", "entryType": "breakfast"}
response = api_client.post(api_routes.households_mealplans_random, json=payload, headers=unique_user.token)
assert response.status_code == 404
# a week entry starting on that Saturday isn't on a specific weekday, so the Saturday rule is skipped
payload = {"date": "2023-02-25", "endDate": "2023-03-03", "entryType": "breakfast"}
response = api_client.post(api_routes.households_mealplans_random, json=payload, headers=unique_user.token)
assert response.status_code == 200
assert response.json()["recipe"]["slug"] == recipe.slug
assert response.json()["endDate"] == "2023-03-03"
finally:
for rule in rules:
unique_user.repos.group_meal_plan_rules.delete(rule.id)
def test_get_mealplan_with_rules_includes_other_households(
api_client: TestClient, unique_user: TestUser, h2_user: TestUser
):
@@ -106,6 +106,20 @@ def test_ical_feed_filters_and_times(api_client: TestClient, unique_user_fn_scop
assert get_feed(api_client, token, {"types": ["brunch"]}).status_code == 422
def test_ical_feed_date_range_entry(api_client: TestClient, unique_user_fn_scoped: TestUser):
user = unique_user_fn_scoped
end_date = JULY_1 + timedelta(days=6)
create_entry(api_client, user, date=JULY_1, end_date=end_date, entry_type="dinner", title=random_string())
token = enable_feed(api_client, user)
# date range entries are all-day events spanning the range, even when their type has a time;
# DTEND is exclusive, so it's the day after the last day
feed = unfold(get_feed(api_client, token, {"tz": "Europe/Berlin", "dinner": "18:30"}).text)
assert feed.count("BEGIN:VEVENT") == 1
last_day_exclusive = end_date + timedelta(days=1)
assert f"DTSTART;VALUE=DATE:{JULY_1:%Y%m%d}\r\nDTEND;VALUE=DATE:{last_day_exclusive:%Y%m%d}\r\n" in feed
def test_ical_feed_skips_old_entries(api_client: TestClient, unique_user_fn_scoped: TestUser):
user = unique_user_fn_scoped
oldest = datetime.now(UTC).date() - timedelta(days=FEED_HISTORY_DAYS)
@@ -18,8 +18,9 @@ def test_duration_migration_preserves_populated_database(random_recipe, unique_u
engine = create_engine(settings.DB_URL)
config = Config(str(Path(__file__).parents[3] / "mealie/alembic/alembic.ini"))
scripts = ScriptDirectory.from_config(config)
assert scripts.get_heads() == ["afdc42353aa4"]
predecessor = scripts.get_revision("afdc42353aa4").down_revision
# target this migration directly, so later migrations don't change what's being tested
revision = "afdc42353aa4"
predecessor = scripts.get_revision(revision).down_revision
def snapshot():
metadata = MetaData()
@@ -35,7 +36,7 @@ def test_duration_migration_preserves_populated_database(random_recipe, unique_u
command.downgrade(config, predecessor)
before = snapshot()
assert before["recipe_instructions"]
command.upgrade(config, "head")
command.upgrade(config, revision)
column = next(c for c in inspect(engine).get_columns("recipe_instructions") if c["name"] == "duration_seconds")
assert column["nullable"]
with engine.begin() as connection:
@@ -49,7 +50,7 @@ def test_duration_migration_preserves_populated_database(random_recipe, unique_u
with engine.begin() as connection:
connection.execute(text("UPDATE recipe_instructions SET text = 'Legacy edit after downgrade'"))
after_legacy_edit = snapshot()
command.upgrade(config, "head")
command.upgrade(config, revision)
with engine.connect() as connection:
assert (
connection.scalar(text("SELECT COUNT(*) FROM recipe_instructions WHERE duration_seconds IS NOT NULL"))
@@ -1,6 +1,7 @@
from pathlib import Path
from mealie.pkgs.i18n.json_provider import JsonProvider
from mealie.routes.households.controller_mealplan import MEALPLAN_NOTIFICATION_KEYS
from mealie.services.event_bus_service.event_types import EventBusMessage, EventTypes
@@ -80,3 +81,13 @@ def test_every_event_type_has_an_english_title_translation():
missing_keys.append(key)
assert not missing_keys, f"Missing event title translations: {missing_keys}"
def test_every_mealplan_notification_key_has_an_english_translation():
repo_root = Path(__file__).parents[4]
translator = JsonProvider(repo_root / "mealie/lang/messages/en-US.json")
keys = [key for keys in MEALPLAN_NOTIFICATION_KEYS.values() for key in keys]
missing_keys = [key for key in keys if translator.t(key) == key]
assert not missing_keys, f"Missing meal plan notification translations: {missing_keys}"
@@ -319,3 +319,32 @@ def test_get_meals_by_date_range_invalid_date_range(unique_user: TestUser):
meals_in_range = meal_repo.get_meals_by_date_range(start_date, end_date)
assert len(meals_in_range) == 0
def test_get_meals_by_date_range_skips_week_entries(unique_user: TestUser):
"""
Test that get_meals_by_date_range leaves out week entries, since they aren't planned for a specific day.
"""
meal_repo = unique_user.repos.meals
today = datetime.now(UTC)
week_meal = meal_repo.create(
{
"date": today,
"end_date": (today + timedelta(days=6)).date(),
"entry_type": "dinner",
"title": "Week Meal",
"text": "Test meal for a week",
"group_id": unique_user.group_id,
"household_id": unique_user.household_id,
"user_id": unique_user.user_id,
}
)
try:
meals_in_range = meal_repo.get_meals_by_date_range(today, today)
assert week_meal.id not in [meal.id for meal in meals_in_range]
finally:
meal_repo.delete(week_meal.id)