1
0
Fork 0
mirror of https://github.com/mealie-recipes/mealie.git synced 2025-08-07 14:35:25 +02:00

feat: Add Households to Mealie (#3970)

This commit is contained in:
Michael Genson 2024-08-22 10:14:32 -05:00 committed by GitHub
parent 0c29cef17d
commit eb170cc7e5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
315 changed files with 6975 additions and 3577 deletions

View file

@ -0,0 +1,181 @@
<template>
<v-container>
<v-menu
v-model="state.picker"
:close-on-content-click="false"
transition="scale-transition"
offset-y
max-width="290px"
min-width="auto"
>
<template #activator="{ on, attrs }">
<v-btn color="primary" class="mb-2" v-bind="attrs" v-on="on">
<v-icon left>
{{ $globals.icons.calendar }}
</v-icon>
{{ $d(weekRange.start, "short") }} - {{ $d(weekRange.end, "short") }}
</v-btn>
</template>
<v-date-picker
v-model="state.range"
no-title
range
:first-day-of-week="firstDayOfWeek"
:local="$i18n.locale"
>
<v-text-field
v-model="numberOfDays"
type="number"
:label="$t('meal-plan.numberOfDays-label')"
:hint="$t('meal-plan.numberOfDays-hint')"
persistent-hint
/>
<v-spacer></v-spacer>
<v-btn text color="primary" @click="state.picker = false">
{{ $t("general.ok") }}
</v-btn>
</v-date-picker>
</v-menu>
<div class="d-flex flex-wrap align-center justify-space-between mb-2">
<v-tabs style="width: fit-content;">
<v-tab :to="`/household/mealplan/planner/view`">{{ $t('meal-plan.meal-planner') }}</v-tab>
<v-tab :to="`/household/mealplan/planner/edit`">{{ $t('general.edit') }}</v-tab>
</v-tabs>
<ButtonLink :icon="$globals.icons.calendar" :to="`/household/mealplan/settings`" :text="$tc('general.settings')" />
</div>
<div>
<NuxtChild :mealplans="mealsByDate" :actions="actions" />
</div>
<v-row> </v-row>
</v-container>
</template>
<script lang="ts">
import { computed, defineComponent, ref, useRoute, useRouter, watch } from "@nuxtjs/composition-api";
import { isSameDay, addDays, parseISO } from "date-fns";
import { useHouseholdSelf } from "~/composables/use-households";
import { useMealplans } from "~/composables/use-group-mealplan";
import { useUserMealPlanPreferences } from "~/composables/use-users/preferences";
export default defineComponent({
middleware: ["auth"],
setup() {
const route = useRoute();
const router = useRouter();
const { household } = useHouseholdSelf();
const mealPlanPreferences = useUserMealPlanPreferences();
const numberOfDays = ref<number>(mealPlanPreferences.value.numberOfDays || 7);
watch(numberOfDays, (val) => {
mealPlanPreferences.value.numberOfDays = Number(val);
});
// Force to /view if current route is /planner
if (route.value.path === "/household/mealplan/planner") {
router.push("/household/mealplan/planner/view");
}
function fmtYYYYMMDD(date: Date) {
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}
function parseYYYYMMDD(date: string) {
const [year, month, day] = date.split("-");
return new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
}
const state = ref({
range: [fmtYYYYMMDD(new Date()), fmtYYYYMMDD(addDays(new Date(), adjustForToday(numberOfDays.value)))] as [string, string],
start: new Date(),
picker: false,
end: addDays(new Date(), adjustForToday(numberOfDays.value)),
});
const firstDayOfWeek = computed(() => {
return household.value?.preferences?.firstDayOfWeek || 0;
});
const weekRange = computed(() => {
const sorted = state.value.range.sort((a, b) => {
return parseYYYYMMDD(a).getTime() - parseYYYYMMDD(b).getTime();
});
if (sorted.length === 2) {
return {
start: parseYYYYMMDD(sorted[0]),
end: parseYYYYMMDD(sorted[1]),
};
}
return {
start: new Date(),
end: addDays(new Date(), adjustForToday(numberOfDays.value)),
};
});
const { mealplans, actions } = useMealplans(weekRange);
function filterMealByDate(date: Date) {
if (!mealplans.value) return [];
return mealplans.value.filter((meal) => {
const mealDate = parseISO(meal.date);
return isSameDay(mealDate, date);
});
}
function adjustForToday(days: number) {
// The use case for this function is "how many days are we adding to 'today'?"
// e.g. If the user wants 7 days, we substract one to do "today + 6"
return days > 0 ? days - 1 : days + 1
}
const days = computed(() => {
const numDays =
Math.floor((weekRange.value.end.getTime() - weekRange.value.start.getTime()) / (1000 * 60 * 60 * 24)) + 1;
// Calculate absolute value
if (numDays < 0) return [];
return Array.from(Array(numDays).keys()).map(
(i) => {
const date = new Date(weekRange.value.start.getTime());
date.setDate(date.getDate() + i);
return date;
}
);
});
const mealsByDate = computed(() => {
return days.value.map((day) => {
return { date: day, meals: filterMealByDate(day) };
});
});
return {
state,
actions,
mealsByDate,
weekRange,
firstDayOfWeek,
numberOfDays,
};
},
head() {
return {
title: this.$t("meal-plan.dinner-this-week") as string,
};
},
});
</script>
<style lang="css">
.left-color-border {
border-left: 5px solid var(--v-primary-base) !important;
}
.bottom-color-border {
border-bottom: 2px solid var(--v-primary-base) !important;
}
</style>

View file

@ -0,0 +1,386 @@
<template>
<div>
<!-- Create Meal Dialog -->
<BaseDialog
v-model="state.dialog"
:title="$tc(newMeal.existing
? 'meal-plan.update-this-meal-plan'
: 'meal-plan.create-a-new-meal-plan'
)"
:submit-text="$tc(newMeal.existing
? 'general.update'
: 'general.create'
)"
color="primary"
:icon="$globals.icons.foods"
@submit="
if (newMeal.existing) {
actions.updateOne(newMeal);
} else {
actions.createOne(newMeal);
}
resetDialog();
"
@close="resetDialog()"
>
<v-card-text>
<v-menu
v-model="state.pickerMenu"
:close-on-content-click="false"
transition="scale-transition"
offset-y
max-width="290px"
min-width="auto"
>
<template #activator="{ on, attrs }">
<v-text-field
v-model="newMeal.date"
:label="$t('general.date')"
:hint="$t('recipe.date-format-hint-yyyy-mm-dd')"
persistent-hint
:prepend-icon="$globals.icons.calendar"
v-bind="attrs"
readonly
v-on="on"
/>
</template>
<v-date-picker
v-model="newMeal.date"
no-title
:first-day-of-week="firstDayOfWeek"
:local="$i18n.locale"
@input="state.pickerMenu = false"
/>
</v-menu>
<v-card-text>
<v-select
v-model="newMeal.entryType"
:return-object="false"
:items="planTypeOptions"
:label="$t('recipe.entry-type')"
/>
<v-autocomplete
v-if="!dialog.note"
v-model="newMeal.recipeId"
:label="$t('meal-plan.meal-recipe')"
:items="search.data.value"
:loading="search.loading.value"
:search-input.sync="search.query.value"
cache-items
item-text="name"
item-value="id"
:return-object="false"
/>
<template v-else>
<v-text-field v-model="newMeal.title" :label="$t('meal-plan.meal-title')" />
<v-textarea v-model="newMeal.text" rows="2" :label="$t('meal-plan.meal-note')" />
</template>
</v-card-text>
<v-card-actions class="my-0 py-0">
<v-switch v-model="dialog.note" class="mt-n3" :label="$t('meal-plan.note-only')" />
</v-card-actions>
</v-card-text>
</BaseDialog>
<v-row>
<v-col
v-for="(plan, index) in mealplans"
:key="index"
cols="12"
sm="12"
md="3"
lg="3"
xl="2"
class="col-borders my-1 d-flex flex-column"
>
<v-card class="mb-2 border-left-primary rounded-sm pa-2">
<p class="pl-2 mb-1">
{{ $d(plan.date, "short") }}
</p>
</v-card>
<draggable
tag="div"
handle=".handle"
:value="plan.meals"
group="meals"
:data-index="index"
:data-box="plan.date"
style="min-height: 150px"
@end="onMoveCallback"
>
<v-card
v-for="mealplan in plan.meals"
:key="mealplan.id"
class="my-1"
:class="{ handle: $vuetify.breakpoint.smAndUp }"
>
<v-list-item
@click="editMeal(mealplan)"
>
<v-list-item-avatar :rounded="false">
<RecipeCardImage
v-if="mealplan.recipe"
:recipe-id="mealplan.recipe.id"
tiny
icon-size="25"
:slug="mealplan.recipe ? mealplan.recipe.slug : ''"
>
</RecipeCardImage>
<v-icon v-else>
{{ $globals.icons.primary }}
</v-icon>
</v-list-item-avatar>
<v-list-item-content>
<v-list-item-title class="mb-1">
{{ mealplan.recipe ? mealplan.recipe.name : mealplan.title }}
</v-list-item-title>
<v-list-item-subtitle style="min-height: 16px">
{{ mealplan.recipe ? mealplan.recipe.description + " " : mealplan.text }}
</v-list-item-subtitle>
</v-list-item-content>
</v-list-item>
<v-divider class="mx-2"></v-divider>
<div class="py-2 px-2 d-flex" style="align-items: center">
<v-btn small icon :class="{ handle: !$vuetify.breakpoint.smAndUp }">
<v-icon>
{{ $globals.icons.arrowUpDown }}
</v-icon>
</v-btn>
<v-menu offset-y>
<template #activator="{ on, attrs }">
<v-chip v-bind="attrs" label small color="accent" v-on="on" @click.prevent>
<v-icon left>
{{ $globals.icons.tags }}
</v-icon>
{{ getEntryTypeText(mealplan.entryType) }}
</v-chip>
</template>
<v-list>
<v-list-item
v-for="mealType in planTypeOptions"
:key="mealType.value"
@click="actions.setType(mealplan, mealType.value)"
>
<v-list-item-title> {{ mealType.text }} </v-list-item-title>
</v-list-item>
</v-list>
</v-menu>
<v-btn class="ml-auto" small icon @click="actions.deleteOne(mealplan.id)">
<v-icon>{{ $globals.icons.delete }}</v-icon>
</v-btn>
</div>
</v-card>
</draggable>
<!-- Day Column Actions -->
<div class="d-flex justify-end mt-auto">
<BaseButtonGroup
:buttons="[
{
icon: $globals.icons.diceMultiple,
text: $tc('meal-plan.random-meal'),
event: 'random',
children: [
{
icon: $globals.icons.diceMultiple,
text: $tc('meal-plan.breakfast'),
event: 'randomBreakfast',
},
{
icon: $globals.icons.diceMultiple,
text: $tc('meal-plan.lunch'),
event: 'randomLunch',
},
],
},
{
icon: $globals.icons.potSteam,
text: $tc('meal-plan.random-dinner'),
event: 'randomDinner',
},
{
icon: $globals.icons.bowlMixOutline,
text: $tc('meal-plan.random-side'),
event: 'randomSide',
},
{
icon: $globals.icons.createAlt,
text: $tc('general.new'),
event: 'create',
},
]"
@create="openDialog(plan.date)"
@randomBreakfast="randomMeal(plan.date, 'breakfast')"
@randomLunch="randomMeal(plan.date, 'lunch')"
@randomDinner="randomMeal(plan.date, 'dinner')"
@randomSide="randomMeal(plan.date, 'side')"
/>
</div>
</v-col>
</v-row>
</div>
</template>
<script lang="ts">
import { defineComponent, computed, reactive, ref, watch, onMounted } from "@nuxtjs/composition-api";
import { format } from "date-fns";
import { SortableEvent } from "sortablejs";
import draggable from "vuedraggable";
import { MealsByDate } from "./types";
import { useMealplans, usePlanTypeOptions, getEntryTypeText } from "~/composables/use-group-mealplan";
import RecipeCardImage from "~/components/Domain/Recipe/RecipeCardImage.vue";
import { PlanEntryType, UpdatePlanEntry } from "~/lib/api/types/meal-plan";
import { useUserApi } from "~/composables/api";
import { useHouseholdSelf } from "~/composables/use-households";
import { useRecipeSearch } from "~/composables/recipes/use-recipe-search";
export default defineComponent({
components: {
draggable,
RecipeCardImage,
},
props: {
mealplans: {
type: Array as () => MealsByDate[],
required: true,
},
actions: {
type: Object as () => ReturnType<typeof useMealplans>["actions"],
required: true,
},
},
setup(props) {
const api = useUserApi();
const { household } = useHouseholdSelf();
const state = ref({
dialog: false,
pickerMenu: null as null | boolean,
});
const firstDayOfWeek = computed(() => {
return household.value?.preferences?.firstDayOfWeek || 0;
});
function onMoveCallback(evt: SortableEvent) {
const supportedEvents = ["drop", "touchend"];
// Adapted From https://github.com/SortableJS/Vue.Draggable/issues/1029
const ogEvent: DragEvent = (evt as any).originalEvent;
if (ogEvent && ogEvent.type in supportedEvents) {
// The drop was cancelled, unsure if anything needs to be done?
console.log("Cancel Move Event");
} else {
// A Meal was moved, set the new date value and make an update request and refresh the meals
const fromMealsByIndex = parseInt(evt.from.getAttribute("data-index") ?? "");
const toMealsByIndex = parseInt(evt.to.getAttribute("data-index") ?? "");
if (!isNaN(fromMealsByIndex) && !isNaN(toMealsByIndex)) {
const mealData = props.mealplans[fromMealsByIndex].meals[evt.oldIndex as number];
const destDate = props.mealplans[toMealsByIndex].date;
mealData.date = format(destDate, "yyyy-MM-dd");
props.actions.updateOne(mealData);
}
}
}
// =====================================================
// New Meal Dialog
const dialog = reactive({
loading: false,
error: false,
note: false,
});
watch(dialog, () => {
if (dialog.note) {
newMeal.recipeId = undefined;
}
});
const newMeal = reactive({
date: "",
title: "",
text: "",
recipeId: undefined as string | undefined,
entryType: "dinner" as PlanEntryType,
existing: false,
id: 0,
groupId: "",
});
function openDialog(date: Date) {
newMeal.date = format(date, "yyyy-MM-dd");
state.value.dialog = true;
}
function editMeal(mealplan: UpdatePlanEntry) {
const { date, title, text, entryType, recipeId, id, groupId } = mealplan;
if (!entryType) return;
newMeal.date = date;
newMeal.title = title || "";
newMeal.text = text || "";
newMeal.recipeId = recipeId;
newMeal.entryType = entryType;
newMeal.existing = true;
newMeal.id = id;
newMeal.groupId = groupId;
state.value.dialog = true;
dialog.note = !recipeId;
}
function resetDialog() {
newMeal.date = "";
newMeal.title = "";
newMeal.text = "";
newMeal.entryType = "dinner";
newMeal.recipeId = undefined;
newMeal.existing = false;
}
async function randomMeal(date: Date, type: PlanEntryType) {
const { data } = await api.mealplans.setRandom({
date: format(date, "yyyy-MM-dd"),
entryType: type,
});
if (data) {
props.actions.refreshAll();
}
}
// =====================================================
// Search
const search = useRecipeSearch(api);
const planTypeOptions = usePlanTypeOptions();
onMounted(async () => {
await search.trigger();
});
return {
state,
onMoveCallback,
planTypeOptions,
getEntryTypeText,
// Dialog
dialog,
newMeal,
openDialog,
editMeal,
resetDialog,
randomMeal,
// Search
search,
firstDayOfWeek,
};
},
});
</script>

