Merge pull request #1247 from TandoorRecipes/feature/related_recipe_switcher

Feature/related recipe switcher
This commit is contained in:
vabene1111
2022-01-06 16:22:54 +01:00
committed by GitHub
9 changed files with 228 additions and 20 deletions

View File

@@ -35,4 +35,3 @@ class CookbookConfig(AppConfig):
# if DEBUG:
# traceback.print_exc()
# pass # dont break startup just because fix could not run, need to investigate cases when this happens

View File

@@ -65,7 +65,6 @@ def test_related_mixed_space(request, recipe, u1_s2):
reverse(RELATED_URL, args={recipe.id})).content)) == 0
# TODO add tests for mealplan related when thats added
# TODO if/when related recipes includes multiple levels (related recipes of related recipes) add the following tests
# -- step recipes included in step recipes
# -- step recipes included in food recipes

View File

@@ -233,7 +233,6 @@ def test_shopping_recipe_mixed_authors(u1_s1, u2_s1):
assert len(json.loads(u2_s1.get(reverse(SHOPPING_LIST_URL)).content)) == 0
# TODO test adding recipe with ingredients that are not food
@pytest.mark.parametrize("recipe", [{'steps__ingredients__header': 1}], indirect=['recipe'])
def test_shopping_with_header_ingredient(u1_s1, recipe):
# with scope(space=recipe.space):

View File

@@ -689,8 +689,11 @@ class RecipeViewSet(viewsets.ModelViewSet):
obj = self.get_object()
if obj.get_space() != request.space:
raise PermissionDenied(detail='You do not have the required permission to perform this action', code=403)
qs = obj.get_related_recipes(levels=1) # TODO: make levels a user setting, included in request data?, keep solely in the backend?
# mealplans= TODO get todays mealplans
try:
levels = int(request.query_params.get('levels', 1))
except (ValueError, TypeError):
levels = 1
qs = obj.get_related_recipes(levels=levels) # TODO: make levels a user setting, included in request data?, keep solely in the backend?
return Response(self.serializer_class(qs, many=True).data)

View File

