feat: Improve recipe parsing ui (#7984)
Co-authored-by: p0lycarpio <arsene.reymond@free.fr>
This commit is contained in:
1 parent
7d8e555818
commit
dd6cea0162
16 files changed
+1792
-842
No files matched your search
@@ -11,229 +11,191 @@
|
||||
style="max-width: 500px"
|
||||
@click="$emit('clickIngredientField', 'title')"
|
||||
/>
|
||||
<v-row
|
||||
:no-gutters="mdAndUp"
|
||||
density="comfortable"
|
||||
class="d-flex flex-wrap my-1"
|
||||
>
|
||||
<v-col
|
||||
sm="12"
|
||||
md="2"
|
||||
cols="12"
|
||||
class="flex-grow-0 flex-shrink-0"
|
||||
>
|
||||
<v-number-input
|
||||
v-model="model.quantity"
|
||||
variant="solo"
|
||||
:precision="null"
|
||||
:min="0"
|
||||
hide-details
|
||||
control-variant="stacked"
|
||||
inset
|
||||
density="compact"
|
||||
:placeholder="$t('recipe.quantity')"
|
||||
@keypress="quantityFilter"
|
||||
>
|
||||
<template v-if="enableDragHandle" #prepend>
|
||||
<v-icon
|
||||
class="mr-n1 handle"
|
||||
<RecipeIngredientEditorLayout :header="enableDragHandle || enableContextMenu">
|
||||
<template v-if="enableDragHandle" #dragHandle>
|
||||
<v-icon class="ma-2 handle" size="large">
|
||||
{{ $globals.icons.arrowUpDown }}
|
||||
</v-icon>
|
||||
</template>
|
||||
<template v-if="enableContextMenu" #contextMenu>
|
||||
<BaseButtonGroup
|
||||
hover
|
||||
:large="false"
|
||||
class="ml-auto"
|
||||
:buttons="btns"
|
||||
@toggle-section="toggleTitle"
|
||||
@toggle-subrecipe="toggleIsRecipe"
|
||||
@insert-above="$emit('insert-above')"
|
||||
@insert-below="$emit('insert-below')"
|
||||
@delete="$emit('delete')"
|
||||
/>
|
||||
</template>
|
||||
<template #form>
|
||||
<div class="flex-grow-1">
|
||||
<div class="d-flex ga-2 py-2" :class="$vuetify.display.mdAndDown ? 'flex-column' : ''">
|
||||
<v-number-input
|
||||
v-model="model.quantity"
|
||||
variant="filled"
|
||||
:precision="null"
|
||||
:min="0"
|
||||
hide-details
|
||||
inset
|
||||
control-variant="stacked"
|
||||
density="compact"
|
||||
:style="$vuetify.display.mdAndDown ? '' : 'flex: 1 0 50px;'"
|
||||
:placeholder="$t('recipe.quantity')"
|
||||
@keypress="quantityFilter"
|
||||
/>
|
||||
<v-autocomplete
|
||||
ref="unitAutocomplete"
|
||||
v-model="model.unit"
|
||||
v-model:search="unitSearch"
|
||||
auto-select-first
|
||||
hide-details
|
||||
density="compact"
|
||||
:style="$vuetify.display.mdAndDown ? '' : 'flex: 2 0 50px;'"
|
||||
variant="filled"
|
||||
return-object
|
||||
:items="filteredUnits"
|
||||
:custom-filter="() => true"
|
||||
item-title="name"
|
||||
:placeholder="$t('recipe.choose-unit')"
|
||||
clearable
|
||||
:menu-props="{ attach: props.menuAttachTarget, maxHeight: '250px' }"
|
||||
@keyup.enter="handleUnitEnter"
|
||||
>
|
||||
{{ $globals.icons.arrowUpDown }}
|
||||
</v-icon>
|
||||
</template>
|
||||
</v-number-input>
|
||||
</v-col>
|
||||
<v-col
|
||||
sm="12"
|
||||
md="2"
|
||||
cols="12"
|
||||
>
|
||||
<v-autocomplete
|
||||
ref="unitAutocomplete"
|
||||
v-model="model.unit"
|
||||
v-model:search="unitSearch"
|
||||
auto-select-first
|
||||
hide-details
|
||||
density="compact"
|
||||
variant="solo"
|
||||
return-object
|
||||
:items="filteredUnits"
|
||||
:custom-filter="() => true"
|
||||
item-title="name"
|
||||
class="mx-1"
|
||||
:placeholder="$t('recipe.choose-unit')"
|
||||
clearable
|
||||
:menu-props="{ attach: props.menuAttachTarget, maxHeight: '250px' }"
|
||||
@keyup.enter="handleUnitEnter"
|
||||
>
|
||||
<template #prepend>
|
||||
<v-tooltip v-if="unitError" location="bottom">
|
||||
<template #activator="{ props: unitTooltipProps }">
|
||||
<v-icon
|
||||
v-bind="unitTooltipProps"
|
||||
class="ml-2 mr-n3 opacity-100"
|
||||
color="primary"
|
||||
>
|
||||
{{ $globals.icons.alert }}
|
||||
</v-icon>
|
||||
<template v-if="unitError" #prepend-inner>
|
||||
<v-tooltip location="bottom">
|
||||
<template #activator="{ props: unitTooltipProps }">
|
||||
<v-icon
|
||||
v-bind="unitTooltipProps"
|
||||
class="opacity-100"
|
||||
color="primary"
|
||||
>
|
||||
{{ $globals.icons.alert }}
|
||||
</v-icon>
|
||||
</template>
|
||||
<span v-if="unitErrorTooltip">
|
||||
{{ unitErrorTooltip }}
|
||||
</span>
|
||||
</v-tooltip>
|
||||
</template>
|
||||
<span v-if="unitErrorTooltip">
|
||||
{{ unitErrorTooltip }}
|
||||
</span>
|
||||
</v-tooltip>
|
||||
</template>
|
||||
<template #no-data>
|
||||
<div class="caption text-center pb-2">
|
||||
{{ $t("recipe.press-enter-to-create") }}
|
||||
</div>
|
||||
</template>
|
||||
<template #append-item>
|
||||
<div v-if="showCreateUnit" class="px-2">
|
||||
<BaseButton
|
||||
block
|
||||
size="small"
|
||||
@click="createAssignUnit()"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</v-autocomplete>
|
||||
</v-col>
|
||||
<template #no-data>
|
||||
<div class="caption text-center pb-2">
|
||||
{{ $t("recipe.press-enter-to-create") }}
|
||||
</div>
|
||||
</template>
|
||||
<template #append-item>
|
||||
<div v-if="showCreateUnit" class="px-2">
|
||||
<BaseButton
|
||||
block
|
||||
size="small"
|
||||
@click="createAssignUnit()"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</v-autocomplete>
|
||||
|
||||
<!-- Foods Input -->
|
||||
<v-col
|
||||
v-if="!state.isRecipe"
|
||||
m="12"
|
||||
md="4"
|
||||
cols="12"
|
||||
class=""
|
||||
>
|
||||
<v-autocomplete
|
||||
ref="foodAutocomplete"
|
||||
v-model="model.food"
|
||||
v-model:search="foodSearch"
|
||||
auto-select-first
|
||||
hide-details
|
||||
density="compact"
|
||||
variant="solo"
|
||||
return-object
|
||||
:items="filteredFoods"
|
||||
:custom-filter="() => true"
|
||||
item-title="name"
|
||||
class="mx-1 py-0"
|
||||
:placeholder="$t('recipe.choose-food')"
|
||||
clearable
|
||||
:menu-props="{ attach: props.menuAttachTarget, maxHeight: '250px' }"
|
||||
@keyup.enter="handleFoodEnter"
|
||||
>
|
||||
<template #prepend>
|
||||
<v-tooltip v-if="foodError" location="bottom">
|
||||
<template #activator="{ props: foodTooltipProps }">
|
||||
<v-icon
|
||||
v-bind="foodTooltipProps"
|
||||
class="ml-2 mr-n3 opacity-100"
|
||||
color="primary"
|
||||
>
|
||||
{{ $globals.icons.alert }}
|
||||
</v-icon>
|
||||
<!-- Foods Input -->
|
||||
<v-autocomplete
|
||||
v-if="!state.isRecipe"
|
||||
ref="foodAutocomplete"
|
||||
v-model="model.food"
|
||||
v-model:search="foodSearch"
|
||||
auto-select-first
|
||||
hide-details
|
||||
density="compact"
|
||||
:style="$vuetify.display.mdAndDown ? '' : 'flex: 4 0 50px;'"
|
||||
variant="filled"
|
||||
return-object
|
||||
:items="filteredFoods"
|
||||
:custom-filter="() => true"
|
||||
item-title="name"
|
||||
:placeholder="$t('recipe.choose-food')"
|
||||
clearable
|
||||
:menu-props="{ attach: props.menuAttachTarget, maxHeight: '250px' }"
|
||||
@keyup.enter="handleFoodEnter"
|
||||
>
|
||||
<template v-if="foodError" #prepend-inner>
|
||||
<v-tooltip location="bottom">
|
||||
<template #activator="{ props: foodTooltipProps }">
|
||||
<v-icon
|
||||
v-bind="foodTooltipProps"
|
||||
class="opacity-100"
|
||||
color="primary"
|
||||
>
|
||||
{{ $globals.icons.alert }}
|
||||
</v-icon>
|
||||
</template>
|
||||
<span v-if="foodErrorTooltip">
|
||||
{{ foodErrorTooltip }}
|
||||
</span>
|
||||
</v-tooltip>
|
||||
</template>
|
||||
<span v-if="foodErrorTooltip">
|
||||
{{ foodErrorTooltip }}
|
||||
</span>
|
||||
</v-tooltip>
|
||||
</template>
|
||||
<template #no-data>
|
||||
<div class="caption text-center pb-2">
|
||||
{{ $t("recipe.press-enter-to-create") }}
|
||||
</div>
|
||||
</template>
|
||||
<template #append-item>
|
||||
<div v-if="showCreateFood" class="px-2">
|
||||
<BaseButton
|
||||
block
|
||||
size="small"
|
||||
@click="createAssignFood()"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</v-autocomplete>
|
||||
</v-col>
|
||||
<!-- Recipe Input -->
|
||||
<v-col
|
||||
v-if="state.isRecipe"
|
||||
m="12"
|
||||
md="4"
|
||||
cols="12"
|
||||
class=""
|
||||
>
|
||||
<v-autocomplete
|
||||
ref="search.query"
|
||||
v-model="model.referencedRecipe"
|
||||
v-model:search="search.query.value"
|
||||
auto-select-first
|
||||
hide-details
|
||||
density="compact"
|
||||
variant="solo"
|
||||
return-object
|
||||
:items="search.data.value || []"
|
||||
item-title="name"
|
||||
class="mx-1 py-0"
|
||||
:placeholder="$t('search.type-to-search')"
|
||||
clearable
|
||||
:label="!model.referencedRecipe ? $t('recipe.choose-recipe') : ''"
|
||||
@click="search.trigger()"
|
||||
@focus="search.trigger()"
|
||||
>
|
||||
<template #prepend />
|
||||
</v-autocomplete>
|
||||
</v-col>
|
||||
<v-col
|
||||
sm="12"
|
||||
md=""
|
||||
cols="12"
|
||||
>
|
||||
<div class="d-flex">
|
||||
<v-text-field
|
||||
v-model="model.note"
|
||||
hide-details
|
||||
density="compact"
|
||||
variant="solo"
|
||||
:placeholder="$t('recipe.notes')"
|
||||
class="mb-auto"
|
||||
@click="$emit('clickIngredientField', 'note')"
|
||||
/>
|
||||
<BaseButtonGroup
|
||||
v-if="enableContextMenu"
|
||||
hover
|
||||
:large="false"
|
||||
class="my-auto d-flex"
|
||||
:buttons="btns"
|
||||
@toggle-section="toggleTitle"
|
||||
@toggle-subrecipe="toggleIsRecipe"
|
||||
@insert-above="$emit('insert-above')"
|
||||
@insert-below="$emit('insert-below')"
|
||||
@delete="$emit('delete')"
|
||||
/>
|
||||
<template #no-data>
|
||||
<div class="caption text-center pb-2">
|
||||
{{ $t("recipe.press-enter-to-create") }}
|
||||
</div>
|
||||
</template>
|
||||
<template #append-item>
|
||||
<div v-if="showCreateFood" class="px-2">
|
||||
<BaseButton
|
||||
block
|
||||
size="small"
|
||||
@click="createAssignFood()"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</v-autocomplete>
|
||||
<!-- Recipe Input -->
|
||||
<v-autocomplete
|
||||
v-if="state.isRecipe"
|
||||
ref="search.query"
|
||||
v-model="model.referencedRecipe"
|
||||
v-model:search="search.query.value"
|
||||
auto-select-first
|
||||
hide-details
|
||||
density="compact"
|
||||
:style="$vuetify.display.mdAndDown ? '' : 'flex: 4 0 50px;'"
|
||||
variant="filled"
|
||||
return-object
|
||||
:items="search.data.value || []"
|
||||
item-title="name"
|
||||
:placeholder="$t('search.type-to-search')"
|
||||
clearable
|
||||
:label="!model.referencedRecipe ? $t('recipe.choose-recipe') : ''"
|
||||
@click="search.trigger()"
|
||||
@focus="search.trigger()"
|
||||
/>
|
||||
<v-text-field
|
||||
v-model="model.note"
|
||||
hide-details
|
||||
density="compact"
|
||||
:style="$vuetify.display.mdAndDown ? '' : 'flex: 4 0 50px;'"
|
||||
variant="filled"
|
||||
:placeholder="$t('recipe.notes')"
|
||||
class=""
|
||||
@click="$emit('clickIngredientField', 'note')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</v-col>
|
||||
</v-row>
|
||||
<slot name="before-divider" />
|
||||
<v-divider
|
||||
v-if="!mdAndUp"
|
||||
class="my-4"
|
||||
/>
|
||||
</template>
|
||||
</RecipeIngredientEditorLayout>
|
||||
<div class="px-2" :class="{ 'ml-10': !$vuetify.display.mdAndDown }">
|
||||
<slot name="before-divider" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, reactive, toRefs, watch } from "vue";
|
||||
import { useDisplay } from "vuetify";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useFoodStore, useFoodData, useUnitStore, useUnitData } from "~/composables/store";
|
||||
import { useSearch } from "~/composables/use-search";
|
||||
import { useNuxtApp } from "#app";
|
||||
import type { RecipeIngredient } from "~/lib/api/types/recipe";
|
||||
import { computed, reactive, ref, toRefs, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { usePublicExploreApi, useUserApi } from "~/composables/api";
|
||||
import { useRecipeSearch } from "~/composables/recipes/use-recipe-search";
|
||||
import { useFoodData, useFoodStore, useUnitData, useUnitStore } from "~/composables/store";
|
||||
import { useSearch } from "~/composables/use-search";
|
||||
import type { RecipeIngredient } from "~/lib/api/types/recipe";
|
||||
|
||||
// defineModel replaces modelValue prop
|
||||
const model = defineModel<RecipeIngredient>({ required: true });
|
||||
@@ -284,7 +246,6 @@ defineEmits([
|
||||
"delete",
|
||||
]);
|
||||
|
||||
const { mdAndUp } = useDisplay();
|
||||
const i18n = useI18n();
|
||||
const { $globals } = useNuxtApp();
|
||||
|
||||
@@ -439,10 +400,3 @@ function quantityFilter(e: KeyboardEvent) {
|
||||
|
||||
const { showTitle } = toRefs(state);
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.v-input__append-outer {
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,13 @@
|
||||
<template>
|
||||
<div v-if="header" class="d-flex pt-2 align-center">
|
||||
<slot name="dragHandle" />
|
||||
<slot v-if="!$vuetify.display.mdAndDown" name="form" />
|
||||
<slot name="contextMenu" />
|
||||
</div>
|
||||
<slot v-else-if="!$vuetify.display.mdAndDown" name="form" />
|
||||
<slot v-if="$vuetify.display.mdAndDown" name="form" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
defineProps<{ header: boolean }>();
|
||||
</script>
|
||||
@@ -219,7 +219,7 @@ import RecipePageIngredientEditor from "./RecipePageParts/RecipePageIngredientEd
|
||||
import RecipePageIngredientToolsView from "./RecipePageParts/RecipePageIngredientToolsView.vue";
|
||||
import RecipePageInstructions from "./RecipePageParts/RecipePageInstructions.vue";
|
||||
import RecipePageOrganizers from "./RecipePageParts/RecipePageOrganizers.vue";
|
||||
import RecipePageParseDialog from "./RecipePageParts/RecipePageParseDialog.vue";
|
||||
import RecipePageParseDialog from "./RecipePageParts/RecipeParseDialog/RecipePageParseDialog.vue";
|
||||
import RecipePageScale from "./RecipePageParts/RecipePageScale.vue";
|
||||
import RecipePageInfoEditor from "./RecipePageParts/RecipePageInfoEditor.vue";
|
||||
import RecipePageComments from "./RecipePageParts/RecipePageComments.vue";
|
||||
@@ -423,9 +423,13 @@ async function saveRecipe() {
|
||||
}
|
||||
|
||||
async function saveParsedIngredients(ingredients: NoUndefinedField<RecipeIngredient[]>) {
|
||||
const returnToEdit = isEditMode.value;
|
||||
recipe.value.recipeIngredient = ingredients;
|
||||
await saveRecipe();
|
||||
toggleIsParsing(false);
|
||||
if (returnToEdit) {
|
||||
setMode(PageMode.EDIT);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteRecipe() {
|
||||
|
||||
+34
-49
@@ -4,9 +4,29 @@
|
||||
<h2 class="mb-4 text-h5 font-weight-medium opacity-80">
|
||||
{{ $t("recipe.ingredients") }}
|
||||
</h2>
|
||||
<BannerWarning v-if="!hasFoodOrUnit">
|
||||
{{ $t("recipe.ingredients-not-parsed-description", { parse: $t('recipe.parse') }) }}
|
||||
</BannerWarning>
|
||||
<v-alert
|
||||
v-if="!hasFoodOrUnit"
|
||||
border="start"
|
||||
color="info"
|
||||
:icon="$globals.icons.information"
|
||||
variant="tonal"
|
||||
>
|
||||
<div>
|
||||
{{ $t('recipe.ingredients-not-parsed-description', { parse: $t('recipe.parse') }) }}
|
||||
</div>
|
||||
<div class="d-flex flex-wrap justify-end mt-3">
|
||||
<BaseButton
|
||||
class="mb-1"
|
||||
color="info"
|
||||
@click="toggleIsParsing(true)"
|
||||
>
|
||||
<template #icon>
|
||||
{{ $globals.icons.foods }}
|
||||
</template>
|
||||
{{ $t('recipe.parse') }}
|
||||
</BaseButton>
|
||||
</div>
|
||||
</v-alert>
|
||||
</div>
|
||||
<VueDraggable
|
||||
v-if="recipe.recipeIngredient.length > 0"
|
||||
@@ -23,22 +43,17 @@
|
||||
@start="drag = true"
|
||||
@end="drag = false"
|
||||
>
|
||||
<TransitionGroup
|
||||
type="transition"
|
||||
>
|
||||
<RecipeIngredientEditor
|
||||
v-for="(ingredient, index) in recipe.recipeIngredient"
|
||||
:key="ingredient.referenceId"
|
||||
v-model="recipe.recipeIngredient[index]"
|
||||
:is-recipe="ingredientIsRecipe(ingredient)"
|
||||
enable-drag-handle
|
||||
enable-context-menu
|
||||
class="list-group-item"
|
||||
@delete="recipe.recipeIngredient.splice(index, 1)"
|
||||
@insert-above="insertNewIngredient(index)"
|
||||
@insert-below="insertNewIngredient(index + 1)"
|
||||
/>
|
||||
</TransitionGroup>
|
||||
<RecipeIngredientEditor
|
||||
v-for="(ingredient, index) in recipe.recipeIngredient"
|
||||
:key="ingredient.referenceId"
|
||||
v-model="recipe.recipeIngredient[index]"
|
||||
:is-recipe="ingredientIsRecipe(ingredient)"
|
||||
enable-drag-handle
|
||||
enable-context-menu
|
||||
@delete="recipe.recipeIngredient.splice(index, 1)"
|
||||
@insert-above="insertNewIngredient(index)"
|
||||
@insert-below="insertNewIngredient(index + 1)"
|
||||
/>
|
||||
</VueDraggable>
|
||||
<v-skeleton-loader
|
||||
v-else
|
||||
@@ -47,28 +62,6 @@
|
||||
type="list-item"
|
||||
/>
|
||||
<div class="d-flex flex-wrap justify-center justify-sm-end mt-3">
|
||||
<v-tooltip
|
||||
location="top"
|
||||
color="accent"
|
||||
>
|
||||
<template #activator="{ props }">
|
||||
<span>
|
||||
<BaseButton
|
||||
class="mb-1"
|
||||
:disabled="hasFoodOrUnit"
|
||||
color="accent"
|
||||
v-bind="props"
|
||||
@click="toggleIsParsing(true)"
|
||||
>
|
||||
<template #icon>
|
||||
{{ $globals.icons.foods }}
|
||||
</template>
|
||||
{{ $t('recipe.parse') }}
|
||||
</BaseButton>
|
||||
</span>
|
||||
</template>
|
||||
<span>{{ parserToolTip }}</span>
|
||||
</v-tooltip>
|
||||
<RecipeDialogBulkAdd
|
||||
ref="domBulkAddDialog"
|
||||
class="mx-1 mb-1"
|
||||
@@ -138,7 +131,6 @@ import { uuid4 } from "~/composables/use-utils";
|
||||
|
||||
const recipe = defineModel<NoUndefinedField<Recipe>>({ required: true });
|
||||
const ingredientsWithRecipe = new Map<string, boolean>();
|
||||
const i18n = useI18n();
|
||||
|
||||
const drag = ref(false);
|
||||
const domBulkAddDialog = ref<InstanceType<typeof RecipeDialogBulkAdd> | null>(null);
|
||||
@@ -158,13 +150,6 @@ const hasFoodOrUnit = computed(() => {
|
||||
return false;
|
||||
});
|
||||
|
||||
const parserToolTip = computed(() => {
|
||||
if (hasFoodOrUnit.value) {
|
||||
return i18n.t("recipe.recipes-with-units-or-foods-defined-cannot-be-parsed");
|
||||
}
|
||||
return i18n.t("recipe.parse-ingredients");
|
||||
});
|
||||
|
||||
function showBulkAdd() {
|
||||
domBulkAddDialog.value?.open();
|
||||
}
|
||||
|
||||
-570
@@ -1,570 +0,0 @@
|
||||
<template>
|
||||
<BaseDialog
|
||||
:model-value="modelValue"
|
||||
:title="$t('recipe.parse-ingredients')"
|
||||
:icon="$globals.icons.fileSign"
|
||||
disable-submit-on-enter
|
||||
@update:model-value="emit('update:modelValue', $event)"
|
||||
>
|
||||
<v-container fluid class="pa-2 ma-0" style="background-color: rgb(var(--v-theme-background));">
|
||||
<div v-if="state.loading.parser" class="my-6">
|
||||
<AppLoader class="my-6" :waiting-text="$t('recipe.parser.parsing-ingredients')" />
|
||||
</div>
|
||||
<div v-else>
|
||||
<BaseCardSectionTitle :title="$t('recipe.parser.ingredient-parser')">
|
||||
<div v-if="!state.allReviewed" class="mb-4">
|
||||
<p>{{ $t("recipe.parser.ingredient-parser-description") }}</p>
|
||||
<p>{{ $t("recipe.parser.ingredient-parser-final-review-description") }}</p>
|
||||
</div>
|
||||
<div class="d-flex flex-wrap align-center">
|
||||
<div class="text-body-2 mr-2">
|
||||
{{ $t("recipe.parser.select-parser") }}
|
||||
</div>
|
||||
<div class="d-flex align-center">
|
||||
<BaseOverflowButton
|
||||
v-model="parser"
|
||||
:disabled="state.loading.parser"
|
||||
btn-class="mx-2"
|
||||
:items="availableParsers"
|
||||
/>
|
||||
<v-btn
|
||||
icon
|
||||
size="40"
|
||||
color="info"
|
||||
:disabled="state.loading.parser"
|
||||
@click="parseIngredients"
|
||||
>
|
||||
<v-icon>{{ $globals.icons.refresh }}</v-icon>
|
||||
</v-btn>
|
||||
</div>
|
||||
</div>
|
||||
</BaseCardSectionTitle>
|
||||
<v-card v-if="!state.allReviewed && currentIng">
|
||||
<v-card-text class="pb-0 mb-0">
|
||||
<div class="text-center px-8 py-4 mb-6">
|
||||
<p class="text-h5 font-italic">
|
||||
{{ currentIng.input }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="d-flex align-center pa-0 ma-0">
|
||||
<v-icon
|
||||
:color="(currentIng.confidence?.average || 0) < confidenceThreshold ? 'error' : 'success'"
|
||||
>
|
||||
{{ (currentIng.confidence?.average || 0) < confidenceThreshold ? $globals.icons.alert : $globals.icons.check }}
|
||||
</v-icon>
|
||||
<span
|
||||
class="ml-2"
|
||||
:color="currentIngHasError ? 'error-text' : 'success-text'"
|
||||
>
|
||||
{{ $t("recipe.parser.confidence-score") }}: {{ currentIng.confidence ? asPercentage(currentIng.confidence?.average!) : "" }}
|
||||
</span>
|
||||
</div>
|
||||
<RecipeIngredientEditor
|
||||
v-model="currentIng.ingredient"
|
||||
:unit-error="!!currentMissingUnit"
|
||||
:unit-error-tooltip="$t('recipe.parser.this-unit-could-not-be-parsed-automatically')"
|
||||
:food-error="!!currentMissingFood"
|
||||
:food-error-tooltip="$t('recipe.parser.this-food-could-not-be-parsed-automatically')"
|
||||
/>
|
||||
<v-card-actions>
|
||||
<v-spacer />
|
||||
<BaseButton
|
||||
v-if="currentMissingUnit && !currentIng.ingredient.unit?.id"
|
||||
color="warning"
|
||||
size="small"
|
||||
@click="createMissingUnit"
|
||||
>
|
||||
{{ i18n.t("recipe.parser.missing-unit", { unit: currentMissingUnit }) }}
|
||||
</BaseButton>
|
||||
<BaseButton
|
||||
v-if="
|
||||
currentMissingUnit
|
||||
&& currentIng.ingredient.unit?.id
|
||||
&& currentMissingUnit.toLowerCase() != currentIng.ingredient.unit?.name.toLowerCase()
|
||||
"
|
||||
color="warning"
|
||||
size="small"
|
||||
@click="addMissingUnitAsAlias"
|
||||
>
|
||||
{{ i18n.t("recipe.parser.add-text-as-alias-for-item", { text: currentMissingUnit, item: currentIng.ingredient.unit.name }) }}
|
||||
</BaseButton>
|
||||
<BaseButton
|
||||
v-if="currentMissingFood && !currentIng.ingredient.food?.id"
|
||||
color="warning"
|
||||
size="small"
|
||||
@click="createMissingFood"
|
||||
>
|
||||
{{ i18n.t("recipe.parser.missing-food", { food: currentMissingFood }) }}
|
||||
</BaseButton>
|
||||
<BaseButton
|
||||
v-if="
|
||||
currentMissingFood
|
||||
&& currentIng.ingredient.food?.id
|
||||
&& currentMissingFood.toLowerCase() != currentIng.ingredient.food?.name.toLowerCase()
|
||||
"
|
||||
color="warning"
|
||||
size="small"
|
||||
@click="addMissingFoodAsAlias"
|
||||
>
|
||||
{{ i18n.t("recipe.parser.add-text-as-alias-for-item", { text: currentMissingFood, item: currentIng.ingredient.food.name }) }}
|
||||
</BaseButton>
|
||||
</v-card-actions>
|
||||
</v-card-text>
|
||||
</v-card>
|
||||
<div v-else>
|
||||
<v-card-title class="text-center pt-0 pb-8">
|
||||
{{ $t("recipe.parser.review-parsed-ingredients") }}
|
||||
</v-card-title>
|
||||
<v-card-text style="max-height: 60vh; overflow-y: auto;">
|
||||
<VueDraggable
|
||||
v-model="parsedIngs"
|
||||
handle=".handle"
|
||||
:delay="250"
|
||||
:delay-on-touch-only="true"
|
||||
v-bind="{
|
||||
animation: 200,
|
||||
group: 'recipe-ingredients',
|
||||
disabled: false,
|
||||
ghostClass: 'ghost',
|
||||
}"
|
||||
class="px-6"
|
||||
@start="drag = true"
|
||||
@end="drag = false"
|
||||
>
|
||||
<TransitionGroup
|
||||
type="transition"
|
||||
>
|
||||
<v-lazy v-for="(ingredient, index) in parsedIngs" :key="index">
|
||||
<RecipeIngredientEditor
|
||||
v-model="ingredient.ingredient"
|
||||
enable-drag-handle
|
||||
enable-context-menu
|
||||
class="list-group-item pb-8"
|
||||
:delete-disabled="parsedIngs.length <= 1"
|
||||
@delete="parsedIngs.splice(index, 1)"
|
||||
@insert-above="insertNewIngredient(index)"
|
||||
@insert-below="insertNewIngredient(index + 1)"
|
||||
>
|
||||
<template #before-divider>
|
||||
<p v-if="ingredient.input" class="py-0 my-0 text-caption">
|
||||
{{ $t("recipe.original-text-with-value", { originalText: ingredient.input }) }}
|
||||
</p>
|
||||
</template>
|
||||
</RecipeIngredientEditor>
|
||||
</v-lazy>
|
||||
</TransitionGroup>
|
||||
</VueDraggable>
|
||||
</v-card-text>
|
||||
</div>
|
||||
</div>
|
||||
</v-container>
|
||||
<template v-if="!state.loading.parser" #custom-card-action>
|
||||
<!-- Parse -->
|
||||
<div v-if="!state.allReviewed" class="d-flex justify-space-between align-center">
|
||||
<v-checkbox
|
||||
v-model="currentIngShouldDelete"
|
||||
color="error"
|
||||
hide-details
|
||||
density="compact"
|
||||
:label="i18n.t('recipe.parser.delete-item')"
|
||||
class="mr-4"
|
||||
/>
|
||||
<BaseButton
|
||||
:color="currentIngShouldDelete ? 'error' : 'info'"
|
||||
:icon="currentIngShouldDelete ? $globals.icons.delete : $globals.icons.arrowRightBold"
|
||||
:icon-right="!currentIngShouldDelete"
|
||||
:text="$t(currentIngShouldDelete ? 'recipe.parser.delete-item' : 'general.next')"
|
||||
@click="nextIngredient"
|
||||
/>
|
||||
</div>
|
||||
<!-- Review -->
|
||||
<div v-else>
|
||||
<BaseButton
|
||||
create
|
||||
:text="$t('general.save')"
|
||||
:icon="$globals.icons.save"
|
||||
:loading="state.loading.save"
|
||||
@click="saveIngs"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</BaseDialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { VueDraggable } from "vue-draggable-plus";
|
||||
import type { IngredientFood, IngredientUnit, ParsedIngredient, RecipeIngredient } from "~/lib/api/types/recipe";
|
||||
import type { Parser } from "~/lib/api/user/recipes/recipe";
|
||||
import type { NoUndefinedField } from "~/lib/api/types/non-generated";
|
||||
import { useUserApi } from "~/composables/api";
|
||||
import { useIngredientTextParser } from "~/composables/recipes";
|
||||
import { useFoodData, useFoodStore, useUnitData, useUnitStore } from "~/composables/store";
|
||||
import { useGlobalI18n } from "~/composables/use-global-i18n";
|
||||
import { useGroupSelf } from "~/composables/use-groups";
|
||||
import { alert } from "~/composables/use-toast";
|
||||
import { useParsingPreferences } from "~/composables/use-users/preferences";
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: boolean;
|
||||
ingredients: NoUndefinedField<RecipeIngredient[]>;
|
||||
}>();
|
||||
|
||||
const { ingredientToParserString } = useIngredientTextParser();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "update:modelValue", value: boolean): void;
|
||||
(e: "save", value: NoUndefinedField<RecipeIngredient[]>): void;
|
||||
}>();
|
||||
|
||||
const { group } = useGroupSelf();
|
||||
const i18n = useGlobalI18n();
|
||||
const api = useUserApi();
|
||||
const drag = ref(false);
|
||||
|
||||
const unitStore = useUnitStore();
|
||||
const unitData = useUnitData();
|
||||
const foodStore = useFoodStore();
|
||||
const foodData = useFoodData();
|
||||
|
||||
const parserPreferences = useParsingPreferences();
|
||||
const parser = ref<Parser>(parserPreferences.value.parser || "nlp");
|
||||
const availableParsers = computed(() => {
|
||||
return [
|
||||
{
|
||||
text: i18n.t("recipe.parser.natural-language-processor"),
|
||||
value: "nlp",
|
||||
},
|
||||
{
|
||||
text: i18n.t("recipe.parser.brute-parser"),
|
||||
value: "brute",
|
||||
},
|
||||
{
|
||||
text: i18n.t("recipe.parser.openai-parser"),
|
||||
value: "openai",
|
||||
hide: !group.value?.aiProviderSettings?.aiEnabled,
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
/**
|
||||
* If confidence of parsing is below this threshold,
|
||||
* we will prompt the user to review the parsed ingredient.
|
||||
*/
|
||||
const confidenceThreshold = 0.85;
|
||||
const parsedIngs = ref<ParsedIngredient[]>([]);
|
||||
|
||||
const currentIng = ref<ParsedIngredient | null>(null);
|
||||
const currentMissingUnit = ref("");
|
||||
const currentMissingFood = ref("");
|
||||
const currentIngHasError = computed(() => currentMissingUnit.value || currentMissingFood.value);
|
||||
const currentIngShouldDelete = ref(false);
|
||||
|
||||
const state = reactive({
|
||||
currentParsedIndex: -1,
|
||||
allReviewed: false,
|
||||
loading: {
|
||||
parser: false,
|
||||
save: false,
|
||||
},
|
||||
});
|
||||
|
||||
function shouldReview(ing: ParsedIngredient): boolean {
|
||||
console.debug(`Checking if ingredient needs review (input="${ing.input})":`, ing);
|
||||
|
||||
if (ing.ingredient.referencedRecipe) {
|
||||
console.debug("No review needed for sub-recipe ingredient");
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((ing.confidence?.average || 0) < confidenceThreshold) {
|
||||
console.debug("Needs review due to low confidence:", ing.confidence?.average);
|
||||
return true;
|
||||
}
|
||||
|
||||
const food = ing.ingredient.food;
|
||||
if (food && !food.id) {
|
||||
console.debug("Needs review due to missing food ID:", food);
|
||||
return true;
|
||||
}
|
||||
|
||||
const unit = ing.ingredient.unit;
|
||||
if (unit && !unit.id) {
|
||||
console.debug("Needs review due to missing unit ID:", unit);
|
||||
return true;
|
||||
}
|
||||
|
||||
console.debug("No review needed");
|
||||
return false;
|
||||
}
|
||||
|
||||
function checkUnit(ing: ParsedIngredient) {
|
||||
const unit = ing.ingredient.unit?.name;
|
||||
if (!unit || ing.ingredient.unit?.id) {
|
||||
currentMissingUnit.value = "";
|
||||
return;
|
||||
}
|
||||
|
||||
const potentialMatch = createdUnits.get(unit.toLowerCase());
|
||||
if (potentialMatch) {
|
||||
ing.ingredient.unit = potentialMatch;
|
||||
currentMissingUnit.value = "";
|
||||
return;
|
||||
}
|
||||
|
||||
currentMissingUnit.value = unit;
|
||||
ing.ingredient.unit = undefined;
|
||||
}
|
||||
|
||||
function checkFood(ing: ParsedIngredient) {
|
||||
const food = ing.ingredient.food?.name;
|
||||
if (!food || ing.ingredient.food?.id) {
|
||||
currentMissingFood.value = "";
|
||||
return;
|
||||
}
|
||||
|
||||
const potentialMatch = createdFoods.get(food.toLowerCase());
|
||||
if (potentialMatch) {
|
||||
ing.ingredient.food = potentialMatch;
|
||||
currentMissingFood.value = "";
|
||||
return;
|
||||
}
|
||||
|
||||
currentMissingFood.value = food;
|
||||
ing.ingredient.food = undefined;
|
||||
}
|
||||
|
||||
function nextIngredient() {
|
||||
let nextIndex = state.currentParsedIndex;
|
||||
if (currentIngShouldDelete.value) {
|
||||
parsedIngs.value.splice(state.currentParsedIndex, 1);
|
||||
currentIngShouldDelete.value = false;
|
||||
}
|
||||
else {
|
||||
nextIndex += 1;
|
||||
}
|
||||
|
||||
while (nextIndex < parsedIngs.value.length) {
|
||||
const current = parsedIngs.value[nextIndex];
|
||||
if (shouldReview(current)) {
|
||||
state.currentParsedIndex = nextIndex;
|
||||
currentIng.value = current;
|
||||
currentIngShouldDelete.value = false;
|
||||
checkUnit(current);
|
||||
checkFood(current);
|
||||
return;
|
||||
}
|
||||
|
||||
nextIndex += 1;
|
||||
}
|
||||
|
||||
// No more to review
|
||||
state.allReviewed = true;
|
||||
}
|
||||
|
||||
/** Clear everything left over from a previous run, so re-opening the dialog starts clean */
|
||||
function resetParserState() {
|
||||
parsedIngs.value = [];
|
||||
currentIng.value = null;
|
||||
currentMissingUnit.value = "";
|
||||
currentMissingFood.value = "";
|
||||
currentIngShouldDelete.value = false;
|
||||
state.currentParsedIndex = -1;
|
||||
state.allReviewed = false;
|
||||
state.loading.save = false;
|
||||
createdUnits.clear();
|
||||
createdFoods.clear();
|
||||
}
|
||||
|
||||
async function parseIngredients() {
|
||||
if (state.loading.parser) {
|
||||
return;
|
||||
}
|
||||
|
||||
resetParserState();
|
||||
|
||||
if (!props.ingredients || props.ingredients.length === 0) {
|
||||
state.loading.parser = false;
|
||||
return;
|
||||
}
|
||||
state.loading.parser = true;
|
||||
try {
|
||||
const filteredIngredients = props.ingredients.filter(ing => !ing.referencedRecipe);
|
||||
const ingsAsString = filteredIngredients.map(ing => ingredientToParserString(ing));
|
||||
const { data, error } = await api.recipes.parseIngredients(parser.value, ingsAsString);
|
||||
if (error || !data) {
|
||||
throw new Error("Failed to parse ingredients");
|
||||
}
|
||||
|
||||
// Restore section titles from original ingredients — the parser doesn't return them
|
||||
data.forEach((parsed, index) => {
|
||||
parsed.ingredient.title = filteredIngredients[index]?.title || "";
|
||||
});
|
||||
|
||||
const parsed = data ?? [];
|
||||
const recipeRefs = props.ingredients.filter(ing => ing.referencedRecipe).map(ing => ({
|
||||
input: ing.note || "",
|
||||
confidence: {},
|
||||
ingredient: ing,
|
||||
}));
|
||||
parsedIngs.value = [...parsed, ...recipeRefs];
|
||||
nextIngredient();
|
||||
}
|
||||
catch (error) {
|
||||
console.error("Error parsing ingredients:", error);
|
||||
alert.error(i18n.t("events.something-went-wrong"));
|
||||
}
|
||||
finally {
|
||||
state.loading.parser = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Cache of lowercased created units to avoid duplicate creations */
|
||||
const createdUnits = new Map<string, IngredientUnit>();
|
||||
/** Cache of lowercased created foods to avoid duplicate creations */
|
||||
const createdFoods = new Map<string, IngredientFood>();
|
||||
|
||||
async function createMissingUnit() {
|
||||
if (!currentMissingUnit.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
unitData.reset();
|
||||
unitData.data.name = currentMissingUnit.value;
|
||||
|
||||
let newUnit: IngredientUnit | null = null;
|
||||
if (createdUnits.has(unitData.data.name)) {
|
||||
newUnit = createdUnits.get(unitData.data.name)!;
|
||||
}
|
||||
else {
|
||||
newUnit = await unitStore.actions.createOne(unitData.data);
|
||||
}
|
||||
|
||||
if (!newUnit) {
|
||||
alert.error(i18n.t("events.something-went-wrong"));
|
||||
return;
|
||||
}
|
||||
|
||||
currentIng.value!.ingredient.unit = newUnit;
|
||||
createdUnits.set(newUnit.name.toLowerCase(), newUnit);
|
||||
currentMissingUnit.value = "";
|
||||
}
|
||||
|
||||
async function createMissingFood() {
|
||||
if (!currentMissingFood.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
foodData.reset();
|
||||
foodData.data.name = currentMissingFood.value;
|
||||
|
||||
let newFood: IngredientFood | null = null;
|
||||
if (createdFoods.has(foodData.data.name)) {
|
||||
newFood = createdFoods.get(foodData.data.name)!;
|
||||
}
|
||||
else {
|
||||
newFood = await foodStore.actions.createOne(foodData.data);
|
||||
}
|
||||
|
||||
if (!newFood) {
|
||||
alert.error(i18n.t("events.something-went-wrong"));
|
||||
return;
|
||||
}
|
||||
|
||||
currentIng.value!.ingredient.food = newFood;
|
||||
createdFoods.set(newFood.name.toLowerCase(), newFood);
|
||||
currentMissingFood.value = "";
|
||||
}
|
||||
|
||||
async function addMissingUnitAsAlias() {
|
||||
const unit = currentIng.value?.ingredient.unit as IngredientUnit | undefined;
|
||||
if (!currentMissingUnit.value || !unit?.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
unit.aliases = unit.aliases || [];
|
||||
if (unit.aliases.map(a => a.name).includes(currentMissingUnit.value)) {
|
||||
return;
|
||||
}
|
||||
|
||||
unit.aliases.push({ name: currentMissingUnit.value });
|
||||
const updated = await unitStore.actions.updateOne(unit);
|
||||
if (!updated) {
|
||||
alert.error(i18n.t("events.something-went-wrong"));
|
||||
return;
|
||||
}
|
||||
|
||||
currentIng.value!.ingredient.unit = updated;
|
||||
currentMissingUnit.value = "";
|
||||
}
|
||||
|
||||
async function addMissingFoodAsAlias() {
|
||||
const food = currentIng.value?.ingredient.food as IngredientFood | undefined;
|
||||
if (!currentMissingFood.value || !food?.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
food.aliases = food.aliases || [];
|
||||
if (food.aliases.map(a => a.name).includes(currentMissingFood.value)) {
|
||||
return;
|
||||
}
|
||||
|
||||
food.aliases.push({ name: currentMissingFood.value });
|
||||
const updated = await foodStore.actions.updateOne(food);
|
||||
if (!updated) {
|
||||
alert.error(i18n.t("events.something-went-wrong"));
|
||||
return;
|
||||
}
|
||||
|
||||
currentIng.value!.ingredient.food = updated;
|
||||
currentMissingFood.value = "";
|
||||
}
|
||||
|
||||
watch(() => props.modelValue, () => {
|
||||
if (!props.modelValue) {
|
||||
return;
|
||||
}
|
||||
|
||||
parseIngredients();
|
||||
});
|
||||
|
||||
watch(parser, () => {
|
||||
parserPreferences.value.parser = parser.value;
|
||||
parseIngredients();
|
||||
});
|
||||
|
||||
watch([parsedIngs, () => state.allReviewed], () => {
|
||||
if (!state.allReviewed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!parsedIngs.value.length) {
|
||||
insertNewIngredient(0);
|
||||
}
|
||||
}, { immediate: true, deep: true });
|
||||
|
||||
function asPercentage(num: number | undefined): string {
|
||||
if (!num) {
|
||||
return "0%";
|
||||
}
|
||||
|
||||
return Math.round(num * 100).toFixed(2) + "%";
|
||||
}
|
||||
|
||||
function insertNewIngredient(index: number) {
|
||||
const ing = {
|
||||
input: "",
|
||||
confidence: {},
|
||||
ingredient: {
|
||||
quantity: 0,
|
||||
referenceId: uuid4(),
|
||||
},
|
||||
} as ParsedIngredient;
|
||||
|
||||
parsedIngs.value.splice(index, 0, ing);
|
||||
}
|
||||
|
||||
function saveIngs() {
|
||||
emit("save", parsedIngs.value.map(x => x.ingredient as NoUndefinedField<RecipeIngredient>));
|
||||
state.loading.save = true;
|
||||
}
|
||||
</script>
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
<template>
|
||||
<v-card
|
||||
variant="outlined"
|
||||
color="info"
|
||||
class="d-flex justify-space-between align-center"
|
||||
@click="$emit('parse')"
|
||||
>
|
||||
<v-card-text>
|
||||
{{ $t('recipe.parser.try-again-with-parser', { parser: currentParserText }) }}
|
||||
</v-card-text>
|
||||
<v-card-actions>
|
||||
<BaseButton edit minor @click.stop="open = true">
|
||||
{{ $t('recipe.parser.select-parser') }}
|
||||
</BaseButton>
|
||||
</v-card-actions>
|
||||
</v-card>
|
||||
<BaseDialog
|
||||
v-model="open"
|
||||
:title="$t('recipe.parser.select-parser')"
|
||||
:icon="$globals.icons.fileSign"
|
||||
>
|
||||
<v-list>
|
||||
<v-list-item
|
||||
v-for="(parser) in availableParsers.filter(({ hide }) => !hide)"
|
||||
:key="parser.value"
|
||||
link
|
||||
:append-icon="$globals.icons.chevronRight"
|
||||
@click="
|
||||
currentParser = parser.value as Parser;
|
||||
$emit('parse')
|
||||
"
|
||||
>
|
||||
{{ parser.text }}
|
||||
</v-list-item>
|
||||
</v-list>
|
||||
</BaseDialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { MenuItem } from "~/components/global/BaseOverflowButton.vue";
|
||||
import type { Parser } from "~/lib/api/user/recipes/recipe";
|
||||
|
||||
defineProps<{ availableParsers: MenuItem[] }>();
|
||||
const emit = defineEmits<{ parse: [] }>();
|
||||
const currentParser = defineModel<Parser>({ default: "nlp" });
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const currentParserText = computed(() => {
|
||||
switch (currentParser.value) {
|
||||
case "brute": return t("recipe.parser.brute-parser");
|
||||
case "openai": return t("recipe.parser.openai-parser");
|
||||
}
|
||||
return t("recipe.parser.natural-language-processor");
|
||||
});
|
||||
const open = ref(false);
|
||||
watch(currentParser, () => emit("parse"));
|
||||
</script>
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
<template>
|
||||
<v-empty-state color="success" :icon="$globals.icons.progressCheck" :headline="$t('recipe.parser.ingredient-parser-headline')">
|
||||
<div class="d-flex ga-2 flex-column">
|
||||
<h3 class="my-0">
|
||||
{{ $t("recipe.parser.ingredient-parser-title") }}
|
||||
</h3>
|
||||
<p>{{ $t("recipe.parser.ingredient-parser-description") }}</p>
|
||||
<p>{{ $t("recipe.parser.ingredient-parser-final-review-description") }}</p>
|
||||
<h3 class="mb-0">
|
||||
{{ $t("recipe.parser.ingredient-parser-result-title") }}
|
||||
</h3>
|
||||
<div class="d-flex ga-2 flex-wrap">
|
||||
<v-chip v-if="autoParsed" size="large" color="success" :prepend-icon="$globals.icons.checkboxMarkedCircle">
|
||||
{{ $t("recipe.parser.ingredient-parser-result-success", autoParsed) }}
|
||||
</v-chip>
|
||||
<v-chip size="large" color="warning" :prepend-icon="$globals.icons.alert">
|
||||
{{ $t("recipe.parser.ingredient-parser-result-failed", toReview) }}
|
||||
</v-chip>
|
||||
</div>
|
||||
</div>
|
||||
</v-empty-state>
|
||||
<v-checkbox
|
||||
v-model="dontShowAgain"
|
||||
class="ml-3"
|
||||
hide-details
|
||||
density="compact"
|
||||
:label="$t('recipe.parser.dont-show-again')"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const dontShowAgain = defineModel<boolean>({ default: true });
|
||||
defineProps<{
|
||||
autoParsed: number;
|
||||
toReview: number;
|
||||
}>();
|
||||
</script>
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
<template>
|
||||
<ParseDialogChangeParser
|
||||
v-model="parser"
|
||||
:available-parsers="availableParsers"
|
||||
@update:model-value="(newParser) => parser = newParser"
|
||||
@parse="parseIngredients"
|
||||
/>
|
||||
<v-card-text v-if="currentIng" class="pb-0 mb-0 d-flex flex-column ga-2">
|
||||
<div class="text-center px-8 py-4 mb-6 bg-background-darken-1 rounded-pill">
|
||||
<p class="text-h5 font-italic">
|
||||
{{ currentIng.input }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="d-flex align-center pa-0 ma-0">
|
||||
<v-icon
|
||||
:color="(currentIng.confidence?.average || 0) < confidenceThreshold ? 'error' : 'success'"
|
||||
>
|
||||
{{ (currentIng.confidence?.average || 0) < confidenceThreshold ? $globals.icons.alert : $globals.icons.check }}
|
||||
</v-icon>
|
||||
<span
|
||||
class="ml-2"
|
||||
:color="currentIngHasError ? 'error-text' : 'success-text'"
|
||||
>
|
||||
{{ $t("recipe.parser.confidence-score") }}: {{ currentIng.confidence ? asPercentage(currentIng.confidence?.average!) : "" }}
|
||||
</span>
|
||||
</div>
|
||||
<RecipeIngredientEditor
|
||||
v-model="currentIng.ingredient"
|
||||
:unit-error="!!currentMissingUnit"
|
||||
:unit-error-tooltip="$t('recipe.parser.this-unit-could-not-be-parsed-automatically')"
|
||||
:food-error="!!currentMissingFood"
|
||||
:food-error-tooltip="$t('recipe.parser.this-food-could-not-be-parsed-automatically')"
|
||||
/>
|
||||
<v-card-actions class="flex-wrap">
|
||||
<v-checkbox
|
||||
v-model="currentIngShouldDelete"
|
||||
color="error"
|
||||
hide-details
|
||||
density="compact"
|
||||
class="mt-8"
|
||||
:label="$t('recipe.parser.delete-item')"
|
||||
/>
|
||||
<v-spacer />
|
||||
<BaseButton
|
||||
v-if="currentMissingUnit && !currentIng.ingredient.unit?.id"
|
||||
:icon="$globals.icons.units"
|
||||
color="warning"
|
||||
size="small"
|
||||
@click="createMissingUnit"
|
||||
>
|
||||
{{ $t("recipe.parser.missing-unit", { unit: currentMissingUnit }) }}
|
||||
</BaseButton>
|
||||
<BaseButton
|
||||
v-if="
|
||||
currentMissingUnit
|
||||
&& currentIng.ingredient.unit?.id
|
||||
&& currentMissingUnit.toLowerCase() != currentIng.ingredient.unit?.name.toLowerCase()
|
||||
"
|
||||
:icon="$globals.icons.units"
|
||||
color="warning"
|
||||
size="small"
|
||||
@click="addMissingUnitAsAlias"
|
||||
>
|
||||
{{ $t("recipe.parser.add-text-as-alias-for-item", { text: currentMissingUnit, item: currentIng.ingredient.unit.name }) }}
|
||||
</BaseButton>
|
||||
<BaseButton
|
||||
v-if="currentMissingFood && !currentIng.ingredient.food?.id"
|
||||
:icon="$globals.icons.foods"
|
||||
color="warning"
|
||||
size="small"
|
||||
@click="createMissingFood"
|
||||
>
|
||||
{{ $t("recipe.parser.missing-food", { food: currentMissingFood }) }}
|
||||
</BaseButton>
|
||||
<BaseButton
|
||||
v-if="
|
||||
currentMissingFood
|
||||
&& currentIng.ingredient.food?.id
|
||||
&& currentMissingFood.toLowerCase() != currentIng.ingredient.food?.name.toLowerCase()
|
||||
"
|
||||
:icon="$globals.icons.foods"
|
||||
color="warning"
|
||||
size="small"
|
||||
@click="addMissingFoodAsAlias"
|
||||
>
|
||||
{{ $t("recipe.parser.add-text-as-alias-for-item", { text: currentMissingFood, item: currentIng.ingredient.food.name }) }}
|
||||
</BaseButton>
|
||||
</v-card-actions>
|
||||
</v-card-text>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { useParseIngredientsDialog } from "~/composables/recipes/use-parse-ingredients-dialog";
|
||||
|
||||
const props = defineProps<{
|
||||
dialogState: ReturnType<typeof useParseIngredientsDialog>;
|
||||
}>();
|
||||
|
||||
const {
|
||||
currentIng,
|
||||
availableParsers,
|
||||
currentIngShouldDelete,
|
||||
parser,
|
||||
confidenceThreshold,
|
||||
currentIngHasError,
|
||||
currentMissingFood,
|
||||
currentMissingUnit,
|
||||
parseIngredients,
|
||||
createMissingFood,
|
||||
createMissingUnit,
|
||||
addMissingFoodAsAlias,
|
||||
addMissingUnitAsAlias,
|
||||
} = props.dialogState;
|
||||
|
||||
function asPercentage(num: number | undefined): string {
|
||||
if (!num) {
|
||||
return "0%";
|
||||
}
|
||||
|
||||
return Math.round(num * 100).toFixed(2) + "%";
|
||||
}
|
||||
</script>
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
<template>
|
||||
<div class="d-flex flex-column ga-4">
|
||||
<ParseDialogChangeParser
|
||||
v-model="state.parser"
|
||||
:available-parsers="availableParsers"
|
||||
@update:model-value="$emit('changeParser', $event)"
|
||||
@parse="$emit('parse')"
|
||||
/>
|
||||
<div>
|
||||
<v-card-title class="text-center pt-0 pb-8">
|
||||
{{ $t("recipe.parser.review-parsed-ingredients") }}
|
||||
</v-card-title>
|
||||
<v-card-text>
|
||||
<VueDraggable
|
||||
v-model="parsedIngs"
|
||||
handle=".handle"
|
||||
:delay="250"
|
||||
:delay-on-touch-only="true"
|
||||
v-bind="{
|
||||
animation: 200,
|
||||
group: 'recipe-ingredients',
|
||||
disabled: false,
|
||||
ghostClass: 'ghost',
|
||||
}"
|
||||
@start="drag = true"
|
||||
@end="drag = false"
|
||||
>
|
||||
<TransitionGroup type="transition">
|
||||
<v-lazy v-for="(ingredient, index) in parsedIngs" :key="index">
|
||||
<RecipeIngredientEditor
|
||||
v-model="ingredient.ingredient"
|
||||
enable-drag-handle
|
||||
enable-context-menu
|
||||
:delete-disabled="parsedIngs.length <= 1"
|
||||
class="mb-5"
|
||||
@delete="parsedIngs.splice(index, 1)"
|
||||
@insert-above="insertNewIngredient(index)"
|
||||
@insert-below="insertNewIngredient(index + 1)"
|
||||
>
|
||||
<template #before-divider>
|
||||
<p v-if="ingredient.input" class="py-0 my-0 text-caption">
|
||||
{{ $t("recipe.original-text-with-value", { originalText: ingredient.input }) }}
|
||||
</p>
|
||||
</template>
|
||||
</RecipeIngredientEditor>
|
||||
</v-lazy>
|
||||
</TransitionGroup>
|
||||
</VueDraggable>
|
||||
</v-card-text>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { VueDraggable } from "vue-draggable-plus";
|
||||
import type { MenuItem } from "~/components/global/BaseOverflowButton.vue";
|
||||
import type { ParsedIngredient } from "~/lib/api/types/recipe";
|
||||
import type { Parser } from "~/lib/api/user/recipes/recipe";
|
||||
|
||||
defineEmits<{
|
||||
parse: [];
|
||||
changeParser: [Parser];
|
||||
}>();
|
||||
const props = defineProps<{
|
||||
availableParsers: MenuItem[];
|
||||
parser: Parser;
|
||||
}>();
|
||||
const parsedIngs = defineModel<ParsedIngredient[]>({ required: true });
|
||||
|
||||
const state = reactive({
|
||||
parser: props.parser,
|
||||
});
|
||||
|
||||
const drag = ref(false);
|
||||
|
||||
function insertNewIngredient(index: number) {
|
||||
const ing = {
|
||||
input: "",
|
||||
confidence: {},
|
||||
ingredient: {
|
||||
quantity: 0,
|
||||
referenceId: uuid4(),
|
||||
},
|
||||
} as ParsedIngredient;
|
||||
|
||||
parsedIngs.value.splice(index, 0, ing);
|
||||
}
|
||||
</script>
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
<template>
|
||||
<BaseDialog
|
||||
:model-value="modelValue"
|
||||
:title="$t('recipe.parse-ingredients')"
|
||||
:icon="$globals.icons.fileSign"
|
||||
disable-submit-on-enter
|
||||
@update:model-value="emit('update:modelValue', $event)"
|
||||
>
|
||||
<v-container fluid class="pa-2 ma-0">
|
||||
<SwipeTransition direction="left">
|
||||
<!-- These wrapping divs appear to be load-bearing in making sure the transition renders correctly -->
|
||||
<div v-if="state.step === ParseStep.LOADING">
|
||||
<AppLoader class="my-6" :waiting-text="$t('recipe.parser.parsing-ingredients')" />
|
||||
</div>
|
||||
<div v-else-if="state.step === ParseStep.INFO">
|
||||
<ParseDialogInfo v-model="dontShowInfoPage" :auto-parsed="autoParsedIngredientsCount" :to-review="ingredientsToReviewCount" />
|
||||
</div>
|
||||
<div
|
||||
v-else-if="state.step === ParseStep.PARSE && currentIng"
|
||||
:key="currentIng.ingredient.referenceId"
|
||||
>
|
||||
<ParseDialogParse :dialog-state="dialogState" />
|
||||
</div>
|
||||
<div v-else>
|
||||
<ParseDialogReview
|
||||
v-model="parsedIngs"
|
||||
:available-parsers="availableParsers"
|
||||
:parser="parser"
|
||||
@parse="parseIngredients"
|
||||
@change-parser="(newParser) => parser = newParser"
|
||||
/>
|
||||
</div>
|
||||
</SwipeTransition>
|
||||
</v-container>
|
||||
<template v-if="state.step !== ParseStep.LOADING" #custom-card-action>
|
||||
<SwipeTransition direction="left">
|
||||
<BaseButton
|
||||
v-if="state.step === ParseStep.INFO"
|
||||
color="info"
|
||||
icon-right
|
||||
:icon="$globals.icons.arrowRightBold"
|
||||
:text="$t('general.next')"
|
||||
@click="nextStep"
|
||||
/>
|
||||
<BaseButton
|
||||
v-else-if="state.step === ParseStep.PARSE"
|
||||
:color="currentIngShouldDelete ? 'error' : 'info'"
|
||||
:icon="currentIngShouldDelete ? $globals.icons.delete : $globals.icons.arrowRightBold"
|
||||
:icon-right="!currentIngShouldDelete"
|
||||
:text="$t(currentIngShouldDelete ? 'recipe.parser.delete-item' : 'general.next')"
|
||||
@click="nextIngredient"
|
||||
/>
|
||||
<BaseButton
|
||||
v-else-if="state.step === ParseStep.REVIEW"
|
||||
create
|
||||
:text="$t('general.save')"
|
||||
:icon="$globals.icons.save"
|
||||
:loading="state.saveLoading"
|
||||
@click="saveIngs"
|
||||
/>
|
||||
</SwipeTransition>
|
||||
</template>
|
||||
</BaseDialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ParseStep, useParseIngredientsDialog } from "~/composables/recipes/use-parse-ingredients-dialog";
|
||||
import type { NoUndefinedField } from "~/lib/api/types/non-generated";
|
||||
import type { RecipeIngredient } from "~/lib/api/types/recipe";
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: boolean;
|
||||
ingredients: NoUndefinedField<RecipeIngredient[]>;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "update:modelValue", value: boolean): void;
|
||||
(e: "save", value: NoUndefinedField<RecipeIngredient[]>): void;
|
||||
}>();
|
||||
|
||||
const dialogState = useParseIngredientsDialog(props.ingredients, ings => emit("save", ings));
|
||||
|
||||
const {
|
||||
availableParsers,
|
||||
parser,
|
||||
dontShowInfoPage,
|
||||
parsedIngs,
|
||||
currentIng,
|
||||
currentIngShouldDelete,
|
||||
state,
|
||||
autoParsedIngredientsCount,
|
||||
ingredientsToReviewCount,
|
||||
nextStep,
|
||||
saveIngs,
|
||||
nextIngredient,
|
||||
parseIngredients,
|
||||
} = dialogState;
|
||||
|
||||
watch(() => props.modelValue, () => {
|
||||
if (!props.modelValue) {
|
||||
return;
|
||||
}
|
||||
|
||||
parseIngredients();
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,59 @@
|
||||
<template>
|
||||
<TransitionGroup v-if="group" :name="`swipe-${direction}`" appear class="overflow-x-hidden-child">
|
||||
<slot />
|
||||
</TransitionGroup>
|
||||
<Transition v-else :name="`swipe-${direction}`" mode="out-in" appear class="overflow-x-hidden-child">
|
||||
<slot />
|
||||
</Transition>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
withDefaults(defineProps<{
|
||||
direction: "left" | "right";
|
||||
group?: boolean;
|
||||
}>(), {
|
||||
group: false,
|
||||
});
|
||||
</script>
|
||||
|
||||
<style lang="scss">
|
||||
.swipe-left {
|
||||
&-move,
|
||||
&-enter-active,
|
||||
&-leave-active {
|
||||
transition: all 0.3s cubic-bezier(0.5, -0.23, 0.5, 1.25);
|
||||
}
|
||||
|
||||
&-enter-from,
|
||||
&-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
&-enter-from {
|
||||
transform: translateX(30px);
|
||||
}
|
||||
&-leave-to {
|
||||
transform: translateX(-30px);
|
||||
}
|
||||
}
|
||||
.swipe-right {
|
||||
&-move,
|
||||
&-enter-active,
|
||||
&-leave-active {
|
||||
transition: all 0.3s cubic-bezier(0.5, -0.23, 0.5, 1.25);
|
||||
}
|
||||
|
||||
&-enter-from,
|
||||
&-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
&-enter-from {
|
||||
transform: translateX(-30px);
|
||||
}
|
||||
&-leave-to {
|
||||
transform: translateX(30px);
|
||||
}
|
||||
}
|
||||
*:has(.overflow-x-hidden-child) {
|
||||
overflow-x: hidden;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,663 @@
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import type { NoUndefinedField } from "~/lib/api/types/non-generated";
|
||||
import type { ParsedIngredient, RecipeIngredient } from "~/lib/api/types/recipe";
|
||||
import { uuid4 } from "../../use-utils";
|
||||
import { ParseStep, useParseIngredientsDialog } from "../use-parse-ingredients-dialog";
|
||||
import type { Parser } from "~/lib/api/user/recipes/recipe";
|
||||
|
||||
(global as any).uuid4 = uuid4;
|
||||
|
||||
const mockError = vi.spyOn((await import("~/composables/use-toast")).alert, "error");
|
||||
|
||||
const mockParseIngredients = vi.fn().mockResolvedValue({ data: [{ ingredient: {} }] });
|
||||
const onSave = vi.fn();
|
||||
const group = ref({
|
||||
aiProviderSettings: { aiEnabled: true },
|
||||
});
|
||||
vi.stubGlobal("useGroupSelf", vi.fn().mockReturnValue({ group }));
|
||||
|
||||
vi.mock("~/composables/api", () => ({
|
||||
useUserApi: () => ({
|
||||
recipes: { parseIngredients: mockParseIngredients },
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../use-recipe-ingredients", () => ({
|
||||
useIngredientTextParser: () => ({
|
||||
ingredientToParserString: vi.fn().mockReturnValue("4 unit ingredient"),
|
||||
}),
|
||||
}));
|
||||
|
||||
const preferences = ref({
|
||||
parser: "nlp",
|
||||
dontShowInfoPage: true,
|
||||
});
|
||||
vi.mock("../../use-users/preferences", () => ({
|
||||
useParsingPreferences: () => preferences,
|
||||
}));
|
||||
|
||||
const createFood = vi.fn().mockResolvedValue({ id: "food_id", name: "fuwud" });
|
||||
const updateFood = vi.fn().mockResolvedValue({ id: "food_id", name: "fuwud" });
|
||||
const foodStore = {
|
||||
actions: {
|
||||
createOne: createFood,
|
||||
updateOne: updateFood,
|
||||
},
|
||||
};
|
||||
|
||||
const createUnit = vi.fn().mockResolvedValue({ id: "unit_id", name: "uwunit" });
|
||||
const updateUnit = vi.fn().mockResolvedValue({ id: "unit_id", name: "uwunit" });
|
||||
const unitStore = {
|
||||
actions: {
|
||||
createOne: createUnit,
|
||||
updateOne: updateUnit,
|
||||
},
|
||||
};
|
||||
|
||||
vi.mock("~/composables/store", async (importOriginal) => {
|
||||
const original: object = await importOriginal();
|
||||
return {
|
||||
...original,
|
||||
useFoodStore: () => foodStore,
|
||||
useUnitStore: () => unitStore,
|
||||
};
|
||||
});
|
||||
|
||||
const wrapper = (ingredients: NoUndefinedField<RecipeIngredient>[] = [{}, { referencedRecipe: {} }] as NoUndefinedField<RecipeIngredient>[]) => {
|
||||
const TestComponent = defineComponent({
|
||||
template: "<div />",
|
||||
props: {},
|
||||
setup() {
|
||||
const x = useParseIngredientsDialog(ingredients, onSave);
|
||||
return {
|
||||
setCurrentFood(str: string) {
|
||||
x.currentMissingFood.value = str;
|
||||
},
|
||||
setCurrentUnit(str: string) {
|
||||
x.currentMissingUnit.value = str;
|
||||
},
|
||||
setParsedIngs(ings: ParsedIngredient[]) {
|
||||
x.parsedIngs.value = ings;
|
||||
},
|
||||
setShouldDelete(should: boolean) {
|
||||
x.currentIngShouldDelete.value = should;
|
||||
},
|
||||
setCurrentIng(ing: ParsedIngredient) {
|
||||
x.currentIng.value = ing;
|
||||
},
|
||||
setParser(parser: Parser) {
|
||||
x.parser.value = parser;
|
||||
},
|
||||
setDontShow(dontShow: boolean) {
|
||||
x.dontShowInfoPage.value = dontShow;
|
||||
},
|
||||
...x,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const wrapper = mount(TestComponent, { props: {} });
|
||||
return wrapper;
|
||||
};
|
||||
|
||||
describe("useParseIngredientsDialog", () => {
|
||||
beforeEach(() => {
|
||||
group.value.aiProviderSettings.aiEnabled = true;
|
||||
preferences.value = {
|
||||
parser: "nlp",
|
||||
dontShowInfoPage: false,
|
||||
};
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe("nextIngredient", () => {
|
||||
test("steps through the ingredients", () => {
|
||||
const wrapped = wrapper();
|
||||
const { nextIngredient, setParsedIngs } = wrapped.vm;
|
||||
setParsedIngs([{
|
||||
ingredient: {},
|
||||
confidence: { average: 0.5 },
|
||||
}, {
|
||||
ingredient: {},
|
||||
}, {
|
||||
ingredient: {
|
||||
food: {
|
||||
id: "",
|
||||
name: "fuwud",
|
||||
},
|
||||
},
|
||||
confidence: { average: 0.99 },
|
||||
}, {
|
||||
ingredient: {
|
||||
unit: {
|
||||
id: "",
|
||||
name: "uwunit",
|
||||
},
|
||||
},
|
||||
confidence: { average: 0.99 },
|
||||
}]);
|
||||
const { state } = wrapped.vm;
|
||||
expect(state.currentParsedIndex).toBe(-1);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(0);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(1);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(2);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(3);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(3);
|
||||
expect(state.allReviewed).toBe(true);
|
||||
});
|
||||
test("skips over ingredients that don't need to be reviewed", () => {
|
||||
const wrapped = wrapper();
|
||||
const { nextIngredient, setParsedIngs } = wrapped.vm;
|
||||
setParsedIngs([{
|
||||
ingredient: {},
|
||||
confidence: { average: 0.5 },
|
||||
}, {
|
||||
ingredient: {},
|
||||
confidence: { average: 0.99 },
|
||||
}, {
|
||||
ingredient: {
|
||||
referencedRecipe: {},
|
||||
},
|
||||
confidence: { average: 0.5 },
|
||||
}, {
|
||||
ingredient: {},
|
||||
confidence: { average: 0.5 },
|
||||
}]);
|
||||
const { state } = wrapped.vm;
|
||||
expect(wrapped.vm.ingredientsToReviewCount).toBe(2);
|
||||
expect(wrapped.vm.autoParsedIngredientsCount).toBe(2);
|
||||
expect(state.currentParsedIndex).toBe(-1);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(0);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(3);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(3);
|
||||
expect(state.allReviewed).toBe(true);
|
||||
});
|
||||
test("skips over deleted ingredients properly", () => {
|
||||
const wrapped = wrapper();
|
||||
const { nextIngredient, setParsedIngs, setShouldDelete } = wrapped.vm;
|
||||
setParsedIngs([{
|
||||
ingredient: {},
|
||||
confidence: { average: 0.5 },
|
||||
}, {
|
||||
ingredient: {},
|
||||
confidence: { average: 0.5 },
|
||||
}, {
|
||||
ingredient: {},
|
||||
confidence: { average: 0.5 },
|
||||
}]);
|
||||
const { state } = wrapped.vm;
|
||||
expect(state.currentParsedIndex).toBe(-1);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
expect(wrapped.vm.currentIngShouldDelete).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(0);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
expect(wrapped.vm.currentIngShouldDelete).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(1);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
expect(wrapped.vm.currentIngShouldDelete).toBe(false);
|
||||
setShouldDelete(true);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(1);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
expect(wrapped.vm.currentIngShouldDelete).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(1);
|
||||
expect(state.allReviewed).toBe(true);
|
||||
expect(wrapped.vm.currentIngShouldDelete).toBe(false);
|
||||
});
|
||||
test("pulls from cache when it can", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { createMissingUnit, createMissingFood, nextIngredient, setCurrentUnit, setCurrentFood, setCurrentIng, setParsedIngs } = wrapped.vm;
|
||||
setParsedIngs([{
|
||||
ingredient: {},
|
||||
confidence: { average: 0.5 },
|
||||
}, {
|
||||
ingredient: {},
|
||||
}, {
|
||||
ingredient: {
|
||||
food: {
|
||||
id: "",
|
||||
name: "fuwud",
|
||||
},
|
||||
},
|
||||
confidence: { average: 0.99 },
|
||||
}, {
|
||||
ingredient: {
|
||||
unit: {
|
||||
id: "",
|
||||
name: "uwunit",
|
||||
},
|
||||
},
|
||||
confidence: { average: 0.99 },
|
||||
}]);
|
||||
setCurrentIng({
|
||||
ingredient: {},
|
||||
});
|
||||
setCurrentUnit("uwunit");
|
||||
setCurrentFood("fuwud");
|
||||
await createMissingUnit();
|
||||
await createMissingFood();
|
||||
createUnit.mockClear();
|
||||
createFood.mockClear();
|
||||
const { state } = wrapped.vm;
|
||||
expect(state.currentParsedIndex).toBe(-1);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(0);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(1);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(2);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(3);
|
||||
expect(state.allReviewed).toBe(false);
|
||||
nextIngredient();
|
||||
expect(state.currentParsedIndex).toBe(3);
|
||||
expect(state.allReviewed).toBe(true);
|
||||
expect(createUnit).not.toHaveBeenCalled();
|
||||
expect(createFood).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
describe("nextStep", () => {
|
||||
test("walks through the workflow", () => {
|
||||
const { nextStep, state } = wrapper().vm;
|
||||
expect(state.step).toBe(ParseStep.LOADING);
|
||||
nextStep();
|
||||
expect(state.step).toBe(ParseStep.INFO);
|
||||
nextStep();
|
||||
expect(state.step).toBe(ParseStep.PARSE);
|
||||
nextStep();
|
||||
expect(state.step).toBe(ParseStep.REVIEW);
|
||||
});
|
||||
test("skips the info page if already seen", () => {
|
||||
preferences.value.dontShowInfoPage = true;
|
||||
const { nextStep, state } = wrapper().vm;
|
||||
expect(state.step).toBe(ParseStep.LOADING);
|
||||
nextStep();
|
||||
expect(state.step).toBe(ParseStep.PARSE);
|
||||
nextStep();
|
||||
expect(state.step).toBe(ParseStep.REVIEW);
|
||||
});
|
||||
test("skips the parse page if nothing to confirm", () => {
|
||||
const { nextStep, state } = wrapper().vm;
|
||||
state.allReviewed = true;
|
||||
expect(state.step).toBe(ParseStep.LOADING);
|
||||
nextStep();
|
||||
expect(state.step).toBe(ParseStep.INFO);
|
||||
nextStep();
|
||||
expect(state.step).toBe(ParseStep.REVIEW);
|
||||
});
|
||||
test("skips the info page if already seen", () => {
|
||||
preferences.value.dontShowInfoPage = true;
|
||||
const { nextStep, state } = wrapper().vm;
|
||||
expect(state.step).toBe(ParseStep.LOADING);
|
||||
nextStep();
|
||||
expect(state.step).toBe(ParseStep.PARSE);
|
||||
nextStep();
|
||||
expect(state.step).toBe(ParseStep.REVIEW);
|
||||
});
|
||||
test("skips the info and parse pages if necessary", () => {
|
||||
preferences.value.dontShowInfoPage = true;
|
||||
const { nextStep, state } = wrapper().vm;
|
||||
state.allReviewed = true;
|
||||
expect(state.step).toBe(ParseStep.LOADING);
|
||||
nextStep();
|
||||
expect(state.step).toBe(ParseStep.REVIEW);
|
||||
});
|
||||
});
|
||||
describe("currentIngHasError", () => {
|
||||
test("is true if either food or unit have an error", () => {
|
||||
const wrapped = wrapper();
|
||||
const { setCurrentFood, setCurrentUnit } = wrapped.vm;
|
||||
setCurrentFood("");
|
||||
setCurrentUnit("");
|
||||
expect(wrapped.vm.currentIngHasError).toBeFalsy();
|
||||
setCurrentFood("food");
|
||||
setCurrentUnit("");
|
||||
expect(wrapped.vm.currentIngHasError).toBeTruthy();
|
||||
setCurrentFood("");
|
||||
setCurrentUnit("unit");
|
||||
expect(wrapped.vm.currentIngHasError).toBeTruthy();
|
||||
setCurrentFood("food");
|
||||
setCurrentUnit("unit");
|
||||
expect(wrapped.vm.currentIngHasError).toBeTruthy();
|
||||
});
|
||||
});
|
||||
describe("availableParsers", () => {
|
||||
test("shows open ai parser when available", () => {
|
||||
const { availableParsers } = wrapper().vm;
|
||||
expect(availableParsers.find(({ value }) => value === "openai")?.hide).toBe(false);
|
||||
});
|
||||
test("hides open ai parser when not available", () => {
|
||||
group.value.aiProviderSettings.aiEnabled = false;
|
||||
const { availableParsers } = wrapper().vm;
|
||||
expect(availableParsers.find(({ value }) => value === "openai")?.hide).toBe(true);
|
||||
});
|
||||
});
|
||||
test("saveIngs", () => {
|
||||
const wrapped = wrapper();
|
||||
const { state, saveIngs, setParsedIngs } = wrapped.vm;
|
||||
setParsedIngs([{
|
||||
ingredient: {},
|
||||
confidence: { average: 0.5 },
|
||||
}, {
|
||||
ingredient: {},
|
||||
confidence: { average: 0.99 },
|
||||
}, {
|
||||
ingredient: {
|
||||
referencedRecipe: {},
|
||||
},
|
||||
confidence: { average: 0.5 },
|
||||
}, {
|
||||
ingredient: {},
|
||||
confidence: { average: 0.5 },
|
||||
}]);
|
||||
saveIngs();
|
||||
expect(state.saveLoading).toBe(true);
|
||||
expect(onSave).toHaveBeenCalled();
|
||||
});
|
||||
describe("parseIngredients", () => {
|
||||
test("parses ingredients", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { state, parseIngredients } = wrapped.vm;
|
||||
const promise = parseIngredients();
|
||||
expect(state.step).toBe(ParseStep.LOADING);
|
||||
expect(state.saveLoading).toBe(false);
|
||||
expect(state.loadingCount).toBe(1);
|
||||
await promise;
|
||||
expect(state.step).toBe(ParseStep.INFO);
|
||||
expect(state.loadingCount).toBe(0);
|
||||
expect(mockParseIngredients).toHaveBeenCalled();
|
||||
});
|
||||
test("only makes one call at a time", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { state, parseIngredients } = wrapped.vm;
|
||||
const promise = parseIngredients();
|
||||
expect(state.step).toBe(ParseStep.LOADING);
|
||||
expect(state.saveLoading).toBe(false);
|
||||
expect(state.loadingCount).toBe(1);
|
||||
parseIngredients(); // Second call
|
||||
await promise;
|
||||
expect(state.step).toBe(ParseStep.INFO);
|
||||
expect(state.loadingCount).toBe(0);
|
||||
expect(mockParseIngredients).toHaveBeenCalledOnce();
|
||||
});
|
||||
test("doesn't parse from an empty list", async () => {
|
||||
const wrapped = wrapper([]);
|
||||
const { state, parseIngredients } = wrapped.vm;
|
||||
const promise = parseIngredients();
|
||||
expect(state.step).toBe(ParseStep.INFO);
|
||||
expect(state.saveLoading).toBe(false);
|
||||
expect(state.loadingCount).toBe(0);
|
||||
await promise;
|
||||
expect(state.step).toBe(ParseStep.INFO);
|
||||
expect(state.loadingCount).toBe(0);
|
||||
expect(mockParseIngredients).not.toHaveBeenCalled();
|
||||
});
|
||||
test("handles errors gracefully", async () => {
|
||||
mockParseIngredients.mockRejectedValue("💥 Woe, exception be upon ye 💥");
|
||||
const wrapped = wrapper();
|
||||
const { state, parseIngredients } = wrapped.vm;
|
||||
const promise = parseIngredients();
|
||||
expect(state.step).toBe(ParseStep.LOADING);
|
||||
expect(state.saveLoading).toBe(false);
|
||||
expect(state.loadingCount).toBe(1);
|
||||
await promise;
|
||||
expect(state.step).toBe(ParseStep.INFO);
|
||||
expect(state.loadingCount).toBe(0);
|
||||
expect(mockError).toHaveBeenCalled();
|
||||
});
|
||||
test("handles errors gracefully", async () => {
|
||||
mockParseIngredients.mockResolvedValue({ data: undefined });
|
||||
const wrapped = wrapper();
|
||||
const { state, parseIngredients } = wrapped.vm;
|
||||
const promise = parseIngredients();
|
||||
expect(state.step).toBe(ParseStep.LOADING);
|
||||
expect(state.saveLoading).toBe(false);
|
||||
expect(state.loadingCount).toBe(1);
|
||||
await promise;
|
||||
expect(state.step).toBe(ParseStep.INFO);
|
||||
expect(state.loadingCount).toBe(0);
|
||||
expect(mockError).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
describe("create and alias food and unit", () => {
|
||||
test("createMissingUnit", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { createMissingUnit, setCurrentUnit, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {},
|
||||
});
|
||||
setCurrentUnit("uwunit");
|
||||
await createMissingUnit();
|
||||
expect(createUnit).toHaveBeenCalled();
|
||||
expect(wrapped.vm.currentIng?.ingredient.unit?.name).toBe("uwunit");
|
||||
});
|
||||
test("createMissingUnit skips if not missing a unit", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { createMissingUnit, setCurrentUnit, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {},
|
||||
});
|
||||
setCurrentUnit("uwunit");
|
||||
await createMissingUnit();
|
||||
createUnit.mockClear();
|
||||
await createMissingUnit();
|
||||
expect(createUnit).not.toHaveBeenCalled();
|
||||
expect(wrapped.vm.currentIng?.ingredient.unit?.name).toBe("uwunit");
|
||||
});
|
||||
test("createMissingUnit pulls from cache", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { createMissingUnit, setCurrentUnit, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {},
|
||||
});
|
||||
setCurrentUnit("uwunit");
|
||||
await createMissingUnit();
|
||||
createUnit.mockClear();
|
||||
setCurrentUnit("uwunit");
|
||||
await createMissingUnit();
|
||||
expect(createUnit).not.toHaveBeenCalled();
|
||||
expect(wrapped.vm.currentIng?.ingredient.unit?.name).toBe("uwunit");
|
||||
});
|
||||
test("createMissingUnit handles undefined values", async () => {
|
||||
createUnit.mockReturnValue(undefined);
|
||||
const wrapped = wrapper();
|
||||
const { createMissingUnit, setCurrentUnit, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {},
|
||||
});
|
||||
setCurrentUnit("uwunit");
|
||||
await createMissingUnit();
|
||||
expect(mockError).toHaveBeenCalled();
|
||||
});
|
||||
test("createMissingFood", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { createMissingFood, setCurrentFood, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {},
|
||||
});
|
||||
setCurrentFood("fuwud");
|
||||
await createMissingFood();
|
||||
expect(createFood).toHaveBeenCalled();
|
||||
expect(wrapped.vm.currentIng?.ingredient.food?.name).toBe("fuwud");
|
||||
});
|
||||
test("createMissingFood skips if not missing a unit", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { createMissingFood, setCurrentFood, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {},
|
||||
});
|
||||
setCurrentFood("fuwud");
|
||||
await createMissingFood();
|
||||
createFood.mockClear();
|
||||
await createMissingFood();
|
||||
expect(createFood).not.toHaveBeenCalled();
|
||||
expect(wrapped.vm.currentIng?.ingredient.food?.name).toBe("fuwud");
|
||||
});
|
||||
test("createMissingFood pulls from cache", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { createMissingFood, setCurrentFood, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {},
|
||||
});
|
||||
setCurrentFood("fuwud");
|
||||
await createMissingFood();
|
||||
createFood.mockClear();
|
||||
setCurrentFood("fuwud");
|
||||
await createMissingFood();
|
||||
expect(createFood).not.toHaveBeenCalled();
|
||||
expect(wrapped.vm.currentIng?.ingredient.food?.name).toBe("fuwud");
|
||||
});
|
||||
test("createMissingFood handles undefined values", async () => {
|
||||
createFood.mockReturnValue(undefined);
|
||||
const wrapped = wrapper();
|
||||
const { createMissingFood, setCurrentFood, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {},
|
||||
});
|
||||
setCurrentFood("fuwud");
|
||||
await createMissingFood();
|
||||
expect(mockError).toHaveBeenCalled();
|
||||
});
|
||||
test("addMissingUnitAsAlias", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { addMissingUnitAsAlias, setCurrentUnit, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {
|
||||
unit: { name: "2uwunit", id: "unit_id_2" },
|
||||
},
|
||||
});
|
||||
setCurrentUnit("uwunit");
|
||||
await addMissingUnitAsAlias();
|
||||
expect(updateUnit).toHaveBeenCalled();
|
||||
expect(wrapped.vm.currentIng?.ingredient.unit?.name).toBe("uwunit");
|
||||
});
|
||||
test("addMissingUnitAsAlias skips if there's no alias to add", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { addMissingUnitAsAlias, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {
|
||||
unit: { name: "2uwunit", id: "unit_id_2" },
|
||||
},
|
||||
});
|
||||
await addMissingUnitAsAlias();
|
||||
expect(updateUnit).not.toHaveBeenCalled();
|
||||
});
|
||||
test("addMissingUnitAsAlias skips if already includes the alias", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { addMissingUnitAsAlias, setCurrentUnit, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {
|
||||
unit: { name: "2uwunit", id: "unit_id_2", aliases: [{ name: "uwunit" }] },
|
||||
},
|
||||
});
|
||||
setCurrentUnit("uwunit");
|
||||
await addMissingUnitAsAlias();
|
||||
expect(updateUnit).not.toHaveBeenCalled();
|
||||
});
|
||||
test("addMissingUnitAsAlias fails gracefully", async () => {
|
||||
updateUnit.mockResolvedValue(undefined);
|
||||
const wrapped = wrapper();
|
||||
const { addMissingUnitAsAlias, setCurrentUnit, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {
|
||||
unit: { name: "2uwunit", id: "unit_id_2" },
|
||||
},
|
||||
});
|
||||
setCurrentUnit("uwunit");
|
||||
await addMissingUnitAsAlias();
|
||||
expect(updateUnit).toHaveBeenCalled();
|
||||
expect(mockError).toHaveBeenCalled();
|
||||
});
|
||||
test("addMissingFoodAsAlias", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { addMissingFoodAsAlias, setCurrentFood, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {
|
||||
food: { name: "f2uwud", id: "food_id_2" },
|
||||
},
|
||||
});
|
||||
setCurrentFood("fuwud");
|
||||
await addMissingFoodAsAlias();
|
||||
expect(updateFood).toHaveBeenCalled();
|
||||
expect(wrapped.vm.currentIng?.ingredient.food?.name).toBe("fuwud");
|
||||
});
|
||||
test("addMissingFoodAsAlias skips if there's no alias to add", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { addMissingFoodAsAlias, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {
|
||||
food: { name: "f2uwud", id: "food_id_2" },
|
||||
},
|
||||
});
|
||||
await addMissingFoodAsAlias();
|
||||
expect(updateFood).not.toHaveBeenCalled();
|
||||
});
|
||||
test("addMissingFoodAsAlias skips if already includes the alias", async () => {
|
||||
const wrapped = wrapper();
|
||||
const { addMissingFoodAsAlias, setCurrentFood, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {
|
||||
food: { name: "f2uwud", id: "food_id_2", aliases: [{ name: "fuwud" }] },
|
||||
},
|
||||
});
|
||||
setCurrentFood("fuwud");
|
||||
await addMissingFoodAsAlias();
|
||||
expect(updateFood).not.toHaveBeenCalled();
|
||||
});
|
||||
test("addMissingFoodAsAlias fails gracefully", async () => {
|
||||
updateFood.mockResolvedValue(undefined);
|
||||
const wrapped = wrapper();
|
||||
const { addMissingFoodAsAlias, setCurrentFood, setCurrentIng } = wrapped.vm;
|
||||
setCurrentIng({
|
||||
ingredient: {
|
||||
food: { name: "f2uwud", id: "food_id_2" },
|
||||
},
|
||||
});
|
||||
setCurrentFood("fuwud");
|
||||
await addMissingFoodAsAlias();
|
||||
expect(updateFood).toHaveBeenCalled();
|
||||
expect(mockError).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
test("parser preferences are stored automatically", async () => {
|
||||
preferences.value.parser = "";
|
||||
const wrapped = wrapper();
|
||||
const { parser, parserPreferences, setParser, setDontShow } = wrapped.vm;
|
||||
expect(parser).toBe("nlp");
|
||||
expect(parserPreferences.parser).toBe("");
|
||||
expect(parserPreferences.dontShowInfoPage).toBe(false);
|
||||
|
||||
setParser("openai");
|
||||
setDontShow(true);
|
||||
|
||||
await wrapped.vm.$nextTick();
|
||||
|
||||
const { parserPreferences: newPrefs } = wrapped.vm;
|
||||
expect(newPrefs.parser).toBe("openai");
|
||||
expect(newPrefs.dontShowInfoPage).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,420 @@
|
||||
import { alert } from "~/composables/use-toast";
|
||||
import type { NoUndefinedField } from "~/lib/api/types/non-generated";
|
||||
import type { IngredientFood, IngredientUnit, ParsedIngredient, RecipeIngredient } from "~/lib/api/types/recipe";
|
||||
import type { Parser } from "~/lib/api/user/recipes/recipe";
|
||||
import { useUserApi } from "../api";
|
||||
import { useFoodData, useFoodStore, useUnitData, useUnitStore } from "../store";
|
||||
import { useParsingPreferences } from "../use-users/preferences";
|
||||
import { useIngredientTextParser } from "./use-recipe-ingredients";
|
||||
|
||||
export const enum ParseStep {
|
||||
LOADING,
|
||||
INFO,
|
||||
PARSE,
|
||||
REVIEW,
|
||||
}
|
||||
|
||||
export function useParseIngredientsDialog(
|
||||
ingredients: NoUndefinedField<RecipeIngredient[]>,
|
||||
onSave: (ingredients: NoUndefinedField<RecipeIngredient>[]) => void,
|
||||
) {
|
||||
const { ingredientToParserString } = useIngredientTextParser();
|
||||
|
||||
const { group } = useGroupSelf();
|
||||
const i18n = useI18n();
|
||||
const api = useUserApi();
|
||||
|
||||
const unitStore = useUnitStore();
|
||||
const unitData = useUnitData();
|
||||
const foodStore = useFoodStore();
|
||||
const foodData = useFoodData();
|
||||
|
||||
const parserPreferences = useParsingPreferences();
|
||||
const parser = ref<Parser>(parserPreferences.value.parser || "nlp");
|
||||
const dontShowInfoPage = ref(parserPreferences.value.dontShowInfoPage);
|
||||
const availableParsers = computed(() => {
|
||||
return [
|
||||
{
|
||||
text: i18n.t("recipe.parser.natural-language-processor"),
|
||||
value: "nlp",
|
||||
},
|
||||
{
|
||||
text: i18n.t("recipe.parser.brute-parser"),
|
||||
value: "brute",
|
||||
},
|
||||
{
|
||||
text: i18n.t("recipe.parser.openai-parser"),
|
||||
value: "openai",
|
||||
hide: !group.value?.aiProviderSettings?.aiEnabled,
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
/**
|
||||
* If confidence of parsing is below this threshold,
|
||||
* we will prompt the user to review the parsed ingredient.
|
||||
*/
|
||||
const confidenceThreshold = 0.85;
|
||||
const parsedIngs = ref<ParsedIngredient[]>([]);
|
||||
|
||||
const currentIng = ref<ParsedIngredient | null>(null);
|
||||
const currentMissingUnit = ref("");
|
||||
const currentMissingFood = ref("");
|
||||
const currentIngHasError = computed(() => currentMissingUnit.value || currentMissingFood.value);
|
||||
const currentIngShouldDelete = ref(false);
|
||||
|
||||
const state = reactive({
|
||||
currentParsedIndex: -1,
|
||||
allReviewed: false,
|
||||
saveLoading: false,
|
||||
step: ParseStep.LOADING,
|
||||
loadingCount: 0,
|
||||
});
|
||||
function nextStep() {
|
||||
state.step = getNextStep(state.step);
|
||||
}
|
||||
|
||||
function getNextStep(current: ParseStep) {
|
||||
switch (current) {
|
||||
case ParseStep.LOADING:
|
||||
if (!dontShowInfoPage.value) {
|
||||
console.log("showing info");
|
||||
return ParseStep.INFO;
|
||||
};
|
||||
return getNextStep(ParseStep.INFO);
|
||||
case ParseStep.INFO:
|
||||
if (!state.allReviewed) {
|
||||
return ParseStep.PARSE;
|
||||
}
|
||||
return ParseStep.REVIEW;
|
||||
case ParseStep.PARSE:
|
||||
case ParseStep.REVIEW:
|
||||
return ParseStep.REVIEW;
|
||||
}
|
||||
}
|
||||
|
||||
function shouldReview(ing: ParsedIngredient): boolean {
|
||||
console.debug(`Checking if ingredient needs review (input="${ing.input})":`, ing);
|
||||
|
||||
if (ing.ingredient.referencedRecipe) {
|
||||
console.debug("No review needed for sub-recipe ingredient");
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((ing.confidence?.average || 0) < confidenceThreshold) {
|
||||
console.debug("Needs review due to low confidence:", ing.confidence?.average);
|
||||
return true;
|
||||
}
|
||||
|
||||
const food = ing.ingredient.food;
|
||||
if (food && !food.id) {
|
||||
console.debug("Needs review due to missing food ID:", food);
|
||||
return true;
|
||||
}
|
||||
|
||||
const unit = ing.ingredient.unit;
|
||||
if (unit && !unit.id) {
|
||||
console.debug("Needs review due to missing unit ID:", unit);
|
||||
return true;
|
||||
}
|
||||
|
||||
console.debug("No review needed");
|
||||
return false;
|
||||
}
|
||||
|
||||
function checkUnit(ing: ParsedIngredient) {
|
||||
const unit = ing.ingredient.unit?.name;
|
||||
if (!unit || ing.ingredient.unit?.id) {
|
||||
currentMissingUnit.value = "";
|
||||
return;
|
||||
}
|
||||
|
||||
const potentialMatch = createdUnits.get(unit.toLowerCase());
|
||||
if (potentialMatch) {
|
||||
ing.ingredient.unit = potentialMatch;
|
||||
currentMissingUnit.value = "";
|
||||
return;
|
||||
}
|
||||
|
||||
currentMissingUnit.value = unit;
|
||||
ing.ingredient.unit = undefined;
|
||||
}
|
||||
|
||||
function checkFood(ing: ParsedIngredient) {
|
||||
const food = ing.ingredient.food?.name;
|
||||
if (!food || ing.ingredient.food?.id) {
|
||||
currentMissingFood.value = "";
|
||||
return;
|
||||
}
|
||||
|
||||
const potentialMatch = createdFoods.get(food.toLowerCase());
|
||||
if (potentialMatch) {
|
||||
ing.ingredient.food = potentialMatch;
|
||||
currentMissingFood.value = "";
|
||||
return;
|
||||
}
|
||||
|
||||
currentMissingFood.value = food;
|
||||
ing.ingredient.food = undefined;
|
||||
}
|
||||
|
||||
const ingredientsToReview = computed(() => parsedIngs.value.filter(shouldReview));
|
||||
|
||||
function nextIngredient() {
|
||||
let nextIndex = state.currentParsedIndex;
|
||||
if (currentIngShouldDelete.value) {
|
||||
parsedIngs.value.splice(state.currentParsedIndex, 1);
|
||||
currentIngShouldDelete.value = false;
|
||||
}
|
||||
else {
|
||||
nextIndex += 1;
|
||||
}
|
||||
|
||||
while (nextIndex < parsedIngs.value.length) {
|
||||
const current = parsedIngs.value[nextIndex]!;
|
||||
if (shouldReview(current)) {
|
||||
state.currentParsedIndex = nextIndex;
|
||||
currentIng.value = current;
|
||||
currentIngShouldDelete.value = false;
|
||||
checkUnit(current);
|
||||
checkFood(current);
|
||||
return;
|
||||
}
|
||||
|
||||
nextIndex += 1;
|
||||
}
|
||||
|
||||
// No more to review
|
||||
state.allReviewed = true;
|
||||
nextStep();
|
||||
}
|
||||
|
||||
/** Clear everything left over from a previous run, so re-opening the dialog starts clean */
|
||||
function resetParserState() {
|
||||
parsedIngs.value = [];
|
||||
currentIng.value = null;
|
||||
currentMissingUnit.value = "";
|
||||
currentMissingFood.value = "";
|
||||
currentIngShouldDelete.value = false;
|
||||
state.currentParsedIndex = -1;
|
||||
state.allReviewed = false;
|
||||
state.step = ParseStep.LOADING;
|
||||
state.saveLoading = false;
|
||||
createdUnits.clear();
|
||||
createdFoods.clear();
|
||||
}
|
||||
|
||||
async function parseIngredients() {
|
||||
if (state.loadingCount > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
resetParserState();
|
||||
|
||||
if (!ingredients || ingredients.length === 0) {
|
||||
nextStep();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const filteredIngredients = ingredients.filter(ing => !ing.referencedRecipe);
|
||||
const ingsAsString = filteredIngredients.map(ing => ingredientToParserString(ing));
|
||||
state.loadingCount += 1;
|
||||
const { data, error } = await api.recipes.parseIngredients(parser.value, ingsAsString);
|
||||
if (error || !data) {
|
||||
throw new Error("Failed to parse ingredients");
|
||||
}
|
||||
|
||||
// Restore section titles from original ingredients — the parser doesn't return them
|
||||
data.forEach((parsed, index) => {
|
||||
parsed.ingredient.title = filteredIngredients[index]?.title || "";
|
||||
});
|
||||
|
||||
const recipeRefs = ingredients.filter(ing => ing.referencedRecipe).map(ing => ({
|
||||
input: ing.note || "",
|
||||
confidence: {},
|
||||
ingredient: ing,
|
||||
}));
|
||||
parsedIngs.value = [...data, ...recipeRefs];
|
||||
state.currentParsedIndex = -1;
|
||||
state.allReviewed = false;
|
||||
createdUnits.clear();
|
||||
createdFoods.clear();
|
||||
currentIngShouldDelete.value = false;
|
||||
nextIngredient();
|
||||
}
|
||||
catch (error) {
|
||||
console.error("Error parsing ingredients:", error);
|
||||
alert.error(i18n.t("events.something-went-wrong"));
|
||||
}
|
||||
finally {
|
||||
state.loadingCount -= 1;
|
||||
nextStep();
|
||||
}
|
||||
}
|
||||
|
||||
/** Cache of lowercased created units to avoid duplicate creations */
|
||||
const createdUnits = new Map<string, IngredientUnit>();
|
||||
/** Cache of lowercased created foods to avoid duplicate creations */
|
||||
const createdFoods = new Map<string, IngredientFood>();
|
||||
|
||||
async function createMissingUnit() {
|
||||
if (!currentMissingUnit.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
unitData.reset();
|
||||
unitData.data.name = currentMissingUnit.value;
|
||||
|
||||
let newUnit: IngredientUnit | null;
|
||||
if (createdUnits.has(unitData.data.name)) {
|
||||
newUnit = createdUnits.get(unitData.data.name)!;
|
||||
}
|
||||
else {
|
||||
newUnit = await unitStore.actions.createOne(unitData.data);
|
||||
}
|
||||
|
||||
if (!newUnit) {
|
||||
alert.error(i18n.t("events.something-went-wrong"));
|
||||
return;
|
||||
}
|
||||
|
||||
currentIng.value!.ingredient.unit = newUnit;
|
||||
createdUnits.set(newUnit.name.toLowerCase(), newUnit);
|
||||
currentMissingUnit.value = "";
|
||||
}
|
||||
|
||||
async function createMissingFood() {
|
||||
if (!currentMissingFood.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
foodData.reset();
|
||||
foodData.data.name = currentMissingFood.value;
|
||||
|
||||
let newFood: IngredientFood | null;
|
||||
if (createdFoods.has(foodData.data.name)) {
|
||||
newFood = createdFoods.get(foodData.data.name)!;
|
||||
}
|
||||
else {
|
||||
newFood = await foodStore.actions.createOne(foodData.data);
|
||||
}
|
||||
|
||||
if (!newFood) {
|
||||
alert.error(i18n.t("events.something-went-wrong"));
|
||||
return;
|
||||
}
|
||||
|
||||
currentIng.value!.ingredient.food = newFood;
|
||||
createdFoods.set(newFood.name.toLowerCase(), newFood);
|
||||
currentMissingFood.value = "";
|
||||
}
|
||||
|
||||
async function addMissingUnitAsAlias() {
|
||||
const unit = currentIng.value?.ingredient.unit as IngredientUnit | undefined;
|
||||
if (!currentMissingUnit.value || !unit?.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
unit.aliases = unit.aliases || [];
|
||||
if (unit.aliases.map(a => a.name).includes(currentMissingUnit.value)) {
|
||||
return;
|
||||
}
|
||||
|
||||
unit.aliases.push({ name: currentMissingUnit.value });
|
||||
const updated = await unitStore.actions.updateOne(unit);
|
||||
if (!updated) {
|
||||
alert.error(i18n.t("events.something-went-wrong"));
|
||||
return;
|
||||
}
|
||||
|
||||
currentIng.value!.ingredient.unit = updated;
|
||||
currentMissingUnit.value = "";
|
||||
}
|
||||
|
||||
async function addMissingFoodAsAlias() {
|
||||
const food = currentIng.value?.ingredient.food as IngredientFood | undefined;
|
||||
if (!currentMissingFood.value || !food?.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
food.aliases = food.aliases || [];
|
||||
if (food.aliases.map(a => a.name).includes(currentMissingFood.value)) {
|
||||
return;
|
||||
}
|
||||
|
||||
food.aliases.push({ name: currentMissingFood.value });
|
||||
const updated = await foodStore.actions.updateOne(food);
|
||||
if (!updated) {
|
||||
alert.error(i18n.t("events.something-went-wrong"));
|
||||
return;
|
||||
}
|
||||
|
||||
currentIng.value!.ingredient.food = updated;
|
||||
currentMissingFood.value = "";
|
||||
}
|
||||
|
||||
watch(parser, () => {
|
||||
parserPreferences.value.parser = parser.value;
|
||||
});
|
||||
|
||||
watch(dontShowInfoPage, () => {
|
||||
parserPreferences.value.dontShowInfoPage = dontShowInfoPage.value;
|
||||
});
|
||||
|
||||
watch([parsedIngs, () => state.allReviewed], () => {
|
||||
if (!state.allReviewed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!parsedIngs.value.length) {
|
||||
insertNewIngredient(0);
|
||||
}
|
||||
}, { immediate: true, deep: true });
|
||||
|
||||
function insertNewIngredient(index: number) {
|
||||
const ing = {
|
||||
input: "",
|
||||
confidence: {},
|
||||
ingredient: {
|
||||
quantity: 0,
|
||||
referenceId: uuid4(),
|
||||
},
|
||||
} as ParsedIngredient;
|
||||
|
||||
parsedIngs.value.splice(index, 0, ing);
|
||||
}
|
||||
|
||||
function saveIngs() {
|
||||
onSave(parsedIngs.value.map(x => x.ingredient as NoUndefinedField<RecipeIngredient>));
|
||||
state.saveLoading = true;
|
||||
}
|
||||
|
||||
const ingredientsToReviewCount = computed(() => ingredientsToReview.value.length);
|
||||
const autoParsedIngredientsCount = computed(() => parsedIngs.value.length - ingredientsToReviewCount.value);
|
||||
|
||||
return {
|
||||
currentIngHasError,
|
||||
availableParsers,
|
||||
parserPreferences,
|
||||
parser,
|
||||
dontShowInfoPage,
|
||||
confidenceThreshold,
|
||||
parsedIngs,
|
||||
currentIng,
|
||||
currentMissingUnit,
|
||||
currentMissingFood,
|
||||
currentIngShouldDelete,
|
||||
state,
|
||||
ingredientsToReviewCount,
|
||||
autoParsedIngredientsCount,
|
||||
nextStep,
|
||||
saveIngs,
|
||||
nextIngredient,
|
||||
parseIngredients,
|
||||
insertNewIngredient,
|
||||
addMissingFoodAsAlias,
|
||||
addMissingUnitAsAlias,
|
||||
createMissingFood,
|
||||
createMissingUnit,
|
||||
};
|
||||
}
|
||||
@@ -46,6 +46,7 @@ export interface UserTimelinePreferences {
|
||||
|
||||
export interface UserParsingPreferences {
|
||||
parser: RegisteredParser;
|
||||
dontShowInfoPage: boolean;
|
||||
}
|
||||
|
||||
export interface UserCookbooksPreferences {
|
||||
@@ -182,6 +183,7 @@ export function useParsingPreferences(): Ref<UserParsingPreferences> {
|
||||
"parsing-preferences",
|
||||
{
|
||||
parser: "nlp" as RegisteredParser,
|
||||
dontShowInfoPage: false,
|
||||
},
|
||||
{ mergeDefaults: true },
|
||||
);
|
||||
|
||||
@@ -588,6 +588,8 @@
|
||||
"parser": {
|
||||
"ingredient-parser": "Ingredient Parser",
|
||||
"select-parser": "Select Parser",
|
||||
"dont-show-again": "Don't show this again",
|
||||
"try-again-with-parser": "Try again with {parser}",
|
||||
"natural-language-processor": "Natural Language Processor",
|
||||
"brute-parser": "Brute Parser",
|
||||
"openai-parser": "OpenAI Parser",
|
||||
@@ -597,11 +599,16 @@
|
||||
"this-food-could-not-be-parsed-automatically": "This food could not be parsed automatically",
|
||||
"review-parsed-ingredients": "Review parsed ingredients",
|
||||
"confidence-score": "Confidence Score",
|
||||
"ingredient-parser-description": "Your ingredients have been successfully parsed. Please review the ingredients we're not sure about.",
|
||||
"ingredient-parser-final-review-description": "Once all ingredients have been reviewed, you'll have one more chance to review all ingredients before applying the changes to your recipe.",
|
||||
"ingredient-parser-headline": "Ingredients Parsed",
|
||||
"ingredient-parser-title": "What's next",
|
||||
"ingredient-parser-description": "You may need to confirm results we're not sure about or create new foods or units that are required by this recipe. We'll let you know what's needed.",
|
||||
"ingredient-parser-final-review-description": "Once everything looks good, you can review the final results, then apply the changes to this recipe.",
|
||||
"add-text-as-alias-for-item": "Add \"{text}\" as alias for {item}",
|
||||
"delete-item": "Delete Item",
|
||||
"parsing-ingredients": "Parsing ingredients..."
|
||||
"parsing-ingredients": "Parsing ingredients...",
|
||||
"ingredient-parser-result-title": "For this recipe",
|
||||
"ingredient-parser-result-success": "No ingredients auto parsed | {count} ingredient auto parsed | {count} ingredients auto parsed",
|
||||
"ingredient-parser-result-failed": "No ingredients to review | {count} ingredient to review | {count} ingredients to review"
|
||||
},
|
||||
"reset-servings-count": "Reset Servings Count",
|
||||
"not-linked-ingredients": "Additional Ingredients",
|
||||
|
||||
@@ -140,6 +140,7 @@ import {
|
||||
mdiWindowClose,
|
||||
mdiWrench,
|
||||
mdiHandWaveOutline,
|
||||
mdiProgressCheck,
|
||||
|
||||
} from "@mdi/js";
|
||||
|
||||
@@ -176,6 +177,7 @@ export const icons = {
|
||||
checkboxMultipleBlankOutline: mdiCheckboxMultipleBlankOutline,
|
||||
checkboxMultipleMarkedOutline: mdiCheckboxMultipleOutline,
|
||||
checkboxMarkedCircle: mdiCheckboxMarkedCircle,
|
||||
progressCheck: mdiProgressCheck,
|
||||
chefHat: mdiChefHat,
|
||||
clipboardCheck: mdiClipboardCheck,
|
||||
clockOutline: mdiClockTimeFourOutline,
|
||||
|
||||
Reference in new issue
Block a user