View file

@ -0,0 +1,6 @@
import { ReadPlanEntry } from "~/lib/api/types/meal-plan";
export type MealsByDate = {
date: Date;
meals: ReadPlanEntry[]
}

View file

@ -0,0 +1,129 @@
<template>
<v-container class="mx-0 my-3 pa">
<v-row>
<v-col
v-for="(day, index) in plan"
:key="index"
cols="12"
sm="12"
md="4"
lg="4"
xl="2"
class="col-borders my-1 d-flex flex-column"
>
<v-card class="mb-2 border-left-primary rounded-sm px-2">
<v-container class="px-0">
<v-row no-gutters style="width: 100%;">
<v-col cols="10">
<p class="pl-2 my-1">
{{ $d(day.date, "short") }}
</p>
</v-col>
<v-col class="d-flex justify-top" cols="2">
<GroupMealPlanDayContextMenu v-if="day.recipes.length" :recipes="day.recipes" />
</v-col>
</v-row>
</v-container>
</v-card>
<div v-for="section in day.sections" :key="section.title">
<div class="py-2 d-flex flex-column">
<div class="primary" style="width: 50px; height: 2.5px"></div>
<p class="text-overline my-0">
{{ section.title }}
</p>
</div>
<RecipeCardMobile
v-for="mealplan in section.meals"
:key="mealplan.id"
:recipe-id="mealplan.recipe ? mealplan.recipe.id : ''"
class="mb-2"
: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"
:tags="mealplan.recipe ? mealplan.recipe.tags : []"
/>
</div>
</v-col>
</v-row>
</v-container>
</template>
<script lang="ts">
import { computed, defineComponent, useContext } from "@nuxtjs/composition-api";
import { MealsByDate } from "./types";
import { ReadPlanEntry } from "~/lib/api/types/meal-plan";
import GroupMealPlanDayContextMenu from "~/components/Domain/Household/GroupMealPlanDayContextMenu.vue";
import RecipeCardMobile from "~/components/Domain/Recipe/RecipeCardMobile.vue";
import { RecipeSummary } from "~/lib/api/types/recipe";
export default defineComponent({
components: {
GroupMealPlanDayContextMenu,
RecipeCardMobile,
},
props: {
mealplans: {
type: Array as () => MealsByDate[],
required: true,
},
},
setup(props) {
type DaySection = {
title: string;
meals: ReadPlanEntry[];
};
type Days = {
date: Date;
sections: DaySection[];
recipes: RecipeSummary[];
};
const { i18n } = useContext();
const plan = computed<Days[]>(() => {
return props.mealplans.reduce((acc, day) => {
const out: Days = {
date: day.date,
sections: [
{ title: i18n.tc("meal-plan.breakfast"), meals: [] },
{ title: i18n.tc("meal-plan.lunch"), meals: [] },
{ title: i18n.tc("meal-plan.dinner"), meals: [] },
{ title: i18n.tc("meal-plan.side"), meals: [] },
],
recipes: [],
};
for (const meal of day.meals) {
if (meal.entryType === "breakfast") {
out.sections[0].meals.push(meal);
} else if (meal.entryType === "lunch") {
out.sections[1].meals.push(meal);
} else if (meal.entryType === "dinner") {
out.sections[2].meals.push(meal);
} else if (meal.entryType === "side") {
out.sections[3].meals.push(meal);
}
if (meal.recipe) {
out.recipes.push(meal.recipe);
}
}
// Drop empty sections
out.sections = out.sections.filter((section) => section.meals.length > 0);
acc.push(out);
return acc;
}, [] as Days[]);
});
return {
plan,
};
},
});
</script>