@@ -1,5 +1,6 @@
<template>
<div id="app" style="margin-bottom: 4vh">
<RecipeSwitcher mode="mealplan" />
<div class="row">
<div class="col-12 col-xl-8 col-lg-10 offset-xl-2 offset-lg-1">
<div class="row">
@@ -244,6 +245,7 @@ import RecipeCard from "@/components/RecipeCard"
import GenericMultiselect from "@/components/GenericMultiselect"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import RecipeSwitcher from "@/components/Buttons/RecipeSwitcher"
Vue.use(BootstrapVue)
@@ -252,7 +254,7 @@ let SETTINGS_COOKIE_NAME = "search_settings"
export default {
name: "RecipeSearchView",
mixins: [ResolveUrlMixin, ApiMixin],
components: { GenericMultiselect, RecipeCard, Treeselect },
components: { GenericMultiselect, RecipeCard, Treeselect, RecipeSwitcher },
data() {
return {
// this.Models and this.Actions inherited from ApiMixin

View File

@@ -5,6 +5,7 @@
</template>
<div v-if="!loading">
<RecipeSwitcher :recipe="rootrecipe.id" :name="rootrecipe.name" mode="recipe" @switch="quickSwitch($event)" />
<div class="row">
<div class="col-12" style="text-align: center">
<h3>{{ recipe.name }}</h3>
@@ -75,12 +76,12 @@
/>
</div>
<div class="my-auto">
<span class="text-primary"
><b
><template v-if="recipe.servings_text === ''">{{ $t("Servings") }}</template
><template v-else>{{ recipe.servings_text }}</template></b
></span
>
<span class="text-primary">
<b>
<template v-if="recipe.servings_text === ''">{{ $t("Servings") }}</template>
<template v-else>{{ recipe.servings_text }}</template>
</b>
</span>
</div>
</div>
</div>
@@ -172,6 +173,7 @@ import IngredientsCard from "@/components/IngredientsCard"
import StepComponent from "@/components/StepComponent"
import KeywordsComponent from "@/components/KeywordsComponent"
import NutritionComponent from "@/components/NutritionComponent"
import RecipeSwitcher from "@/components/Buttons/RecipeSwitcher"
Vue.prototype.moment = moment
@@ -192,22 +194,32 @@ export default {
KeywordsComponent,
LoadingSpinner,
AddRecipeToBook,
RecipeSwitcher,
},
computed: {
ingredient_factor: function () {
return this.servings / this.recipe.servings
},
ingredient_count() {
return this.recipe?.steps.map((x) => x.ingredients).flat().length
},
},
data() {
return {
loading: true,
recipe: undefined,
ingredient_count: 0,
rootrecipe: undefined,
servings: 1,
servings_cache: {},
start_time: "",
share_uid: window.SHARE_UID,
}
},
watch: {
servings(newVal, oldVal) {
this.servings_cache[this.recipe.id] = this.servings
},
},
mounted() {
this.loadRecipe(window.RECIPE_ID)
this.$i18n.locale = window.CUSTOM_LOCALE
@@ -218,12 +230,9 @@ export default {
if (window.USER_SERVINGS !== 0) {
recipe.servings = window.USER_SERVINGS
}
this.servings = recipe.servings
let total_time = 0
for (let step of recipe.steps) {
this.ingredient_count += step.ingredients.length
for (let ingredient of step.ingredients) {
this.$set(ingredient, "checked", false)
}
@@ -237,7 +246,8 @@ export default {
this.start_time = moment().format("yyyy-MM-DDTHH:mm")
}
this.recipe = recipe
this.recipe = this.rootrecipe = recipe
this.servings = this.servings_cache[this.rootrecipe.id] = recipe.servings
this.loading = false
})
},
@@ -253,6 +263,15 @@ export default {
}
}
},
quickSwitch: function (e) {
if (e === -1) {
this.recipe = this.rootrecipe
this.servings = this.servings_cache[this.rootrecipe?.id ?? 1]
} else {
this.recipe = e
this.servings = this.servings_cache?.[e.id] ?? e.servings
}
},
},
}
</script>

View File

