Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Change Recipe Owner #4355

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions frontend/components/Domain/Recipe/RecipeDataTable.vue
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@
<template #item.userId="{ item }">
<v-list-item class="justify-start">
<UserAvatar :user-id="item.userId" :tooltip="false" size="40" />
<v-list-item-content>
<v-list-item-title>
<v-list-item-content class="pl-2">
<v-list-item-title class="text-left">
{{ getMember(item.userId) }}
</v-list-item-title>
</v-list-item-content>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,53 @@
<template>
<div class="d-flex justify-start align-center">
<div class="d-flex justify-start align-top py-2">
<RecipeImageUploadBtn class="my-1" :slug="recipe.slug" @upload="uploadImage" @refresh="imageKey++" />
<RecipeSettingsMenu
class="my-1 mx-1"
:value="recipe.settings"
:is-owner="recipe.userId == user.id"
@upload="uploadImage"
/>
<v-spacer />
<v-container class="py-0" style="width: 40%;">
<v-select
v-model="recipe.userId"
:items="allUsers"
item-text="fullName"
item-value="id"
:label="$tc('general.owner')"
hide-details
:disabled="!canEditOwner"
>
<template #prepend>
<UserAvatar :user-id="recipe.userId" :tooltip="false" />
</template>
</v-select>
<v-card-text v-if="ownerHousehold" class="pa-0 d-flex" style="align-items: flex-end;">
<v-spacer />
<v-icon>{{ $globals.icons.household }}</v-icon>
<span class="pl-1">{{ ownerHousehold.name }}</span>
</v-card-text>
</v-container>
</div>
</template>

<script lang="ts">
import { defineComponent, onUnmounted } from "@nuxtjs/composition-api";
import { computed, defineComponent, onUnmounted } from "@nuxtjs/composition-api";
import { clearPageState, usePageState, usePageUser } from "~/composables/recipe-page/shared-state";
import { NoUndefinedField } from "~/lib/api/types/non-generated";
import { Recipe } from "~/lib/api/types/recipe";
import { useUserApi } from "~/composables/api";
import RecipeImageUploadBtn from "~/components/Domain/Recipe/RecipeImageUploadBtn.vue";
import RecipeSettingsMenu from "~/components/Domain/Recipe/RecipeSettingsMenu.vue";
import { useUserStore } from "~/composables/store/use-user-store";
import UserAvatar from "~/components/Domain/User/UserAvatar.vue";
import { useHouseholdStore } from "~/composables/store";