View file

@ -0,0 +1,187 @@
<template>
<v-container class="md-container">
<BasePageTitle divider>
<template #header>
<v-img max-height="100" max-width="100" :src="require('~/static/svgs/manage-cookbooks.svg')"></v-img>
</template>
<template #title> {{ $t('meal-plan.meal-plan-rules') }} </template>
{{ $t('meal-plan.meal-plan-rules-description') }}
</BasePageTitle>
<v-card>
<v-card-title class="headline"> {{ $t('meal-plan.new-rule') }} </v-card-title>
<v-divider class="mx-2"></v-divider>
<v-card-text>
{{ $t('meal-plan.new-rule-description') }}
<GroupMealPlanRuleForm
class="mt-2"
:day.sync="createData.day"
:entry-type.sync="createData.entryType"
:categories.sync="createData.categories"
:tags.sync="createData.tags"
/>
</v-card-text>
<v-card-actions class="justify-end">
<BaseButton create @click="createRule" />
</v-card-actions>
</v-card>
<section>
<BaseCardSectionTitle class="mt-10" :title="$tc('meal-plan.recipe-rules')" />
<div>
<div v-for="(rule, idx) in allRules" :key="rule.id">
<v-card class="my-2 left-border">
<v-card-title class="headline pb-1">
{{ rule.day === "unset" ? $t('meal-plan.applies-to-all-days') : $t('meal-plan.applies-on-days', [rule.day]) }}
{{ rule.entryType === "unset" ? $t('meal-plan.for-all-meal-types') : $t('meal-plan.for-type-meal-types', [rule.entryType]) }}
<span class="ml-auto">
<BaseButtonGroup
:buttons="[
{
icon: $globals.icons.edit,
text: $tc('general.edit'),
event: 'edit',
},
{
icon: $globals.icons.delete,
text: $tc('general.delete'),
event: 'delete',
},
]"
@delete="deleteRule(rule.id)"
@edit="toggleEditState(rule.id)"
/>
</span>
</v-card-title>
<v-card-text>
<template v-if="!editState[rule.id]">
<div v-if="rule.categories">
<h4 class="py-1">{{ $t("category.categories") }}:</h4>
<RecipeChips :items="rule.categories" small />
</div>
<div v-if="rule.tags">
<h4 class="py-1">{{ $t("tag.tags") }}:</h4>
<RecipeChips :items="rule.tags" url-prefix="tags" small />
</div>
</template>
<template v-else>
<GroupMealPlanRuleForm
:day.sync="allRules[idx].day"
:entry-type.sync="allRules[idx].entryType"
:categories.sync="allRules[idx].categories"
:tags.sync="allRules[idx].tags"
/>
<div class="d-flex justify-end">
<BaseButton update @click="updateRule(rule)" />
</div>
</template>
</v-card-text>
</v-card>
</div>
</div>
</section>
</v-container>
</template>
<script lang="ts">
import { defineComponent, ref, useAsync } from "@nuxtjs/composition-api";
import { useUserApi } from "~/composables/api";
import { PlanRulesCreate, PlanRulesOut } from "~/lib/api/types/meal-plan";
import GroupMealPlanRuleForm from "~/components/Domain/Household/GroupMealPlanRuleForm.vue";
import { useAsyncKey } from "~/composables/use-utils";
import RecipeChips from "~/components/Domain/Recipe/RecipeChips.vue";
export default defineComponent({
components: {
GroupMealPlanRuleForm,
RecipeChips,
},
middleware: ["auth"],
props: {
value: {
type: Boolean,
default: false,
},
},
setup() {
const api = useUserApi();
// ======================================================
// Manage All
const editState = ref<{ [key: string]: boolean }>({});
const allRules = ref<PlanRulesOut[]>([]);
function toggleEditState(id: string) {
editState.value[id] = !editState.value[id];
editState.value = { ...editState.value };
}
async function refreshAll() {
const { data } = await api.mealplanRules.getAll();
if (data) {
allRules.value = data.items ?? [];
}
}
useAsync(async () => {
await refreshAll();
}, useAsyncKey());
// ======================================================
// Creating Rules
const createData = ref<PlanRulesCreate>({
entryType: "unset",
day: "unset",
categories: [],
tags: [],
});
async function createRule() {
const { data } = await api.mealplanRules.createOne(createData.value);
if (data) {
refreshAll();
createData.value = {
entryType: "unset",
day: "unset",
categories: [],
tags: [],
};
}
}
async function deleteRule(ruleId: string) {
const { data } = await api.mealplanRules.deleteOne(ruleId);
if (data) {
refreshAll();
}
}
async function updateRule(rule: PlanRulesOut) {
const { data } = await api.mealplanRules.updateOne(rule.id, rule);
if (data) {
refreshAll();
toggleEditState(rule.id);
}
}
return {
allRules,
createData,
createRule,
deleteRule,
editState,
updateRule,
toggleEditState,
};
},
head() {
return {
title: this.$tc("meal-plan.meal-plan-settings"),
};
},
});
</script>