@@ -0,0 +1,185 @@
<template>
<div v-if="recipes.length > 0">
<div id="switcher">
<i class="btn btn-outline-dark fas fa-receipt fa-xl shadow-none btn-circle" v-b-toggle.related-recipes />
</div>
<b-sidebar id="related-recipes" :title="title" backdrop right shadow="sm" style="z-index: 10000">
<template #default="{ hide }">
<nav class="mb-3">
<b-nav vertical>
<b-nav-item
variant="link"
@click="
navRecipe(-1)
hide()
"
>{{ name }}</b-nav-item
>
<div v-for="r in recipes" :key="r.id">
<b-nav-item
variant="link"
@click="
navRecipe(r)
hide()
"
>{{ r.name }}</b-nav-item
>
</div>
</b-nav>
</nav>
</template>
</b-sidebar>
</div>
</template>
<script>
const { ApiApiFactory } = require("@/utils/openapi/api")
import { ResolveUrlMixin } from "@/utils/utils"
export default {
name: "RecipeSwitcher",
mixins: [ResolveUrlMixin],
props: {
recipe: { type: Number, default: undefined },
name: { type: String, default: undefined },
mode: { type: String, default: "recipe" },
},
data() {
return {
recipes: [],
recipe_list: [],
}
},
computed: {
title() {
let title = ""
switch (this.mode) {
case "recipe":
title = this.$t("related_recipes")
break
case "mealplan":
title = this.$t("today_recipes")
break
}
return title
},
},
mounted() {
this.recipes = []
switch (this.mode) {
case "recipe":
this.loadRecipes()
break
case "mealplan":
this.loadMealPlans()
break
}
},
methods: {
navRecipe: function (recipe) {
switch (this.mode) {
case "recipe":
this.$emit("switch", recipe)
break
case "mealplan":
window.location.href = this.resolveDjangoUrl("view_recipe", recipe.id)
break
default:
console.log(this.mode, " isn't defined.")
}
},
loadRecipes: function () {
let apiClient = new ApiApiFactory()
apiClient
.relatedRecipe(this.recipe, { query: { levels: 2 } })
// get related recipes and save them for later
.then((result) => {
this.recipe_list = result.data
})
// get all recipes for today
.then(() => {
this.loadMealPlans()
})
},
loadMealPlans: function () {
let apiClient = new ApiApiFactory()
// TODO move to utility function moment is in maintenance mode https://momentjs.com/docs/
var tzoffset = new Date().getTimezoneOffset() * 60000 //offset in milliseconds
let today = new Date(Date.now() - tzoffset).toISOString().split("T")[0]
apiClient
.listMealPlans({
query: {
from_date: today,
to_date: today,
},
})
.then((result) => {
let promises = []
result.data.forEach((mealplan) => {
this.recipe_list.push({ ...mealplan?.recipe, servings: mealplan?.servings })
const serving_factor = (mealplan?.servings ?? mealplan?.recipe?.servings ?? 1) / (mealplan?.recipe?.servings ?? 1)
promises.push(
apiClient.relatedRecipe(mealplan?.recipe?.id, { query: { levels: 2 } }).then((r) => {
// scale all recipes to mealplan servings
r.data = r.data.map((x) => {
return { ...x, factor: serving_factor }
})
this.recipe_list = [...this.recipe_list, ...r.data]
})
)
})
return Promise.all(promises).then(() => {
let promises = []
let dedup = []
this.recipe_list.forEach((recipe) => {
if (!dedup.includes(recipe.id)) {
dedup.push(recipe.id)
promises.push(
apiClient.retrieveRecipe(recipe.id).then((result) => {
// scale all recipes to mealplan servings
result.data.servings = recipe?.servings ?? result.data.servings * (recipe?.factor ?? 1)
this.recipes.push(result.data)
})
)
}
})
return Promise.all(promises)
})
})
},
},
}
</script>
<style>
.btn-circle {
width: 50px;
height: 50px;
padding: 10px 16px;
text-align: center;
border-radius: 35px;
font-size: 24px;
line-height: 1.33;
z-index: 9000;
}
@media screen and (max-width: 600px) {
#switcher .btn-circle {
position: fixed;
top: 9px;
left: 80px;
color: white;
}
}
@media screen and (max-width: 2000px) {
#switcher .btn-circle {
position: fixed;
bottom: 10px;
right: 50px;
}
}
</style>

View File

@@ -108,7 +108,7 @@ export default {
this.shop = false // don't check any boxes until user selects a shopping list to edit
if (count_shopping_ingredient >= 1) {
this.shopping_status = true // ingredient is in the shopping list - probably (but not definitely, this ingredient)
} else if (this.ingredient.food.shopping) {
} else if (this.ingredient?.food?.shopping) {
this.shopping_status = null // food is in the shopping list, just not for this ingredient/recipe
} else {
// food is not in any shopping list
@@ -123,7 +123,7 @@ export default {
if (count_shopping_ingredient >= 1) {
// ingredient is in this shopping list (not entirely sure how this could happen?)
this.shopping_status = true
} else if (count_shopping_ingredient == 0 && this.ingredient.food.shopping) {
} else if (count_shopping_ingredient == 0 && this.ingredient?.food?.shopping) {
// food is in the shopping list, just not for this ingredient/recipe
this.shopping_status = null
} else {

View File

@@ -276,5 +276,7 @@
"csv_prefix_label": "List Prefix",
"copy_markdown_table": "Copy as Markdown Table",
"in_shopping": "In Shopping List",
"DelayUntil": "Delay Until"
"DelayUntil": "Delay Until",
"related_recipes": "Related Recipes",
"today_recipes": "Today's Recipes"
}