export default defineComponent({
components: {
RecipeImageUploadBtn,
RecipeSettingsMenu,
UserAvatar,
},
props: {
recipe: {
Expand All @@ -34,6 +59,22 @@ export default defineComponent({
const { user } = usePageUser();
const api = useUserApi();
const { imageKey } = usePageState(props.recipe.slug);

const canEditOwner = computed(() => {
return user.id === props.recipe.userId || user.admin;
})

const { store: allUsers } = useUserStore();
const { store: households } = useHouseholdStore();
const ownerHousehold = computed(() => {
const owner = allUsers.value.find((u) => u.id === props.recipe.userId);
if (!owner) {
return null;
};

return households.value.find((h) => h.id === owner.householdId);
});

onUnmounted(() => {
clearPageState(props.recipe.slug);
console.debug("reset RecipePage state during unmount");
Expand All @@ -51,8 +92,11 @@ export default defineComponent({

return {
user,
canEditOwner,
uploadImage,
imageKey,
allUsers,
ownerHousehold,
};
},
});
Expand Down
1 change: 1 addition & 0 deletions frontend/lang/messages/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@
"date": "Date",
"id": "Id",
"owner": "Owner",
"change-owner": "Change Owner",
"date-added": "Date Added",
"none": "None",
"run": "Run",
Expand Down
2 changes: 2 additions & 0 deletions frontend/lib/api/types/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ export interface ReadWebhook {
}
export interface UserSummary {
id: string;
groupId: string;
householdId: string;
username: string;
fullName: string;
}
Expand Down
4 changes: 4 additions & 0 deletions frontend/lib/api/user/recipes/recipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,10 @@ export class RecipeAPI extends BaseCRUDAPI<CreateRecipe, Recipe, Recipe> {
return `${routes.recipesRecipeSlugExportZip(recipeSlug)}?token=${token}`;
}

async updateMany(payload: Recipe[]) {
return await this.requests.put<Recipe[]>(routes.recipesBase, payload);
}

async updateLastMade(recipeSlug: string, timestamp: string) {
return await this.requests.patch<Recipe, RecipeLastMade>(routes.recipesSlugLastMade(recipeSlug), { timestamp })
}
Expand Down
76 changes: 69 additions & 7 deletions frontend/pages/group/data/recipes.vue
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,24 @@
<i>{{ $tc('data-pages.recipes.selected-length-recipe-s-settings-will-be-updated', selected.length) }}</i>
</p>
</v-card-text>
<v-card-text v-else-if="dialog.mode == MODES.changeOwner">
<v-select
v-model="selectedOwner"
:items="allUsers"
item-text="fullName"
item-value="id"
:label="$tc('general.owner')"
hide-details
>
<template #prepend>
<UserAvatar :user-id="selectedOwner" :tooltip="false" />
</template>
</v-select>
<v-card-text v-if="selectedOwnerHousehold" class="d-flex" style="align-items: flex-end;">
<v-icon>{{ $globals.icons.household }}</v-icon>
<span class="pl-1">{{ selectedOwnerHousehold.name }}</span>
</v-card-text>
</v-card-text>
</BaseDialog>
<section>
<!-- Recipe Data Table -->
Expand Down Expand Up @@ -109,6 +127,7 @@
@categorize-selected="openDialog(MODES.category)"
@delete-selected="openDialog(MODES.delete)"
@update-settings="openDialog(MODES.updateSettings)"
@change-owner="openDialog(MODES.changeOwner)"
>
</BaseOverflowButton>

Expand Down Expand Up @@ -155,7 +174,7 @@
</template>

<script lang="ts">
import { defineComponent, reactive, ref, useContext, onMounted } from "@nuxtjs/composition-api";
import { computed, defineComponent, reactive, ref, useContext, onMounted } from "@nuxtjs/composition-api";
import RecipeDataTable from "~/components/Domain/Recipe/RecipeDataTable.vue";
import RecipeOrganizerSelector from "~/components/Domain/Recipe/RecipeOrganizerSelector.vue";
import { useUserApi } from "~/composables/api";
Expand All @@ -165,17 +184,21 @@ import GroupExportData from "~/components/Domain/Group/GroupExportData.vue";
import { GroupDataExport } from "~/lib/api/types/group";
import { MenuItem } from "~/components/global/BaseOverflowButton.vue";
import RecipeSettingsSwitches from "~/components/Domain/Recipe/RecipeSettingsSwitches.vue";
import { useUserStore } from "~/composables/store/use-user-store";
import UserAvatar from "~/components/Domain/User/UserAvatar.vue";
import { useHouseholdStore } from "~/composables/store/use-household-store";

enum MODES {
tag = "tag",
category = "category",
export = "export",
delete = "delete",
updateSettings = "updateSettings",
changeOwner = "changeOwner",
}

export default defineComponent({
components: { RecipeDataTable, RecipeOrganizerSelector, GroupExportData, RecipeSettingsSwitches },
components: { RecipeDataTable, RecipeOrganizerSelector, GroupExportData, RecipeSettingsSwitches, UserAvatar },
scrollToTop: true,
setup() {
const { $auth, $globals, i18n } = useContext();
Expand Down Expand Up @@ -230,6 +253,11 @@ export default defineComponent({
text: i18n.tc("data-pages.recipes.update-settings"),
event: "update-settings",
},
{
icon: $globals.icons.user,
text: i18n.tc("general.change-owner"),
event: "change-owner",
},
{
icon: $globals.icons.delete,
text: i18n.tc("general.delete"),
Expand Down Expand Up @@ -312,9 +340,7 @@ export default defineComponent({

const recipes = selected.value.map((x: Recipe) => x.slug ?? "");

const { response, data } = await api.bulk.bulkDelete({ recipes });

console.log(response, data);
await api.bulk.bulkDelete({ recipes });

await refreshRecipes();
resetAll();
Expand All @@ -335,9 +361,23 @@ export default defineComponent({

const recipes = selected.value.map((x: Recipe) => x.slug ?? "");

const { response, data } = await api.bulk.bulkSetSettings({ recipes, settings: recipeSettings });
await api.bulk.bulkSetSettings({ recipes, settings: recipeSettings });

console.log(response, data);
await refreshRecipes();
resetAll();
}

async function changeOwner() {
if(!selected.value.length || !selectedOwner.value) {
return;
}

selected.value.forEach((r) => {
r.userId = selectedOwner.value;
});

loading.value = true;
await api.recipes.updateMany(selected.value);

await refreshRecipes();
resetAll();
Expand Down Expand Up @@ -365,6 +405,7 @@ export default defineComponent({
[MODES.export]: i18n.tc("data-pages.recipes.export-recipes"),
[MODES.delete]: i18n.tc("data-pages.recipes.delete-recipes"),
[MODES.updateSettings]: i18n.tc("data-pages.recipes.update-settings"),
[MODES.changeOwner]: i18n.tc("general.change-owner"),
};

const callbacks: Record<MODES, () => Promise<void>> = {
Expand All @@ -373,6 +414,7 @@ export default defineComponent({
[MODES.export]: exportSelected,
[MODES.delete]: deleteSelected,
[MODES.updateSettings]: updateSettings,
[MODES.changeOwner]: changeOwner,
};

const icons: Record<MODES, string> = {
Expand All @@ -381,6 +423,7 @@ export default defineComponent({
[MODES.export]: $globals.icons.database,
[MODES.delete]: $globals.icons.delete,
[MODES.updateSettings]: $globals.icons.cog,
[MODES.changeOwner]: $globals.icons.user,
};

dialog.mode = mode;
Expand All @@ -390,6 +433,22 @@ export default defineComponent({
dialog.state = true;
}

const { store: allUsers } = useUserStore();
const { store: households } = useHouseholdStore();
const selectedOwner = ref("");
const selectedOwnerHousehold = computed(() => {
if(!selectedOwner.value) {
return null;
}

const owner = allUsers.value.find((u) => u.id === selectedOwner.value);
if (!owner) {
return null;
};

return households.value.find((h) => h.id === owner.householdId);
});

return {
recipeSettings,
selectAll,
Expand All @@ -412,6 +471,9 @@ export default defineComponent({
groupExports,
purgeExportsDialog,
purgeExports,
allUsers,
selectedOwner,
selectedOwnerHousehold,
};
},
head() {
Expand Down
8 changes: 5 additions & 3 deletions mealie/routes/households/controller_cookbooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,19 +79,21 @@ def update_many(self, data: list[UpdateCookBook]):
cb = self.mixins.update_one(cookbook, cookbook.id)
updated_by_group_and_household[cb.group_id][cb.household_id].append(cb)

all_updated: list[ReadCookBook] = []
if updated_by_group_and_household:
for group_id, household_dict in updated_by_group_and_household.items():
for household_id, updated in household_dict.items():
for household_id, updated_cookbooks in household_dict.items():
all_updated.extend(updated_cookbooks)
self.publish_event(
event_type=EventTypes.cookbook_updated,
document_data=EventCookbookBulkData(
operation=EventOperation.update, cookbook_ids=[cb.id for cb in updated]
operation=EventOperation.update, cookbook_ids=[cb.id for cb in updated_cookbooks]
),
group_id=group_id,
household_id=household_id,
)

return updated
return all_updated

@router.get("/{item_id}", response_model=RecipeCookBook)
def get_one(self, item_id: UUID4 | str):
Expand Down
27 changes: 27 additions & 0 deletions mealie/routes/recipe/recipe_crud_routes.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from collections import defaultdict
from functools import cached_property
from shutil import copyfileobj, rmtree
from uuid import UUID
Expand Down Expand Up @@ -60,6 +61,7 @@
from mealie.services import urls
from mealie.services.event_bus_service.event_types import (
EventOperation,
EventRecipeBulkData,
EventRecipeBulkReportData,
EventRecipeData,
EventTypes,
Expand Down Expand Up @@ -466,6 +468,31 @@ def update_one(self, slug: str, data: Recipe):

return recipe

@router.put("")
def update_many(self, data: list[Recipe]):
updated_by_group_and_household: defaultdict[UUID4, defaultdict[UUID4, list[Recipe]]] = defaultdict(
lambda: defaultdict(list)
)
for recipe in data:
r = self.service.update_one(recipe.id, recipe) # type: ignore
updated_by_group_and_household[r.group_id][r.household_id].append(r)

all_updated: list[Recipe] = []
if updated_by_group_and_household:
for group_id, household_dict in updated_by_group_and_household.items():
for household_id, updated_recipes in household_dict.items():
all_updated.extend(updated_recipes)
self.publish_event(
event_type=EventTypes.recipe_updated,
document_data=EventRecipeBulkData(
operation=EventOperation.update, recipe_slugs=[r.slug for r in updated_recipes]
),
group_id=group_id,
household_id=household_id,
)

return all_updated

@router.patch("/{slug}")
def patch_one(self, slug: str, data: Recipe):
"""Updates a recipe by existing slug and data."""
Expand Down
2 changes: 2 additions & 0 deletions mealie/schema/user/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,8 @@ def loader_options(cls) -> list[LoaderOption]:

class UserSummary(MealieModel):
id: UUID4
group_id: UUID4
household_id: UUID4
username: str
full_name: str
model_config = ConfigDict(from_attributes=True)
Expand Down
5 changes: 5 additions & 0 deletions mealie/services/event_bus_service/event_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@ class EventRecipeData(EventDocumentDataBase):
recipe_slug: str


class EventRecipeBulkData(EventDocumentDataBase):
document_type: EventDocumentType = EventDocumentType.recipe
recipe_slugs: list[str]


class EventRecipeBulkReportData(EventDocumentDataBase):
document_type: EventDocumentType = EventDocumentType.recipe_bulk_report
report_id: UUID4
Expand Down
Loading
Loading