feat: persist drag-and-drop meal ordering (#8749)
Co-authored-by: Michael Genson <genson.michael@gmail.com>
This commit is contained in:
1 parent
73f22c874d
commit
e4a567c597
18 files changed
+742
-42
No files matched your search
@@ -9,6 +9,38 @@ Mealie supports long-live api tokens in the user frontend. These can be created
|
||||
### Exploring Your Local API
|
||||
On your local installation you can access interactive API documentation that provides `curl` examples and expected results. This allows you to easily test and interact with your API to identify places to include your own functionality. You can visit the documentation at `http://<your-mealie-site>/docs` or see the example at the [Demo Site](https://demo.mealie.io/docs).
|
||||
|
||||
### Meal Plan Ordering
|
||||
|
||||
Meal plan entries have a `position` that determines their order within a day, starting at zero. By default, `GET /api/households/mealplans` returns entries ordered by date and then position. Without ordering parameters, both are sorted ascending.
|
||||
|
||||
You can pass `orderDirection=desc` to reverse this order, or use `orderBy` and the other [advanced ordering](#advanced-ordering) parameters to choose your own sort. These parameters only change the order of the results, they do not change the saved positions.
|
||||
|
||||
To reorder your household's entries or move them between days or weeks, use `PUT /api/households/mealplans/reorder`. Each request item identifies a bucket by its `date` and, for a week entry, its `endDate`. Omit `endDate` or set it to `null` for a day bucket. A week entry's `endDate` is six days after its `date`. The IDs in each item are meal plan entry IDs in the desired order. For example:
|
||||
|
||||
```json
|
||||
[
|
||||
{"date": "2026-10-20", "entryIds": [103, 101]},
|
||||
{"date": "2026-10-21", "entryIds": [102, 104]}
|
||||
]
|
||||
```
|
||||
|
||||
If October 20 contains entries `101`, `102`, and `103`, and October 21 contains `104`, this moves entry `102` to October 21 and places `103` before `101` on October 20. These are meal plan entry IDs, not recipe IDs. Dates outside the request are left unchanged.
|
||||
|
||||
To move an entry between a day and a week bucket, include both buckets. For example, to move entry `105` from the day list to the week list starting October 20:
|
||||
|
||||
```json
|
||||
[
|
||||
{"date": "2026-10-20", "entryIds": []},
|
||||
{"date": "2026-10-20", "endDate": "2026-10-26", "entryIds": [105]}
|
||||
]
|
||||
```
|
||||
|
||||
Include every entry currently in each bucket you submit, including an empty ID list when clearing a bucket. Buckets are identified by date and whether they are day or week entries.
|
||||
|
||||
Successful requests return `204 No Content`. An empty request, repeated buckets, or repeated IDs returns `422`. If the IDs do not match the entries currently in the submitted buckets, the API returns `409`. Fetch the affected buckets again before retrying.
|
||||
|
||||
New meal entries are placed after the last entry of the same meal type. If there are none, Mealie uses the meal type order: breakfast, lunch, dinner, side, snack, drink, dessert. This also applies when changing an entry's date through the regular update endpoint. Existing entries keep their relative order.
|
||||
|
||||
### Extras
|
||||
#### Recipe Extras
|
||||
Recipes extras are a key feature of the Mealie API. They allow you to create custom json key/value pairs within a recipe to reference from 3rd part applications. You can use these keys to contain information to trigger automation or custom messages to relay to your desired device.
|
||||
|
||||
@@ -82,6 +82,10 @@ Mealie also has the concept of cookbooks. These can be created inside of a group
|
||||
|
||||
Mealie uses a calendar like view to help you plan your meals. It shows you the previous day and the next 6 days by default. You can toggle through the calendar by clicking the arrows on the top of the page. In editor mode, you can use the random recipe buttons or manually add an entry.
|
||||
|
||||
In edit mode, drag entries to reorder them within a day or move them to another day. Your order is saved and also shown in the planner's view mode. Newly added entries are placed after the last entry of the same meal type, without rearranging existing entries.
|
||||
|
||||
Integrations can also [reorder meal plan entries through the API](api-usage.md#meal-plan-ordering).
|
||||
|
||||
!!! tip
|
||||
You can also add a "Note" type entry to your meal plan when you want to include something that might not have a specific recipes. This is great for leftovers, or for ordering out.
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import MealPlanLayout from "./MealPlanLayout.vue";
|
||||
import type { Days } from "~/composables/use-group-mealplan";
|
||||
import type { ReadPlanEntry } from "~/lib/api/types/meal-plan";
|
||||
|
||||
describe("MealPlanLayout", () => {
|
||||
it.each([
|
||||
{ types: [], sizes: [] },
|
||||
{ types: ["breakfast", "breakfast", "lunch", "dinner"], sizes: [2, 1, 1] },
|
||||
{ types: ["dinner", "breakfast", "dinner", "lunch"], sizes: [1, 1, 1, 1] },
|
||||
])("preserves saved order and groups adjacent types: $types", ({ types, sizes }) => {
|
||||
const meals = types.map((entryType, id) => ({ id, entryType }) as ReadPlanEntry);
|
||||
let day: Days | undefined;
|
||||
mount(MealPlanLayout, {
|
||||
props: { mealplans: [{ date: new Date(2026, 9, 15), meals }] },
|
||||
global: {
|
||||
stubs: {
|
||||
"v-row": { template: "<div><slot /></div>" },
|
||||
"v-col": { template: "<div><slot /></div>" },
|
||||
},
|
||||
},
|
||||
slots: {
|
||||
default: (props: { day: Days }) => {
|
||||
day = props.day;
|
||||
return "";
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(day!.sections.flatMap(section => section.meals)).toEqual(meals);
|
||||
expect(day!.sections.map(section => section.meals.length)).toEqual(sizes);
|
||||
});
|
||||
});
|
||||
@@ -14,24 +14,34 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { PlanEntryType } from "~/lib/api/types/meal-plan";
|
||||
import { getScaledRecipes } from "~/composables/use-group-mealplan";
|
||||
import type { DaySection, Days, MealsByDate } from "~/composables/use-group-mealplan";
|
||||
import { useGlobalI18n } from "~/composables/use-global-i18n";
|
||||
|
||||
defineProps<{
|
||||
mealplans: MealsByDate[];
|
||||
}>();
|
||||
const planTypeOptions = usePlanTypeOptions();
|
||||
const i18n = useGlobalI18n();
|
||||
|
||||
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);
|
||||
// Group only adjacent types so headings never change the saved meal order.
|
||||
const sections: DaySection[] = [];
|
||||
for (const meal of day.meals) {
|
||||
const last = sections.at(-1);
|
||||
if (last && last.meals[0].entryType === meal.entryType) {
|
||||
last.meals.push(meal);
|
||||
}
|
||||
else {
|
||||
sections.push({ title: i18n.t("meal-plan." + meal.entryType), meals: [meal] });
|
||||
}
|
||||
}
|
||||
return {
|
||||
date: day.date,
|
||||
endDate: day.endDate,
|
||||
sections: planTypeOptions
|
||||
.map(({ text, value }) => ({ title: text, meals: forSection(value) }))
|
||||
.filter(({ meals }) => meals.length > 0),
|
||||
sections,
|
||||
recipes: getScaledRecipes(day.meals),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,8 +2,17 @@ import { addDays, format, startOfWeek } from "date-fns";
|
||||
import type { Day } from "date-fns";
|
||||
import { useHouseholdSelf } from "./use-households";
|
||||
import { useAsyncKey } from "./use-utils";
|
||||
import { alert } from "./use-toast";
|
||||
import { useGlobalI18n } from "./use-global-i18n";
|
||||
import { useUserApi } from "~/composables/api";
|
||||
import type { PlanEntryCreate, PlanEntryType, PlanEntryOut, RecipeSummary, PlanEntryUpdate } from "~/lib/api/types/meal-plan";
|
||||
import type {
|
||||
PlanEntryCreate,
|
||||
PlanEntryType,
|
||||
PlanEntryOut,
|
||||
RecipeSummary,
|
||||
PlanEntryReorderUpdate,
|
||||
PlanEntryUpdate,
|
||||
} from "~/lib/api/types/meal-plan";
|
||||
|
||||
type PlanOption = {
|
||||
text: string;
|
||||
@@ -83,7 +92,7 @@ export function useMealPlanEntryDates() {
|
||||
}
|
||||
export type DaySection = {
|
||||
title: string;
|
||||
meals: PlanEntryOut[];
|
||||
meals: [PlanEntryOut, ...PlanEntryOut[]];
|
||||
};
|
||||
|
||||
export type ScaledRecipe = RecipeSummary & { scale: number };
|
||||
@@ -127,6 +136,7 @@ export interface Meal {
|
||||
|
||||
export const useMealplans = function (range: Ref<DateRange>) {
|
||||
const api = useUserApi();
|
||||
const i18n = useGlobalI18n();
|
||||
const loading = ref(false);
|
||||
|
||||
const actions = {
|
||||
@@ -195,6 +205,20 @@ export const useMealplans = function (range: Ref<DateRange>) {
|
||||
loading.value = false;
|
||||
},
|
||||
|
||||
async reorder(days: PlanEntryReorderUpdate[]) {
|
||||
loading.value = true;
|
||||
try {
|
||||
const { error } = await api.mealplans.reorder(days);
|
||||
await this.refreshAll();
|
||||
if (error) {
|
||||
alert.error(i18n.t("events.something-went-wrong"));
|
||||
}
|
||||
}
|
||||
finally {
|
||||
loading.value = false;
|
||||
}
|
||||
},
|
||||
|
||||
async deleteOne(id: string | number) {
|
||||
loading.value = true;
|
||||
const { data } = await api.mealplans.deleteOne(id);
|
||||
|
||||
@@ -37,6 +37,7 @@ export interface PlanEntryOut {
|
||||
groupId: string;
|
||||
userId: string;
|
||||
householdId: string;
|
||||
position: number;
|
||||
recipe: RecipeSummary | null;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
@@ -90,6 +91,11 @@ export interface ToolOut {
|
||||
recipeCount: number;
|
||||
householdsWithTool: string[];
|
||||
}
|
||||
export interface PlanEntryReorderUpdate {
|
||||
date: string;
|
||||
endDate?: string | null;
|
||||
entryIds: number[];
|
||||
}
|
||||
export interface PlanEntrySave {
|
||||
date: string;
|
||||
endDate?: string | null;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { BaseCRUDAPI } from "../base/base-clients";
|
||||
import type { PlanEntryCreate, RandomPlanEntryCreate, MealPlanICalTokenOut, PlanEntryOut, PlanEntryUpdate } from "~/lib/api/types/meal-plan";
|
||||
import type { PlanEntryCreate, RandomPlanEntryCreate, MealPlanICalTokenOut, PlanEntryOut, PlanEntryUpdate, PlanEntryReorderUpdate } from "~/lib/api/types/meal-plan";
|
||||
|
||||
const prefix = "/api";
|
||||
|
||||
@@ -7,12 +7,13 @@ const routes = {
|
||||
mealplan: `${prefix}/households/mealplans`,
|
||||
random: `${prefix}/households/mealplans/random`,
|
||||
ical: `${prefix}/households/mealplans/ical`,
|
||||
reorder: `${prefix}/households/mealplans/reorder`,
|
||||
mealplanId: (id: string | number) => `${prefix}/households/mealplans/${id}`,
|
||||
};
|
||||
|
||||
export class MealPlanAPI extends BaseCRUDAPI<PlanEntryCreate, PlanEntryOut, PlanEntryUpdate> {
|
||||
baseRoute = routes.mealplan;
|
||||
itemRoute = routes.mealplanId;
|
||||
override baseRoute = routes.mealplan;
|
||||
override itemRoute = routes.mealplanId;
|
||||
|
||||
async setRandom(payload: RandomPlanEntryCreate) {
|
||||
return await this.requests.post<PlanEntryOut>(routes.random, payload);
|
||||
@@ -29,4 +30,8 @@ export class MealPlanAPI extends BaseCRUDAPI<PlanEntryCreate, PlanEntryOut, Plan
|
||||
async deleteICalToken() {
|
||||
return await this.requests.delete<MealPlanICalTokenOut>(routes.ical);
|
||||
}
|
||||
|
||||
async reorder(payload: PlanEntryReorderUpdate[]) {
|
||||
return await this.requests.put<undefined, PlanEntryReorderUpdate[]>(routes.reorder, payload);
|
||||
}
|
||||
}
|
||||
@@ -164,21 +164,32 @@ watch(
|
||||
{ immediate: true, deep: true },
|
||||
);
|
||||
|
||||
function onMoveCallback(evt: SortableEvent) {
|
||||
// A Meal was moved, set the new date value and make an update request and refresh the meals
|
||||
async function onMoveCallback(evt: SortableEvent) {
|
||||
// VueDraggable has already updated the source and destination arrays.
|
||||
const fromMealsByIndex = parseInt(evt.from.getAttribute("data-index") ?? "");
|
||||
const toMealsByIndex = parseInt(evt.to.getAttribute("data-index") ?? "");
|
||||
|
||||
if (!isNaN(fromMealsByIndex) && !isNaN(toMealsByIndex)) {
|
||||
const dest = props.mealplans[toMealsByIndex];
|
||||
const mealData = mealplansByDate[planKey(dest)][evt.newIndex as number];
|
||||
if (Number.isNaN(fromMealsByIndex) || Number.isNaN(toMealsByIndex)) return;
|
||||
|
||||
// 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;
|
||||
const fromDay = props.mealplans[fromMealsByIndex];
|
||||
const toDay = props.mealplans[toMealsByIndex];
|
||||
if (!fromDay || !toDay) return;
|
||||
|
||||
props.actions.updateOne(mealData);
|
||||
}
|
||||
const affectedDays = fromMealsByIndex === toMealsByIndex ? [toDay] : [fromDay, toDay];
|
||||
const movedMeal = mealplansByDate[planKey(toDay)][evt.newIndex as number];
|
||||
if (!movedMeal) return;
|
||||
|
||||
// keep the local entry in sync with the destination before saving both lists
|
||||
movedMeal.date = format(toDay.date, "yyyy-MM-dd");
|
||||
movedMeal.endDate = toDay.endDate ? format(toDay.endDate, "yyyy-MM-dd") : null;
|
||||
|
||||
const orderedDays = affectedDays.map(day => ({
|
||||
date: format(day.date, "yyyy-MM-dd"),
|
||||
endDate: day.endDate ? format(day.endDate, "yyyy-MM-dd") : null,
|
||||
entryIds: mealplansByDate[planKey(day)].map(meal => meal.id),
|
||||
}));
|
||||
|
||||
await props.actions.reorder(orderedDays);
|
||||
}
|
||||
|
||||
// =====================================================
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
:color="day.endDate ? 'transparent' : undefined"
|
||||
>
|
||||
<SpinTransition>
|
||||
<div v-for="section in day.sections" :key="section.title">
|
||||
<div v-for="section in day.sections" :key="section.meals[0].id">
|
||||
<div class="py-2 d-flex flex-column">
|
||||
<p class="text-overline my-0">
|
||||
{{ section.title }}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""add meal plan position
|
||||
|
||||
Revision ID: a136609cde0f
|
||||
Revises: 08880d089634
|
||||
Create Date: 2026-11-25 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "a136609cde0f"
|
||||
down_revision: str | None = "08880d089634"
|
||||
branch_labels: str | tuple[str, ...] | None = None
|
||||
depends_on: str | tuple[str, ...] | None = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table("group_meal_plans", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("position", sa.Integer(), nullable=True))
|
||||
|
||||
connection = op.get_bind()
|
||||
rows = connection.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT group_meal_plans.id, users.household_id, group_meal_plans.date,
|
||||
group_meal_plans.end_date
|
||||
FROM group_meal_plans
|
||||
LEFT JOIN users ON users.id = group_meal_plans.user_id
|
||||
ORDER BY users.household_id, group_meal_plans.date,
|
||||
group_meal_plans.end_date,
|
||||
CASE group_meal_plans.entry_type
|
||||
WHEN 'breakfast' THEN 0 WHEN 'lunch' THEN 1 WHEN 'dinner' THEN 2
|
||||
WHEN 'side' THEN 3 WHEN 'snack' THEN 4 WHEN 'drink' THEN 5
|
||||
WHEN 'dessert' THEN 6 ELSE 7
|
||||
END,
|
||||
group_meal_plans.created_at DESC, group_meal_plans.id
|
||||
"""
|
||||
)
|
||||
).mappings()
|
||||
|
||||
positions_by_day = {}
|
||||
updates = []
|
||||
for row in rows:
|
||||
# use end_date to distinguish day and week lists that share the same start date
|
||||
position_bucket = (row["household_id"], row["date"], row["end_date"] is not None)
|
||||
position = positions_by_day.get(position_bucket, 0)
|
||||
updates.append({"id": row["id"], "position": position})
|
||||
positions_by_day[position_bucket] = position + 1
|
||||
|
||||
if updates:
|
||||
connection.execute(
|
||||
sa.text("UPDATE group_meal_plans SET position = :position WHERE id = :id"),
|
||||
updates,
|
||||
)
|
||||
|
||||
with op.batch_alter_table("group_meal_plans", schema=None) as batch_op:
|
||||
batch_op.alter_column("position", existing_type=sa.Integer(), nullable=False)
|
||||
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table("group_meal_plans", schema=None) as batch_op:
|
||||
batch_op.drop_column("position")
|
||||
@@ -55,6 +55,14 @@ class NoEntryFound(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class MealPlanEntriesChanged(Exception):
|
||||
"""
|
||||
This exception is raised when meal plan entries change during a reorder operation.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class OpenAIServiceError(Exception):
|
||||
"""
|
||||
This exception is raised when there is an error communicating with OpenAI services.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import datetime
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import Column, Date, Float, ForeignKey, String, Table, UniqueConstraint, orm
|
||||
from sqlalchemy import Column, Date, Float, ForeignKey, Integer, String, Table, UniqueConstraint, orm
|
||||
from sqlalchemy.ext.associationproxy import AssociationProxy, association_proxy
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
@@ -57,6 +57,7 @@ class GroupMealPlan(SqlAlchemyBase, BaseMixins):
|
||||
|
||||
date: FilterableColumn[datetime.date] = mapped_column(Date, index=True, nullable=False)
|
||||
end_date: FilterableColumn[datetime.date | None] = mapped_column(Date, index=True, nullable=True)
|
||||
position: FilterableColumn[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
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)
|
||||
|
||||
@@ -1,30 +1,148 @@
|
||||
from datetime import UTC, datetime
|
||||
from datetime import UTC, date, datetime
|
||||
from typing import Any
|
||||
|
||||
from pydantic import UUID4, BaseModel
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import or_, select
|
||||
|
||||
from mealie.core.exceptions import MealPlanEntriesChanged
|
||||
from mealie.db.models.household import GroupMealPlan
|
||||
from mealie.schema.meal_plan.new_meal import PlanEntryOut
|
||||
from mealie.schema.meal_plan.new_meal import PlanEntryOut, PlanEntryReorderUpdate, PlanEntryType
|
||||
|
||||
from .repository_generic import HouseholdRepositoryGeneric
|
||||
|
||||
|
||||
class RepositoryMeals(HouseholdRepositoryGeneric[PlanEntryOut, GroupMealPlan]):
|
||||
def update(self, match_value: str | int | UUID4, new_data: dict | BaseModel) -> PlanEntryOut:
|
||||
new_data = new_data.copy() if isinstance(new_data, dict) else new_data.model_dump()
|
||||
current_entry = self._query_one(match_value=match_value)
|
||||
# The plan's household comes from its user, so a client-supplied user_id could move it to another household
|
||||
new_data = new_data if isinstance(new_data, dict) else new_data.model_dump()
|
||||
new_data["user_id"] = self._query_one(match_value=match_value).user_id
|
||||
new_data["user_id"] = current_entry.user_id
|
||||
|
||||
new_date = new_data.get("date", current_entry.date)
|
||||
new_end_date = new_data.get("end_date", current_entry.end_date)
|
||||
# end_date = None => meal is scheduled on a specific weekday
|
||||
schedule_changed = new_date != current_entry.date or (new_end_date is not None) != (
|
||||
current_entry.end_date is not None
|
||||
)
|
||||
|
||||
if schedule_changed:
|
||||
previous_date = current_entry.date
|
||||
previous_is_week = current_entry.end_date is not None
|
||||
new_data["position"] = self._insert_position(
|
||||
new_date,
|
||||
new_end_date,
|
||||
new_data.get("entry_type", current_entry.entry_type),
|
||||
)
|
||||
current_entry.date = new_date
|
||||
current_entry.end_date = new_end_date
|
||||
self.session.flush()
|
||||
self._renumber_positions_in_source_list(previous_date, previous_is_week)
|
||||
|
||||
return super().update(match_value, new_data)
|
||||
|
||||
def _insert_position(self, date_value: date, end_date_value: date | None, entry_type: str) -> int:
|
||||
if not self.household_id:
|
||||
raise Exception("household_id not set")
|
||||
|
||||
entries = self.session.scalars(
|
||||
select(GroupMealPlan)
|
||||
# select the destination list: day entries when end_date_value is None, or week entries otherwise
|
||||
.where(
|
||||
GroupMealPlan.date == date_value,
|
||||
GroupMealPlan.end_date.is_not(None) if end_date_value is not None else GroupMealPlan.end_date.is_(None),
|
||||
GroupMealPlan.household_id == self.household_id,
|
||||
)
|
||||
.order_by(GroupMealPlan.position, GroupMealPlan.id)
|
||||
).all()
|
||||
type_order = {plan_type.value: rank for rank, plan_type in enumerate(PlanEntryType)}
|
||||
# Preserve manual order: join the last matching type, otherwise precede a later type.
|
||||
matching = [i for i, entry in enumerate(entries) if entry.entry_type == entry_type]
|
||||
if matching:
|
||||
position = matching[-1] + 1
|
||||
else:
|
||||
new_type_rank = type_order.get(entry_type, len(type_order))
|
||||
position = len(entries)
|
||||
for i, entry in enumerate(entries):
|
||||
existing_type_rank = type_order.get(entry.entry_type, len(type_order))
|
||||
if existing_type_rank > new_type_rank:
|
||||
position = i
|
||||
break
|
||||
# shift the affected positions to make a gap
|
||||
for i, entry in enumerate(entries):
|
||||
entry.position = i if i < position else i + 1
|
||||
return position
|
||||
|
||||
def _renumber_positions_in_source_list(self, date_value: date, is_week: bool) -> None:
|
||||
entries = self.session.scalars(
|
||||
select(GroupMealPlan)
|
||||
.where(
|
||||
GroupMealPlan.date == date_value,
|
||||
GroupMealPlan.end_date.is_not(None) if is_week else GroupMealPlan.end_date.is_(None),
|
||||
GroupMealPlan.household_id == self.household_id,
|
||||
)
|
||||
.order_by(GroupMealPlan.position, GroupMealPlan.id)
|
||||
).all()
|
||||
for position, entry in enumerate(entries):
|
||||
entry.position = position
|
||||
|
||||
def create(self, data: PlanEntryOut | BaseModel | dict[str, Any]) -> PlanEntryOut:
|
||||
data = data if isinstance(data, dict) else data.model_dump()
|
||||
data["position"] = self._insert_position(
|
||||
data["date"], data.get("end_date"), data.get("entry_type", PlanEntryType.breakfast)
|
||||
)
|
||||
return super().create(data)
|
||||
|
||||
def reorder(self, days: list[PlanEntryReorderUpdate]) -> None:
|
||||
if not self.household_id:
|
||||
raise Exception("household_id not set")
|
||||
|
||||
requested_ids = [entry_id for day in days for entry_id in day.entry_ids]
|
||||
position_buckets = [
|
||||
(GroupMealPlan.date == day.date)
|
||||
& (GroupMealPlan.end_date.is_not(None) if day.end_date is not None else GroupMealPlan.end_date.is_(None))
|
||||
for day in days
|
||||
]
|
||||
|
||||
entries = (
|
||||
self.session.execute(
|
||||
select(GroupMealPlan).where(
|
||||
or_(*position_buckets),
|
||||
GroupMealPlan.household_id == self.household_id,
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
entries_by_id = {entry.id: entry for entry in entries}
|
||||
if set(requested_ids) != set(entries_by_id):
|
||||
raise MealPlanEntriesChanged
|
||||
|
||||
try:
|
||||
for day in days:
|
||||
for position, entry_id in enumerate(day.entry_ids):
|
||||
entry = entries_by_id[entry_id]
|
||||
entry.date = day.date
|
||||
entry.end_date = day.end_date
|
||||
entry.position = position
|
||||
|
||||
self.session.commit()
|
||||
except Exception:
|
||||
self.session.rollback()
|
||||
raise
|
||||
|
||||
def get_today(self, tz=UTC) -> list[PlanEntryOut]:
|
||||
if not self.household_id:
|
||||
raise Exception("household_id not set")
|
||||
|
||||
today = datetime.now(tz=tz).date()
|
||||
stmt = select(GroupMealPlan).filter(
|
||||
GroupMealPlan.date == today,
|
||||
GroupMealPlan.end_date.is_(None), # week entries aren't planned for a specific day
|
||||
GroupMealPlan.household_id == self.household_id,
|
||||
stmt = (
|
||||
select(GroupMealPlan)
|
||||
.filter(
|
||||
GroupMealPlan.date == today,
|
||||
GroupMealPlan.end_date.is_(None), # week entries aren't planned for a specific day
|
||||
GroupMealPlan.household_id == self.household_id,
|
||||
)
|
||||
.order_by(GroupMealPlan.position)
|
||||
)
|
||||
plans = self.session.execute(stmt).scalars().all()
|
||||
return [self.schema.model_validate(x) for x in plans]
|
||||
@@ -33,11 +151,15 @@ class RepositoryMeals(HouseholdRepositoryGeneric[PlanEntryOut, GroupMealPlan]):
|
||||
if not self.household_id:
|
||||
raise Exception("household_id not set")
|
||||
|
||||
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,
|
||||
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,
|
||||
)
|
||||
.order_by(GroupMealPlan.date, GroupMealPlan.position)
|
||||
)
|
||||
plans = self.session.execute(stmt).scalars().all()
|
||||
return [self.schema.model_validate(x) for x in plans]
|
||||
@@ -3,9 +3,9 @@ from functools import cached_property
|
||||
from uuid import UUID
|
||||
|
||||
from dateutil.tz import tzlocal
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
from mealie.core.exceptions import mealie_registered_exceptions
|
||||
from mealie.core.exceptions import MealPlanEntriesChanged, mealie_registered_exceptions
|
||||
from mealie.repos.all_repositories import get_repositories
|
||||
from mealie.repos.repository_meals import RepositoryMeals
|
||||
from mealie.routes._base import controller
|
||||
@@ -14,10 +14,15 @@ from mealie.routes._base.mixins import HttpRepo
|
||||
from mealie.routes._base.permissions import not_found
|
||||
from mealie.schema import mapper
|
||||
from mealie.schema.meal_plan import PlanEntryCreate, PlanEntryOut, PlanEntrySave, PlanEntryUpdate
|
||||
from mealie.schema.meal_plan.new_meal import PlanEntryPagination, PlanEntryType, RandomPlanEntryCreate
|
||||
from mealie.schema.meal_plan.new_meal import (
|
||||
PlanEntryPagination,
|
||||
PlanEntryReorderUpdate,
|
||||
PlanEntryType,
|
||||
RandomPlanEntryCreate,
|
||||
)
|
||||
from mealie.schema.meal_plan.plan_rules import PlanRulesDay
|
||||
from mealie.schema.recipe.recipe import RecipeOut
|
||||
from mealie.schema.response.pagination import PaginationQuery
|
||||
from mealie.schema.response.pagination import OrderDirection, PaginationQuery
|
||||
from mealie.services.event_bus_service.event_types import (
|
||||
EventMealplanData,
|
||||
EventOperation,
|
||||
@@ -109,6 +114,7 @@ class GroupMealplanController(BaseCrudController):
|
||||
@router.get("", response_model=PlanEntryPagination)
|
||||
def get_all(
|
||||
self,
|
||||
request: Request,
|
||||
q: PaginationQuery = Depends(PaginationQuery),
|
||||
start_date: date | None = None,
|
||||
end_date: date | None = None,
|
||||
@@ -128,6 +134,11 @@ class GroupMealplanController(BaseCrudController):
|
||||
|
||||
q.query_filter = QueryFilterBuilder.combine_filters(q.query_filter, week_filter, *date_filters)
|
||||
|
||||
if not q.order_by:
|
||||
q.order_by = "date,position"
|
||||
if "orderDirection" not in request.query_params:
|
||||
q.order_direction = OrderDirection.asc
|
||||
|
||||
return self.repo.page_all(pagination=q)
|
||||
|
||||
@router.post("", response_model=PlanEntryOut, status_code=201)
|
||||
@@ -203,6 +214,27 @@ class GroupMealplanController(BaseCrudController):
|
||||
|
||||
return result
|
||||
|
||||
@router.put("/reorder", status_code=204)
|
||||
def reorder(self, days: list[PlanEntryReorderUpdate]):
|
||||
if not days:
|
||||
raise HTTPException(status_code=422, detail="At least one day is required.")
|
||||
|
||||
buckets = [(day.date, day.end_date is not None) for day in days]
|
||||
if len(set(buckets)) != len(buckets):
|
||||
raise HTTPException(status_code=422, detail="Each day or week may only be included once.")
|
||||
|
||||
requested_ids = [entry_id for day in days for entry_id in day.entry_ids]
|
||||
if len(set(requested_ids)) != len(requested_ids):
|
||||
raise HTTPException(status_code=422, detail="A meal plan entry may only be included once.")
|
||||
|
||||
try:
|
||||
self.repo.reorder(days)
|
||||
except MealPlanEntriesChanged:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail="Meal plan entries changed. Refresh and try again.",
|
||||
) from None
|
||||
|
||||
@router.get("/{item_id}", response_model=PlanEntryOut)
|
||||
def get_one(self, item_id: int):
|
||||
return self.mixins.get_one(item_id)
|
||||
|
||||
@@ -4,6 +4,7 @@ from .new_meal import (
|
||||
PlanEntryCreate,
|
||||
PlanEntryOut,
|
||||
PlanEntryPagination,
|
||||
PlanEntryReorderUpdate,
|
||||
PlanEntrySave,
|
||||
PlanEntryType,
|
||||
PlanEntryUpdate,
|
||||
@@ -15,6 +16,7 @@ __all__ = [
|
||||
"PlanEntryCreate",
|
||||
"PlanEntryOut",
|
||||
"PlanEntryPagination",
|
||||
"PlanEntryReorderUpdate",
|
||||
"PlanEntrySave",
|
||||
"PlanEntryType",
|
||||
"PlanEntryUpdate",
|
||||
|
||||
@@ -48,6 +48,14 @@ class RandomPlanEntryCreate(MealieModel):
|
||||
_validate_end_date = field_validator("end_date")(validate_end_date)
|
||||
|
||||
|
||||
class PlanEntryReorderUpdate(MealieModel):
|
||||
date: date
|
||||
end_date: datetime.date | None = None
|
||||
entry_ids: list[int]
|
||||
|
||||
_validate_end_date = field_validator("end_date")(validate_end_date)
|
||||
|
||||
|
||||
class PlanEntryCreate(MealieModel):
|
||||
date: date
|
||||
end_date: datetime.date | None = None
|
||||
@@ -82,6 +90,7 @@ class PlanEntrySave(PlanEntryCreate):
|
||||
|
||||
class PlanEntryOut(PlanEntryUpdate, MealieOutModel):
|
||||
household_id: UUID
|
||||
position: int = 0
|
||||
recipe: RecipeSummary | None = None
|
||||
updated_at: datetime.datetime | None = UpdatedAtField(None)
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
@@ -268,6 +268,339 @@ def test_get_all_mealplans(api_client: TestClient, unique_user: TestUser):
|
||||
assert len(response.json()["items"]) >= 3
|
||||
|
||||
|
||||
def test_reorder_mealplans_within_day(api_client: TestClient, unique_user: TestUser):
|
||||
start_date = datetime.now(UTC).date() + timedelta(days=10)
|
||||
|
||||
def create_entry(entry_date, title):
|
||||
response = api_client.post(
|
||||
api_routes.households_mealplans,
|
||||
headers=unique_user.token,
|
||||
json={"date": entry_date.isoformat(), "title": title},
|
||||
)
|
||||
assert response.status_code == 201
|
||||
return response.json()
|
||||
|
||||
first = create_entry(start_date, "First")
|
||||
second = create_entry(start_date, "Second")
|
||||
third = create_entry(start_date, "Third")
|
||||
|
||||
response = api_client.put(
|
||||
f"{api_routes.households_mealplans}/reorder",
|
||||
headers=unique_user.token,
|
||||
json=[{"date": start_date.isoformat(), "entryIds": [third["id"], first["id"], second["id"]]}],
|
||||
)
|
||||
assert response.status_code == 204
|
||||
|
||||
response = api_client.get(
|
||||
route_all_slice(1, -1, start_date.isoformat(), start_date.isoformat()),
|
||||
headers=unique_user.token,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
items = response.json()["items"]
|
||||
assert [item["id"] for item in items] == [third["id"], first["id"], second["id"]]
|
||||
assert [item["position"] for item in items] == [0, 1, 2]
|
||||
|
||||
|
||||
def test_reorder_mealplans_across_days(api_client: TestClient, unique_user: TestUser):
|
||||
start_date = datetime.now(UTC).date() + timedelta(days=20)
|
||||
next_date = start_date + timedelta(days=1)
|
||||
|
||||
def create_entry(entry_date, title):
|
||||
response = api_client.post(
|
||||
api_routes.households_mealplans,
|
||||
headers=unique_user.token,
|
||||
json={"date": entry_date.isoformat(), "title": title},
|
||||
)
|
||||
assert response.status_code == 201
|
||||
return response.json()
|
||||
|
||||
remaining_source = create_entry(start_date, "Remaining source entry")
|
||||
moved = create_entry(start_date, "Moved entry")
|
||||
existing_destination = create_entry(next_date, "Existing destination entry")
|
||||
|
||||
response = api_client.put(
|
||||
f"{api_routes.households_mealplans}/reorder",
|
||||
headers=unique_user.token,
|
||||
json=[
|
||||
{"date": start_date.isoformat(), "entryIds": [remaining_source["id"]]},
|
||||
{"date": next_date.isoformat(), "entryIds": [existing_destination["id"], moved["id"]]},
|
||||
],
|
||||
)
|
||||
assert response.status_code == 204
|
||||
|
||||
response = api_client.get(
|
||||
route_all_slice(1, -1, start_date.isoformat(), next_date.isoformat()),
|
||||
headers=unique_user.token,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
items = response.json()["items"]
|
||||
source_items = [item for item in items if item["date"] == start_date.isoformat()]
|
||||
destination_items = [item for item in items if item["date"] == next_date.isoformat()]
|
||||
|
||||
assert [item["id"] for item in source_items] == [remaining_source["id"]]
|
||||
assert [item["position"] for item in source_items] == [0]
|
||||
assert [item["id"] for item in destination_items] == [existing_destination["id"], moved["id"]]
|
||||
assert [item["position"] for item in destination_items] == [0, 1]
|
||||
|
||||
|
||||
def test_reorder_mealplans_within_week(api_client: TestClient, unique_user: TestUser):
|
||||
week_start = datetime.now(UTC).date()
|
||||
week_end = week_start + timedelta(days=6)
|
||||
first = create_entry(api_client, unique_user, date=week_start, end_date=week_end, title="First")
|
||||
second = create_entry(api_client, unique_user, date=week_start, end_date=week_end, title="Second")
|
||||
third = create_entry(api_client, unique_user, date=week_start, end_date=week_end, title="Third")
|
||||
|
||||
response = api_client.put(
|
||||
f"{api_routes.households_mealplans}/reorder",
|
||||
headers=unique_user.token,
|
||||
json=[
|
||||
{
|
||||
"date": week_start.isoformat(),
|
||||
"endDate": week_end.isoformat(),
|
||||
"entryIds": [third["id"], first["id"], second["id"]],
|
||||
}
|
||||
],
|
||||
)
|
||||
assert response.status_code == 204
|
||||
|
||||
response = api_client.get(
|
||||
api_routes.households_mealplans,
|
||||
headers=unique_user.token,
|
||||
params={"page": 1, "perPage": -1, "start_date": week_start, "end_date": week_end, "include_week_entries": True},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
week_entries = [entry for entry in response.json()["items"] if entry["endDate"]]
|
||||
assert [entry["id"] for entry in week_entries] == [third["id"], first["id"], second["id"]]
|
||||
assert [entry["position"] for entry in week_entries] == [0, 1, 2]
|
||||
|
||||
|
||||
def test_append_mealplan_to_week(api_client: TestClient, unique_user: TestUser):
|
||||
week_start = datetime.now(UTC).date() + timedelta(days=31)
|
||||
week_end = week_start + timedelta(days=6)
|
||||
first = create_entry(api_client, unique_user, date=week_start, end_date=week_end, title="First")
|
||||
second = create_entry(api_client, unique_user, date=week_start, end_date=week_end, title="Second")
|
||||
|
||||
appended = create_entry(api_client, unique_user, date=week_start, end_date=week_end, title="Appended")
|
||||
assert [first["position"], second["position"], appended["position"]] == [0, 1, 2]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("destination_is_week", [False, True])
|
||||
# runs twice, once moving a day entry into a week list and vice-versa
|
||||
def test_reorder_mealplans_between_day_and_week(
|
||||
api_client: TestClient, unique_user: TestUser, destination_is_week: bool
|
||||
):
|
||||
# this module shares a household across tests. Use a distinct date so reruns
|
||||
# don't leave entries in the buckets that would invalidate a full reorder.
|
||||
week_start = datetime.now(UTC).date() + timedelta(days=random.randint(100, 10_000))
|
||||
week_end = week_start + timedelta(days=6)
|
||||
day_entry = create_entry(api_client, unique_user, date=week_start, title="Day entry")
|
||||
week_entry = create_entry(api_client, unique_user, date=week_start, end_date=week_end, title="Week entry")
|
||||
|
||||
if destination_is_week:
|
||||
reorder_buckets = [
|
||||
{"date": week_start.isoformat(), "endDate": None, "entryIds": []},
|
||||
{
|
||||
"date": week_start.isoformat(),
|
||||
"endDate": week_end.isoformat(),
|
||||
"entryIds": [week_entry["id"], day_entry["id"]],
|
||||
},
|
||||
]
|
||||
expected_day_ids, expected_week_ids = [], [week_entry["id"], day_entry["id"]]
|
||||
else:
|
||||
reorder_buckets = [
|
||||
{"date": week_start.isoformat(), "endDate": week_end.isoformat(), "entryIds": []},
|
||||
{"date": week_start.isoformat(), "endDate": None, "entryIds": [day_entry["id"], week_entry["id"]]},
|
||||
]
|
||||
expected_day_ids, expected_week_ids = [day_entry["id"], week_entry["id"]], []
|
||||
|
||||
response = api_client.put(
|
||||
f"{api_routes.households_mealplans}/reorder", headers=unique_user.token, json=reorder_buckets
|
||||
)
|
||||
assert response.status_code == 204
|
||||
|
||||
response = api_client.get(
|
||||
api_routes.households_mealplans,
|
||||
headers=unique_user.token,
|
||||
params={"page": 1, "perPage": -1, "start_date": week_start, "end_date": week_end, "include_week_entries": True},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
entries = response.json()["items"]
|
||||
day_entries = [entry for entry in entries if entry["date"] == week_start.isoformat() and entry["endDate"] is None]
|
||||
week_entries = [entry for entry in entries if entry["endDate"] is not None]
|
||||
assert [entry["id"] for entry in day_entries] == expected_day_ids
|
||||
assert [entry["id"] for entry in week_entries] == expected_week_ids
|
||||
|
||||
|
||||
@pytest.mark.parametrize("destination_is_week", [False, True])
|
||||
def test_update_mealplan_between_day_and_week(api_client: TestClient, unique_user: TestUser, destination_is_week: bool):
|
||||
week_start = datetime.now(UTC).date() + timedelta(days=42)
|
||||
week_end = week_start + timedelta(days=6)
|
||||
meal = create_entry(
|
||||
api_client,
|
||||
unique_user,
|
||||
date=week_start,
|
||||
**({} if destination_is_week else {"end_date": week_end}),
|
||||
title="Moved meal",
|
||||
)
|
||||
payload = {**meal, "endDate": week_end.isoformat()} if destination_is_week else {**meal, "endDate": None}
|
||||
|
||||
response = api_client.put(
|
||||
api_routes.households_mealplans_item_id(meal["id"]),
|
||||
headers=unique_user.token,
|
||||
json=payload,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["endDate"] == (week_end.isoformat() if destination_is_week else None)
|
||||
|
||||
|
||||
def test_update_mealplan_between_weeks(api_client: TestClient, unique_user: TestUser):
|
||||
source_week = datetime.now(UTC).date() + timedelta(days=10)
|
||||
destination_week = source_week + timedelta(days=7)
|
||||
source_week_end = source_week + timedelta(days=6)
|
||||
destination_week_end = destination_week + timedelta(days=6)
|
||||
moved = create_entry(api_client, unique_user, date=source_week, end_date=source_week_end, title="Moved week entry")
|
||||
remaining = create_entry(
|
||||
api_client, unique_user, date=source_week, end_date=source_week_end, title="Remaining week entry"
|
||||
)
|
||||
|
||||
response = api_client.put(
|
||||
api_routes.households_mealplans_item_id(moved["id"]),
|
||||
headers=unique_user.token,
|
||||
json={**moved, "date": destination_week.isoformat(), "endDate": destination_week_end.isoformat()},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
response = api_client.get(
|
||||
api_routes.households_mealplans,
|
||||
headers=unique_user.token,
|
||||
params={
|
||||
"page": 1,
|
||||
"perPage": -1,
|
||||
"start_date": source_week,
|
||||
"end_date": destination_week_end,
|
||||
"include_week_entries": True,
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
entries = response.json()["items"]
|
||||
source_entries = [entry for entry in entries if entry["date"] == source_week.isoformat() and entry["endDate"]]
|
||||
destination_entries = [entry for entry in entries if entry["date"] == destination_week.isoformat()]
|
||||
assert [entry["id"] for entry in source_entries] == [remaining["id"]]
|
||||
assert source_entries[0]["position"] == 0
|
||||
assert [entry["id"] for entry in destination_entries] == [moved["id"]]
|
||||
assert destination_entries[0]["position"] == 0
|
||||
|
||||
|
||||
def test_update_mealplan_date_inserts_by_type(api_client: TestClient, unique_user: TestUser):
|
||||
start_date = datetime.now(UTC).date() + timedelta(days=12)
|
||||
destination_date = start_date + timedelta(days=1)
|
||||
|
||||
def create_entry(entry_date, title, entry_type):
|
||||
response = api_client.post(
|
||||
api_routes.households_mealplans,
|
||||
headers=unique_user.token,
|
||||
json={"date": entry_date.isoformat(), "title": title, "entryType": entry_type},
|
||||
)
|
||||
assert response.status_code == 201
|
||||
return response.json()
|
||||
|
||||
moved = create_entry(start_date, "Moved", "lunch")
|
||||
remaining_source = create_entry(start_date, "Remaining source", "dinner")
|
||||
first_destination = create_entry(destination_date, "Destination first", "breakfast")
|
||||
second_destination = create_entry(destination_date, "Destination second", "dinner")
|
||||
|
||||
response = api_client.put(
|
||||
api_routes.households_mealplans_item_id(moved["id"]),
|
||||
headers=unique_user.token,
|
||||
json={**moved, "date": destination_date.isoformat()},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
response = api_client.get(
|
||||
route_all_slice(1, -1, destination_date.isoformat(), destination_date.isoformat()),
|
||||
headers=unique_user.token,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
entries = response.json()["items"]
|
||||
assert [entry["id"] for entry in entries] == [first_destination["id"], moved["id"], second_destination["id"]]
|
||||
assert [entry["position"] for entry in entries] == [0, 1, 2]
|
||||
|
||||
source_response = api_client.get(
|
||||
route_all_slice(1, -1, start_date.isoformat(), start_date.isoformat()),
|
||||
headers=unique_user.token,
|
||||
)
|
||||
assert source_response.status_code == 200
|
||||
source_entries = source_response.json()["items"]
|
||||
assert [entry["id"] for entry in source_entries] == [remaining_source["id"]]
|
||||
assert [entry["position"] for entry in source_entries] == [0]
|
||||
|
||||
|
||||
def test_mealplan_ordering_query_parameters(api_client: TestClient, unique_user: TestUser) -> None:
|
||||
day = datetime.now(UTC).date() + timedelta(days=50)
|
||||
for offset, title in [(0, "B"), (0, "A"), (1, "D"), (1, "C")]:
|
||||
response = api_client.post(
|
||||
api_routes.households_mealplans,
|
||||
headers=unique_user.token,
|
||||
json={"date": (day + timedelta(days=offset)).isoformat(), "title": title},
|
||||
)
|
||||
assert response.status_code == 201
|
||||
|
||||
cases = [
|
||||
({}, ["B", "A", "D", "C"]),
|
||||
({"orderDirection": "asc"}, ["B", "A", "D", "C"]),
|
||||
({"orderDirection": "desc"}, ["C", "D", "A", "B"]),
|
||||
({"orderBy": "title"}, ["D", "C", "B", "A"]),
|
||||
({"orderBy": "title", "orderDirection": "asc"}, ["A", "B", "C", "D"]),
|
||||
({"orderBy": "date:asc,position", "orderDirection": "desc"}, ["A", "B", "C", "D"]),
|
||||
]
|
||||
for ordering, expected_titles in cases:
|
||||
response = api_client.get(
|
||||
api_routes.households_mealplans,
|
||||
headers=unique_user.token,
|
||||
params={
|
||||
"start_date": day.isoformat(),
|
||||
"end_date": (day + timedelta(days=1)).isoformat(),
|
||||
**ordering,
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert [entry["title"] for entry in response.json()["items"]] == expected_titles
|
||||
|
||||
|
||||
def test_mealplan_type_insertion_preserves_manual_order(api_client: TestClient, unique_user: TestUser):
|
||||
day = (datetime.now(UTC).date() + timedelta(days=40)).isoformat()
|
||||
|
||||
def create(entry_type: str) -> dict:
|
||||
response = api_client.post(
|
||||
api_routes.households_mealplans,
|
||||
headers=unique_user.token,
|
||||
json={"date": day, "title": entry_type, "entryType": entry_type},
|
||||
)
|
||||
assert response.status_code == 201
|
||||
return response.json()
|
||||
|
||||
def entries() -> list[dict]:
|
||||
response = api_client.get(route_all_slice(1, -1, day, day), headers=unique_user.token)
|
||||
assert response.status_code == 200
|
||||
return response.json()["items"]
|
||||
|
||||
dinner = create("dinner")
|
||||
breakfast = create("breakfast")
|
||||
lunch = create("lunch")
|
||||
assert [entry["id"] for entry in entries()] == [breakfast["id"], lunch["id"], dinner["id"]]
|
||||
assert [entry["position"] for entry in entries()] == [0, 1, 2]
|
||||
|
||||
response = api_client.put(
|
||||
f"{api_routes.households_mealplans}/reorder",
|
||||
headers=unique_user.token,
|
||||
json=[{"date": day, "entryIds": [dinner["id"], breakfast["id"], lunch["id"]]}],
|
||||
)
|
||||
assert response.status_code == 204
|
||||
another_dinner = create("dinner")
|
||||
assert [entry["id"] for entry in entries()] == [dinner["id"], another_dinner["id"], breakfast["id"], lunch["id"]]
|
||||
assert [entry["position"] for entry in entries()] == [0, 1, 2, 3]
|
||||
|
||||
|
||||
def test_get_slice_mealplans(api_client: TestClient, unique_user: TestUser):
|
||||
# Make List of 10 dates from now to +10 days
|
||||
dates = [datetime.now(UTC).date() + timedelta(days=x) for x in range(10)]
|
||||
@@ -327,7 +660,8 @@ def test_get_mealplan_today(api_client: TestClient, unique_user: TestUser):
|
||||
|
||||
|
||||
def create_entry(api_client: TestClient, unique_user: TestUser, **kwargs) -> dict:
|
||||
data = PlanEntryCreate(entry_type="dinner", title=random_string(), **kwargs).model_dump(by_alias=True, mode="json")
|
||||
kwargs.setdefault("title", random_string())
|
||||
data = PlanEntryCreate(entry_type="dinner", **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()
|
||||
|
||||
@@ -111,6 +111,8 @@ households_mealplans_ical = "/api/households/mealplans/ical"
|
||||
"""`/api/households/mealplans/ical`"""
|
||||
households_mealplans_random = "/api/households/mealplans/random"
|
||||
"""`/api/households/mealplans/random`"""
|
||||
households_mealplans_reorder = "/api/households/mealplans/reorder"
|
||||
"""`/api/households/mealplans/reorder`"""
|
||||
households_mealplans_rules = "/api/households/mealplans/rules"
|
||||
"""`/api/households/mealplans/rules`"""
|
||||
households_mealplans_today = "/api/households/mealplans/today"
|
||||
|
||||
Reference in new issue
Block a user