' + productDetails.product.calories * mealPlanEntry.product_amount + ' kcal ' + '';
- }
-
- element.html('\
- \
-
' + productDetails.product.name + ' \
- ' + mealPlanEntry.product_amount + " " + __n(mealPlanEntry.product_amount, productDetails.quantity_unit_stock.name, productDetails.quantity_unit_stock.name_plural) + '
\
- ' + fulfillmentIconHtml + " " + fulfillmentInfoHtml + '
\
- ' + costsAndCaloriesPerServing + ' \
- \
- \
- \
- \
- \
-
\
-
');
-
- if (productDetails.product.picture_file_name && !productDetails.product.picture_file_name.isEmpty())
- {
- element.html(element.html() + '')
- }
- }
- else if (event.type == "note")
- {
- element.html('\
- \
-
' + mealPlanEntry.note + ' \
- \
- \
- \
-
\
-
');
- }
- },
- eventPositioned: function(info)
+ },
+ });
+ // render the calendar.
+ calendar.render();
+ if (setLocale)
{
- // this callback is called once a event is rendered.
- // try to limit DOM operations as much as possible
- // to the rendered element.
- var elem = $(info.el);
- RefreshLocaleNumberDisplay();
- LoadImagesLazy();
- elem.find('[data-toggle="tooltip"]').tooltip();
-
- if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK)
- {
- elem.find(".recipe-order-missing-button").addClass("d-none");
- elem.find(".recipe-consume-button").addClass("d-none");
- }
- },
-});
-// render the calendar.
-calendar.render();
-if (setLocale)
-{
- calendar.setOption("locale", __t('fullcalendar_locale'));
-}
-
-// this triggers a re-render, so we can't do that in the callback;
-// but it works here no problem.
-if (GetUriParam("week") !== undefined)
-{
- calendar.gotoDate(GetUriParam("week"));
-}
-
-$(document).on("click", ".add-recipe-button", function(e)
-{
- var day = $(this).parent().parent().data("date");
-
- $("#add-recipe-modal-title").text(__t("Add recipe on %s", day.toString()));
- $("#day").val(day.toString());
- Grocy.Components.RecipePicker.Clear();
- $("#add-recipe-modal").modal("show");
- Grocy.FrontendHelpers.ValidateForm("add-recipe-form");
- Grocy.IsMealPlanEntryEditAction = false;
-});
-
-$(document).on("click", ".add-note-button", function(e)
-{
- var day = $(this).parent().parent().parent().data("date");
-
- $("#add-note-modal-title").text(__t("Add note on %s", day.toString()));
- $("#day").val(day.toString());
- $("#note").val("");
- $("#add-note-modal").modal("show");
- Grocy.FrontendHelpers.ValidateForm("add-note-form");
- Grocy.IsMealPlanEntryEditAction = false;
-});
-
-$(document).on("click", ".add-product-button", function(e)
-{
- var day = $(this).parent().parent().parent().data("date");
-
- $("#add-product-modal-title").text(__t("Add product on %s", day.toString()));
- $("#day").val(day.toString());
- Grocy.Components.ProductPicker.Clear();
- $("#add-product-modal").modal("show");
- Grocy.FrontendHelpers.ValidateForm("add-product-form");
- Grocy.IsMealPlanEntryEditAction = false;
-});
-
-$(document).on("click", ".edit-meal-plan-entry-button", function(e)
-{
- var mealPlanEntry = JSON.parse($(this).parents(".fc-h-event:first").attr("data-meal-plan-entry"));
-
- if (mealPlanEntry.type == "recipe")
+ calendar.setOption("locale", __t('fullcalendar_locale'));
+ }
+
+ // this triggers a re-render, so we can't do that in the callback;
+ // but it works here no problem.
+ if (GetUriParam("week") !== undefined)
{
- $("#add-recipe-modal-title").text(__t("Edit recipe on %s", mealPlanEntry.day.toString()));
- $("#day").val(mealPlanEntry.day.toString());
- $("#recipe_servings").val(mealPlanEntry.recipe_servings);
- Grocy.Components.RecipePicker.SetId(mealPlanEntry.recipe_id);
+ calendar.gotoDate(GetUriParam("week"));
+ }
+
+ $(document).on("click", ".add-recipe-button", function(e)
+ {
+ var day = $(this).parent().parent().data("date");
+
+ $("#add-recipe-modal-title").text(__t("Add recipe on %s", day.toString()));
+ $("#day").val(day.toString());
+ Grocy.Components.RecipePicker.Clear();
$("#add-recipe-modal").modal("show");
Grocy.FrontendHelpers.ValidateForm("add-recipe-form");
- }
- else if (mealPlanEntry.type == "product")
+ Grocy.IsMealPlanEntryEditAction = false;
+ });
+
+ $(document).on("click", ".add-note-button", function(e)
{
- $("#add-product-modal-title").text(__t("Edit product on %s", mealPlanEntry.day.toString()));
- $("#day").val(mealPlanEntry.day.toString());
- Grocy.Components.ProductPicker.SetId(mealPlanEntry.product_id);
- $("#add-product-modal").modal("show");
- Grocy.FrontendHelpers.ValidateForm("add-product-form");
- Grocy.Components.ProductPicker.GetPicker().trigger("change");
- }
- else if (mealPlanEntry.type == "note")
- {
- $("#add-note-modal-title").text(__t("Edit note on %s", mealPlanEntry.day.toString()));
- $("#day").val(mealPlanEntry.day.toString());
- $("#note").val(mealPlanEntry.note);
+ var day = $(this).parent().parent().parent().data("date");
+
+ $("#add-note-modal-title").text(__t("Add note on %s", day.toString()));
+ $("#day").val(day.toString());
+ $("#note").val("");
$("#add-note-modal").modal("show");
Grocy.FrontendHelpers.ValidateForm("add-note-form");
- }
- Grocy.IsMealPlanEntryEditAction = true;
- Grocy.MealPlanEntryEditObjectId = mealPlanEntry.id;
-});
-
-$("#add-recipe-modal").on("shown.bs.modal", function(e)
-{
- Grocy.Components.RecipePicker.GetInputElement().focus();
-})
-
-$("#add-note-modal").on("shown.bs.modal", function(e)
-{
- $("#note").focus();
-})
-
-$("#add-product-modal").on("shown.bs.modal", function(e)
-{
- Grocy.Components.ProductPicker.GetInputElement().focus();
-})
-
-$(document).on("click", ".remove-recipe-button, .remove-note-button, .remove-product-button", function(e)
-{
- var mealPlanEntry = JSON.parse($(this).parents(".fc-h-event:first").attr("data-meal-plan-entry"));
-
- Grocy.Api.Delete('objects/meal_plan/' + mealPlanEntry.id.toString(), {},
- function(result)
- {
- window.location.reload();
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
-});
-
-$('#save-add-recipe-button').on('click', function(e)
-{
- e.preventDefault();
-
- if ($(".combobox-menu-visible").length)
- {
- return;
- }
-
- if (document.getElementById("add-recipe-form").checkValidity() === false) //There is at least one validation error
- {
- return false;
- }
-
- if (Grocy.IsMealPlanEntryEditAction)
- {
- Grocy.Api.Put('objects/meal_plan/' + Grocy.MealPlanEntryEditObjectId.toString(), $('#add-recipe-form').serializeJSON(),
- function(result)
- {
- window.location.reload();
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
- else
- {
- Grocy.Api.Post('objects/meal_plan', $('#add-recipe-form').serializeJSON(),
- function(result)
- {
- window.location.reload();
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
-});
-
-$('#save-add-note-button').on('click', function(e)
-{
- e.preventDefault();
-
- if ($(".combobox-menu-visible").length)
- {
- return;
- }
-
- if (document.getElementById("add-note-form").checkValidity() === false) //There is at least one validation error
- {
- return false;
- }
-
- var jsonData = $('#add-note-form').serializeJSON();
- jsonData.day = $("#day").val();
-
- if (Grocy.IsMealPlanEntryEditAction)
- {
- Grocy.Api.Put('objects/meal_plan/' + Grocy.MealPlanEntryEditObjectId.toString(), jsonData,
- function(result)
- {
- window.location.reload();
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
- else
- {
- Grocy.Api.Post('objects/meal_plan', jsonData,
- function(result)
- {
- window.location.reload();
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
-
-});
-
-$('#save-add-product-button').on('click', function(e)
-{
- e.preventDefault();
-
- if ($(".combobox-menu-visible").length)
- {
- return;
- }
-
- if (document.getElementById("add-product-form").checkValidity() === false) //There is at least one validation error
- {
- return false;
- }
-
- var jsonData = $('#add-product-form').serializeJSON();
- jsonData.day = $("#day").val();
- delete jsonData.display_amount;
- jsonData.product_amount = jsonData.amount;
- delete jsonData.amount;
- jsonData.product_qu_id = jsonData.qu_id;
- delete jsonData.qu_id;
-
- if (Grocy.IsMealPlanEntryEditAction)
- {
- Grocy.Api.Put('objects/meal_plan/' + Grocy.MealPlanEntryEditObjectId.toString(), jsonData,
- function(result)
- {
- window.location.reload();
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
- else
- {
- Grocy.Api.Post('objects/meal_plan', jsonData,
- function(result)
- {
- window.location.reload();
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
-});
-
-$('#add-recipe-form input').keydown(function(event)
-{
- if (event.keyCode === 13) //Enter
- {
- event.preventDefault();
-
- if (document.getElementById("add-recipe-form").checkValidity() === false) //There is at least one validation error
- {
- return false;
- }
- else
- {
- $("#save-add-recipe-button").click();
- }
- }
-});
-
-$('#add-product-form input').keydown(function(event)
-{
- if (event.keyCode === 13) //Enter
- {
- event.preventDefault();
-
- if (document.getElementById("add-product-form").checkValidity() === false) //There is at least one validation error
- {
- return false;
- }
- else
- {
- $("#save-add-product-button").click();
- }
- }
-});
-
-$(document).on("keydown", "#servings", function(event)
-{
- if (event.key === 13) //Enter
- {
- event.preventDefault();
-
- if (document.getElementById("add-recipe-form").checkValidity() === false) //There is at least one validation error
- {
- return false;
- }
- else
- {
- $("#save-add-recipe-button").click();
- }
- }
-});
-
-$(document).on('click', '.recipe-order-missing-button', function(e)
-{
- // Remove the focus from the current button
- // to prevent that the tooltip stays until clicked anywhere else
- document.activeElement.blur();
-
- var objectName = $(e.currentTarget).attr('data-recipe-name');
- var objectId = $(e.currentTarget).attr('data-recipe-id');
- var button = $(this);
- var servings = $(e.currentTarget).attr('data-mealplan-servings');
-
- bootbox.confirm({
- message: __t('Are you sure to put all missing ingredients for recipe "%s" on the shopping list?', objectName),
- closeButton: false,
- buttons: {
- confirm: {
- label: __t('Yes'),
- className: 'btn-success'
- },
- cancel: {
- label: __t('No'),
- className: 'btn-danger'
- }
- },
- callback: function(result)
- {
- if (result === true)
- {
- Grocy.FrontendHelpers.BeginUiBusy();
-
- // Set the recipes desired_servings so that the "recipes resolved"-views resolve correctly based on the meal plan entry servings
- Grocy.Api.Put('objects/recipes/' + objectId, { "desired_servings": servings },
- function(result)
- {
- Grocy.Api.Post('recipes/' + objectId + '/add-not-fulfilled-products-to-shoppinglist', {},
- function(result)
- {
- if (button.attr("data-recipe-type") == "normal")
- {
- button.addClass("disabled");
- Grocy.FrontendHelpers.EndUiBusy();
- }
- else
- {
- window.location.reload();
- }
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy();
- console.error(xhr);
- }
- );
- },
- function(xhr)
- {
- console.error(xhr);
- }
- );
- }
- }
+ Grocy.IsMealPlanEntryEditAction = false;
});
-});
-
-$(document).on('click', '.product-consume-button', function(e)
-{
- e.preventDefault();
-
- // Remove the focus from the current button
- // to prevent that the tooltip stays until clicked anywhere else
- document.activeElement.blur();
-
- Grocy.FrontendHelpers.BeginUiBusy();
-
- var productId = $(e.currentTarget).attr('data-product-id');
- var consumeAmount = parseFloat($(e.currentTarget).attr('data-product-amount'));
-
- Grocy.Api.Post('stock/products/' + productId + '/consume', { 'amount': consumeAmount, 'spoiled': false },
- function(bookingResponse)
+
+ $(document).on("click", ".add-product-button", function(e)
+ {
+ var day = $(this).parent().parent().parent().data("date");
+
+ $("#add-product-modal-title").text(__t("Add product on %s", day.toString()));
+ $("#day").val(day.toString());
+ Grocy.Components.ProductPicker.Clear();
+ $("#add-product-modal").modal("show");
+ Grocy.FrontendHelpers.ValidateForm("add-product-form");
+ Grocy.IsMealPlanEntryEditAction = false;
+ });
+
+ $(document).on("click", ".edit-meal-plan-entry-button", function(e)
+ {
+ var mealPlanEntry = JSON.parse($(this).parents(".fc-h-event:first").attr("data-meal-plan-entry"));
+
+ if (mealPlanEntry.type == "recipe")
{
- Grocy.Api.Get('stock/products/' + productId,
+ $("#add-recipe-modal-title").text(__t("Edit recipe on %s", mealPlanEntry.day.toString()));
+ $("#day").val(mealPlanEntry.day.toString());
+ $("#recipe_servings").val(mealPlanEntry.recipe_servings);
+ Grocy.Components.RecipePicker.SetId(mealPlanEntry.recipe_id);
+ $("#add-recipe-modal").modal("show");
+ Grocy.FrontendHelpers.ValidateForm("add-recipe-form");
+ }
+ else if (mealPlanEntry.type == "product")
+ {
+ $("#add-product-modal-title").text(__t("Edit product on %s", mealPlanEntry.day.toString()));
+ $("#day").val(mealPlanEntry.day.toString());
+ Grocy.Components.ProductPicker.SetId(mealPlanEntry.product_id);
+ $("#add-product-modal").modal("show");
+ Grocy.FrontendHelpers.ValidateForm("add-product-form");
+ Grocy.Components.ProductPicker.GetPicker().trigger("change");
+ }
+ else if (mealPlanEntry.type == "note")
+ {
+ $("#add-note-modal-title").text(__t("Edit note on %s", mealPlanEntry.day.toString()));
+ $("#day").val(mealPlanEntry.day.toString());
+ $("#note").val(mealPlanEntry.note);
+ $("#add-note-modal").modal("show");
+ Grocy.FrontendHelpers.ValidateForm("add-note-form");
+ }
+ Grocy.IsMealPlanEntryEditAction = true;
+ Grocy.MealPlanEntryEditObjectId = mealPlanEntry.id;
+ });
+
+ $("#add-recipe-modal").on("shown.bs.modal", function(e)
+ {
+ Grocy.Components.RecipePicker.GetInputElement().focus();
+ })
+
+ $("#add-note-modal").on("shown.bs.modal", function(e)
+ {
+ $("#note").focus();
+ })
+
+ $("#add-product-modal").on("shown.bs.modal", function(e)
+ {
+ Grocy.Components.ProductPicker.GetInputElement().focus();
+ })
+
+ $(document).on("click", ".remove-recipe-button, .remove-note-button, .remove-product-button", function(e)
+ {
+ var mealPlanEntry = JSON.parse($(this).parents(".fc-h-event:first").attr("data-meal-plan-entry"));
+
+ Grocy.Api.Delete('objects/meal_plan/' + mealPlanEntry.id.toString(), {},
+ function(result)
+ {
+ window.location.reload();
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
+ });
+
+ $('#save-add-recipe-button').on('click', function(e)
+ {
+ e.preventDefault();
+
+ if ($(".combobox-menu-visible").length)
+ {
+ return;
+ }
+
+ if (document.getElementById("add-recipe-form").checkValidity() === false) //There is at least one validation error
+ {
+ return false;
+ }
+
+ if (Grocy.IsMealPlanEntryEditAction)
+ {
+ Grocy.Api.Put('objects/meal_plan/' + Grocy.MealPlanEntryEditObjectId.toString(), $('#add-recipe-form').serializeJSON(),
function(result)
{
- var toastMessage = __t('Removed %1$s of %2$s from stock', consumeAmount.toString() + " " + __n(consumeAmount, result.quantity_unit_stock.name, result.quantity_unit_stock.name_plural), result.product.name) + '
' + __t("Undo") + '';
-
- Grocy.FrontendHelpers.EndUiBusy();
- toastr.success(toastMessage);
window.location.reload();
},
function(xhr)
{
- Grocy.FrontendHelpers.EndUiBusy();
- console.error(xhr);
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy();
- console.error(xhr);
}
- );
-});
-
-$(document).on('click', '.recipe-consume-button', function(e)
-{
- // Remove the focus from the current button
- // to prevent that the tooltip stays until clicked anywhere else
- document.activeElement.blur();
-
- var objectName = $(e.currentTarget).attr('data-recipe-name');
- var objectId = $(e.currentTarget).attr('data-recipe-id');
- var servings = $(e.currentTarget).attr('data-mealplan-servings');
-
- bootbox.confirm({
- message: __t('Are you sure to consume all ingredients needed by recipe "%s" (ingredients marked with "only check if any amount is in stock" will be ignored)?', objectName),
- closeButton: false,
- buttons: {
- confirm: {
- label: __t('Yes'),
- className: 'btn-success'
- },
- cancel: {
- label: __t('No'),
- className: 'btn-danger'
- }
- },
- callback: function(result)
+ else
{
- if (result === true)
+ Grocy.Api.Post('objects/meal_plan', $('#add-recipe-form').serializeJSON(),
+ function(result)
+ {
+ window.location.reload();
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
+ }
+ });
+
+ $('#save-add-note-button').on('click', function(e)
+ {
+ e.preventDefault();
+
+ if ($(".combobox-menu-visible").length)
+ {
+ return;
+ }
+
+ if (document.getElementById("add-note-form").checkValidity() === false) //There is at least one validation error
+ {
+ return false;
+ }
+
+ var jsonData = $('#add-note-form').serializeJSON();
+ jsonData.day = $("#day").val();
+
+ if (Grocy.IsMealPlanEntryEditAction)
+ {
+ Grocy.Api.Put('objects/meal_plan/' + Grocy.MealPlanEntryEditObjectId.toString(), jsonData,
+ function(result)
+ {
+ window.location.reload();
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
+ }
+ else
+ {
+ Grocy.Api.Post('objects/meal_plan', jsonData,
+ function(result)
+ {
+ window.location.reload();
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
+ }
+
+ });
+
+ $('#save-add-product-button').on('click', function(e)
+ {
+ e.preventDefault();
+
+ if ($(".combobox-menu-visible").length)
+ {
+ return;
+ }
+
+ if (document.getElementById("add-product-form").checkValidity() === false) //There is at least one validation error
+ {
+ return false;
+ }
+
+ var jsonData = $('#add-product-form').serializeJSON();
+ jsonData.day = $("#day").val();
+ delete jsonData.display_amount;
+ jsonData.product_amount = jsonData.amount;
+ delete jsonData.amount;
+ jsonData.product_qu_id = jsonData.qu_id;
+ delete jsonData.qu_id;
+
+ if (Grocy.IsMealPlanEntryEditAction)
+ {
+ Grocy.Api.Put('objects/meal_plan/' + Grocy.MealPlanEntryEditObjectId.toString(), jsonData,
+ function(result)
+ {
+ window.location.reload();
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
+ }
+ else
+ {
+ Grocy.Api.Post('objects/meal_plan', jsonData,
+ function(result)
+ {
+ window.location.reload();
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
+ }
+ });
+
+ $('#add-recipe-form input').keydown(function(event)
+ {
+ if (event.keyCode === 13) //Enter
+ {
+ event.preventDefault();
+
+ if (document.getElementById("add-recipe-form").checkValidity() === false) //There is at least one validation error
{
- Grocy.FrontendHelpers.BeginUiBusy();
-
- // Set the recipes desired_servings so that the "recipes resolved"-views resolve correctly based on the meal plan entry servings
- Grocy.Api.Put('objects/recipes/' + objectId, { "desired_servings": servings },
- function(result)
- {
- Grocy.Api.Post('recipes/' + objectId + '/consume', {},
- function(result)
- {
- Grocy.FrontendHelpers.EndUiBusy();
- toastr.success(__t('Removed all ingredients of recipe "%s" from stock', objectName));
- window.location.reload();
- },
- function(xhr)
- {
- toastr.warning(__t('Not all ingredients of recipe "%s" are in stock, nothing removed', objectName));
- Grocy.FrontendHelpers.EndUiBusy();
- console.error(xhr);
- }
- );
- },
- function(xhr)
- {
- console.error(xhr);
- }
- );
+ return false;
+ }
+ else
+ {
+ $("#save-add-recipe-button").click();
}
}
});
-});
-
-$(document).on("click", ".recipe-popup-button", function(e)
-{
- // Remove the focus from the current button
- // to prevent that the tooltip stays until clicked anywhere else
- document.activeElement.blur();
-
- var objectId = $(e.currentTarget).attr('data-recipe-id');
- var servings = $(e.currentTarget).attr('data-mealplan-servings');
-
- // Set the recipes desired_servings so that the "recipes resolved"-views resolve correctly based on the meal plan entry servings
- Grocy.Api.Put('objects/recipes/' + objectId, { "desired_servings": servings },
- function(result)
+
+ $('#add-product-form input').keydown(function(event)
+ {
+ if (event.keyCode === 13) //Enter
{
- bootbox.dialog({
- message: '',
- size: 'extra-large',
- backdrop: true,
- closeButton: false,
- buttons: {
- cancel: {
- label: __t('Close'),
- className: 'btn-secondary responsive-button',
- callback: function()
+ event.preventDefault();
+
+ if (document.getElementById("add-product-form").checkValidity() === false) //There is at least one validation error
+ {
+ return false;
+ }
+ else
+ {
+ $("#save-add-product-button").click();
+ }
+ }
+ });
+
+ $(document).on("keydown", "#servings", function(event)
+ {
+ if (event.key === 13) //Enter
+ {
+ event.preventDefault();
+
+ if (document.getElementById("add-recipe-form").checkValidity() === false) //There is at least one validation error
+ {
+ return false;
+ }
+ else
+ {
+ $("#save-add-recipe-button").click();
+ }
+ }
+ });
+
+ $(document).on('click', '.recipe-order-missing-button', function(e)
+ {
+ // Remove the focus from the current button
+ // to prevent that the tooltip stays until clicked anywhere else
+ document.activeElement.blur();
+
+ var objectName = $(e.currentTarget).attr('data-recipe-name');
+ var objectId = $(e.currentTarget).attr('data-recipe-id');
+ var button = $(this);
+ var servings = $(e.currentTarget).attr('data-mealplan-servings');
+
+ bootbox.confirm({
+ message: __t('Are you sure to put all missing ingredients for recipe "%s" on the shopping list?', objectName),
+ closeButton: false,
+ buttons: {
+ confirm: {
+ label: __t('Yes'),
+ className: 'btn-success'
+ },
+ cancel: {
+ label: __t('No'),
+ className: 'btn-danger'
+ }
+ },
+ callback: function(result)
+ {
+ if (result === true)
+ {
+ Grocy.FrontendHelpers.BeginUiBusy();
+
+ // Set the recipes desired_servings so that the "recipes resolved"-views resolve correctly based on the meal plan entry servings
+ Grocy.Api.Put('objects/recipes/' + objectId, { "desired_servings": servings },
+ function(result)
{
- bootbox.hideAll();
+ Grocy.Api.Post('recipes/' + objectId + '/add-not-fulfilled-products-to-shoppinglist', {},
+ function(result)
+ {
+ if (button.attr("data-recipe-type") == "normal")
+ {
+ button.addClass("disabled");
+ Grocy.FrontendHelpers.EndUiBusy();
+ }
+ else
+ {
+ window.location.reload();
+ }
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy();
+ console.error(xhr);
+ }
+ );
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ }
+ }
+ });
+ });
+
+ $(document).on('click', '.product-consume-button', function(e)
+ {
+ e.preventDefault();
+
+ // Remove the focus from the current button
+ // to prevent that the tooltip stays until clicked anywhere else
+ document.activeElement.blur();
+
+ Grocy.FrontendHelpers.BeginUiBusy();
+
+ var productId = $(e.currentTarget).attr('data-product-id');
+ var consumeAmount = parseFloat($(e.currentTarget).attr('data-product-amount'));
+
+ Grocy.Api.Post('stock/products/' + productId + '/consume', { 'amount': consumeAmount, 'spoiled': false },
+ function(bookingResponse)
+ {
+ Grocy.Api.Get('stock/products/' + productId,
+ function(result)
+ {
+ var toastMessage = __t('Removed %1$s of %2$s from stock', consumeAmount.toString() + " " + __n(consumeAmount, result.quantity_unit_stock.name, result.quantity_unit_stock.name_plural), result.product.name) + '
' + __t("Undo") + '';
+
+ Grocy.FrontendHelpers.EndUiBusy();
+ toastr.success(toastMessage);
+ window.location.reload();
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy();
+ console.error(xhr);
+ }
+ );
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy();
+ console.error(xhr);
+ }
+ );
+ });
+
+ $(document).on('click', '.recipe-consume-button', function(e)
+ {
+ // Remove the focus from the current button
+ // to prevent that the tooltip stays until clicked anywhere else
+ document.activeElement.blur();
+
+ var objectName = $(e.currentTarget).attr('data-recipe-name');
+ var objectId = $(e.currentTarget).attr('data-recipe-id');
+ var servings = $(e.currentTarget).attr('data-mealplan-servings');
+
+ bootbox.confirm({
+ message: __t('Are you sure to consume all ingredients needed by recipe "%s" (ingredients marked with "only check if any amount is in stock" will be ignored)?', objectName),
+ closeButton: false,
+ buttons: {
+ confirm: {
+ label: __t('Yes'),
+ className: 'btn-success'
+ },
+ cancel: {
+ label: __t('No'),
+ className: 'btn-danger'
+ }
+ },
+ callback: function(result)
+ {
+ if (result === true)
+ {
+ Grocy.FrontendHelpers.BeginUiBusy();
+
+ // Set the recipes desired_servings so that the "recipes resolved"-views resolve correctly based on the meal plan entry servings
+ Grocy.Api.Put('objects/recipes/' + objectId, { "desired_servings": servings },
+ function(result)
+ {
+ Grocy.Api.Post('recipes/' + objectId + '/consume', {},
+ function(result)
+ {
+ Grocy.FrontendHelpers.EndUiBusy();
+ toastr.success(__t('Removed all ingredients of recipe "%s" from stock', objectName));
+ window.location.reload();
+ },
+ function(xhr)
+ {
+ toastr.warning(__t('Not all ingredients of recipe "%s" are in stock, nothing removed', objectName));
+ Grocy.FrontendHelpers.EndUiBusy();
+ console.error(xhr);
+ }
+ );
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ }
+ }
+ });
+ });
+
+ $(document).on("click", ".recipe-popup-button", function(e)
+ {
+ // Remove the focus from the current button
+ // to prevent that the tooltip stays until clicked anywhere else
+ document.activeElement.blur();
+
+ var objectId = $(e.currentTarget).attr('data-recipe-id');
+ var servings = $(e.currentTarget).attr('data-mealplan-servings');
+
+ // Set the recipes desired_servings so that the "recipes resolved"-views resolve correctly based on the meal plan entry servings
+ Grocy.Api.Put('objects/recipes/' + objectId, { "desired_servings": servings },
+ function(result)
+ {
+ bootbox.dialog({
+ message: '',
+ size: 'extra-large',
+ backdrop: true,
+ closeButton: false,
+ buttons: {
+ cancel: {
+ label: __t('Close'),
+ className: 'btn-secondary responsive-button',
+ callback: function()
+ {
+ bootbox.hideAll();
+ }
}
}
- }
- });
- },
- function(xhr)
+ });
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ });
+
+ $(window).one("resize", function()
+ {
+ // Automatically switch the calendar to "basicDay" view on small screens
+ // and to "basicWeek" otherwise
+ if ($(window).width() < 768)
{
- console.error(xhr);
+ calendar.changeView("dayGridDay");
}
- );
-});
-
-$(window).one("resize", function()
-{
- // Automatically switch the calendar to "basicDay" view on small screens
- // and to "basicWeek" otherwise
- if ($(window).width() < 768)
+ else
+ {
+ calendar.changeView("dayGridWeek");
+ }
+ });
+
+ Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{
- calendar.changeView("dayGridDay");
- }
- else
+ var productId = $(e.target).val();
+
+ if (productId)
+ {
+ Grocy.Api.Get('stock/products/' + productId,
+ function(productDetails)
+ {
+ Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
+
+ $('#display_amount').val(1);
+ RefreshLocaleNumberInput();
+ $(".input-group-productamountpicker").trigger("change");
+ $('#display_amount').focus();
+ $('#display_amount').select();
+ $(".input-group-productamountpicker").trigger("change");
+ Grocy.FrontendHelpers.ValidateForm('add-product-form');
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ }
+ });
+
+ Grocy.Components.RecipePicker.GetPicker().on('change', function(e)
{
- calendar.changeView("dayGridWeek");
- }
-});
-
-Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
-{
- var productId = $(e.target).val();
-
- if (productId)
- {
- Grocy.Api.Get('stock/products/' + productId,
- function(productDetails)
- {
- Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
-
- $('#display_amount').val(1);
- RefreshLocaleNumberInput();
- $(".input-group-productamountpicker").trigger("change");
- $('#display_amount').focus();
- $('#display_amount').select();
- $(".input-group-productamountpicker").trigger("change");
- Grocy.FrontendHelpers.ValidateForm('add-product-form');
- },
- function(xhr)
- {
- console.error(xhr);
- }
- );
- }
-});
-
-Grocy.Components.RecipePicker.GetPicker().on('change', function(e)
-{
- var recipeId = $(e.target).val();
-
- if (recipeId)
- {
- Grocy.Api.Get('objects/recipes/' + recipeId,
- function(recipe)
- {
- $("#recipe_servings").val(recipe.base_servings);
- $("#recipe_servings").focus();
- $("#recipe_servings").select();
- },
- function(xhr)
- {
- console.error(xhr);
- }
- );
- }
-});
+ var recipeId = $(e.target).val();
+
+ if (recipeId)
+ {
+ Grocy.Api.Get('objects/recipes/' + recipeId,
+ function(recipe)
+ {
+ $("#recipe_servings").val(recipe.base_servings);
+ $("#recipe_servings").focus();
+ $("#recipe_servings").select();
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ }
+ });
+
+}
diff --git a/js/viewjs/openapiui.js b/js/viewjs/openapiui.js
index 07f68a4d..029af9f9 100644
--- a/js/viewjs/openapiui.js
+++ b/js/viewjs/openapiui.js
@@ -1,27 +1,37 @@
-/* global SwaggerUIBundle, SwaggerUIStandalonePreset */
-function HideTopbarPlugin()
+function openapiuiView(Grocy, scope = null)
{
- return {
- components: {
- Topbar: function() { return null }
+ var $scope = $;
+ if (scope != null)
+ {
+ $scope = $(scope).find;
+ }
+
+ /* global SwaggerUIBundle, SwaggerUIStandalonePreset */
+ function HideTopbarPlugin()
+ {
+ return {
+ components: {
+ Topbar: function() { return null }
+ }
}
}
+
+ const swaggerUi = SwaggerUIBundle({
+ url: Grocy.OpenApi.SpecUrl,
+ dom_id: '#swagger-ui',
+ deepLinking: true,
+ presets: [
+ SwaggerUIBundle.presets.apis,
+ SwaggerUIStandalonePreset
+ ],
+ plugins: [
+ SwaggerUIBundle.plugins.DownloadUrl,
+ HideTopbarPlugin
+ ],
+ layout: 'StandaloneLayout',
+ docExpansion: "list"
+ });
+
+ window.ui = swaggerUi;
+
}
-
-const swaggerUi = SwaggerUIBundle({
- url: Grocy.OpenApi.SpecUrl,
- dom_id: '#swagger-ui',
- deepLinking: true,
- presets: [
- SwaggerUIBundle.presets.apis,
- SwaggerUIStandalonePreset
- ],
- plugins: [
- SwaggerUIBundle.plugins.DownloadUrl,
- HideTopbarPlugin
- ],
- layout: 'StandaloneLayout',
- docExpansion: "list"
-});
-
-window.ui = swaggerUi;
diff --git a/js/viewjs/productbarcodeform.js b/js/viewjs/productbarcodeform.js
index b9bd75c0..1a60ed2d 100644
--- a/js/viewjs/productbarcodeform.js
+++ b/js/viewjs/productbarcodeform.js
@@ -1,111 +1,121 @@
-import { WindowMessageBag } from '../helpers/messagebag';
-
-Grocy.Use('barcodescanner');
-Grocy.Use("productamountpicker");
-Grocy.Use("userfieldsform");
-
-$('#save-barcode-button').on('click', function(e)
+function productbarcodeformView(Grocy, scope = null)
{
- e.preventDefault();
-
- if ($(".combobox-menu-visible").length)
+ var $scope = $;
+ if (scope != null)
{
- return;
+ $scope = $(scope).find;
}
- var jsonData = $('#barcode-form').serializeJSON();
- jsonData.amount = jsonData.display_amount;
- delete jsonData.display_amount;
-
- Grocy.FrontendHelpers.BeginUiBusy("barcode-form");
-
- if (Grocy.EditMode === 'create')
+ import { WindowMessageBag } from '../helpers/messagebag';
+
+ Grocy.Use('barcodescanner');
+ Grocy.Use("productamountpicker");
+ Grocy.Use("userfieldsform");
+
+ $('#save-barcode-button').on('click', function(e)
{
- Grocy.Api.Post('objects/product_barcodes', jsonData,
- function(result)
- {
- Grocy.EditObjectId = result.created_object_id;
- Grocy.Components.UserfieldsForm.Save()
-
- window.parent.postMessage(WindowMessageBag("ProductBarcodesChanged"), U("/product/" + GetUriParam("product")));
- window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy("barcode-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
- }
- );
- }
- else
- {
- Grocy.Components.UserfieldsForm.Save();
- Grocy.Api.Put('objects/product_barcodes/' + Grocy.EditObjectId, jsonData,
- function(result)
- {
- window.parent.postMessage(WindowMessageBag("ProductBarcodesChanged"), U("/product/" + GetUriParam("product")));
- window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy("barcode-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
- }
- );
- }
-});
-
-$('#barcode').on('keyup', function(e)
-{
- Grocy.FrontendHelpers.ValidateForm('barcode-form');
-});
-
-$('#qu_id').on('change', function(e)
-{
- Grocy.FrontendHelpers.ValidateForm('barcode-form');
-});
-
-$('#display_amount').on('keyup', function(e)
-{
- Grocy.FrontendHelpers.ValidateForm('barcode-form');
-});
-
-$('#barcode-form input').keydown(function(event)
-{
- if (event.keyCode === 13) //Enter
- {
- event.preventDefault();
-
- if (document.getElementById('barcode-form').checkValidity() === false) //There is at least one validation error
+ e.preventDefault();
+
+ if ($(".combobox-menu-visible").length)
{
- return false;
+ return;
+ }
+
+ var jsonData = $('#barcode-form').serializeJSON();
+ jsonData.amount = jsonData.display_amount;
+ delete jsonData.display_amount;
+
+ Grocy.FrontendHelpers.BeginUiBusy("barcode-form");
+
+ if (Grocy.EditMode === 'create')
+ {
+ Grocy.Api.Post('objects/product_barcodes', jsonData,
+ function(result)
+ {
+ Grocy.EditObjectId = result.created_object_id;
+ Grocy.Components.UserfieldsForm.Save()
+
+ window.parent.postMessage(WindowMessageBag("ProductBarcodesChanged"), U("/product/" + GetUriParam("product")));
+ window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy("barcode-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
+ }
+ );
}
else
{
- $('#save-barcode-button').click();
+ Grocy.Components.UserfieldsForm.Save();
+ Grocy.Api.Put('objects/product_barcodes/' + Grocy.EditObjectId, jsonData,
+ function(result)
+ {
+ window.parent.postMessage(WindowMessageBag("ProductBarcodesChanged"), U("/product/" + GetUriParam("product")));
+ window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy("barcode-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
+ }
+ );
}
- }
-});
-
-Grocy.Components.ProductAmountPicker.Reload(Grocy.EditObjectProduct.id, Grocy.EditObjectProduct.qu_id_purchase);
-if (Grocy.EditMode == "edit")
-{
- $("#display_amount").val(Grocy.EditObject.amount);
- $(".input-group-productamountpicker").trigger("change");
- Grocy.Components.ProductAmountPicker.SetQuantityUnit(Grocy.EditObject.qu_id);
-}
-
-Grocy.FrontendHelpers.ValidateForm('barcode-form');
-$('#barcode').focus();
-RefreshLocaleNumberInput();
-Grocy.Components.UserfieldsForm.Load()
-
-$(document).on("Grocy.BarcodeScanned", function(e, barcode, target)
-{
- if (target !== "#barcode")
+ });
+
+ $('#barcode').on('keyup', function(e)
{
- return;
+ Grocy.FrontendHelpers.ValidateForm('barcode-form');
+ });
+
+ $('#qu_id').on('change', function(e)
+ {
+ Grocy.FrontendHelpers.ValidateForm('barcode-form');
+ });
+
+ $('#display_amount').on('keyup', function(e)
+ {
+ Grocy.FrontendHelpers.ValidateForm('barcode-form');
+ });
+
+ $('#barcode-form input').keydown(function(event)
+ {
+ if (event.keyCode === 13) //Enter
+ {
+ event.preventDefault();
+
+ if (document.getElementById('barcode-form').checkValidity() === false) //There is at least one validation error
+ {
+ return false;
+ }
+ else
+ {
+ $('#save-barcode-button').click();
+ }
+ }
+ });
+
+ Grocy.Components.ProductAmountPicker.Reload(Grocy.EditObjectProduct.id, Grocy.EditObjectProduct.qu_id_purchase);
+ if (Grocy.EditMode == "edit")
+ {
+ $("#display_amount").val(Grocy.EditObject.amount);
+ $(".input-group-productamountpicker").trigger("change");
+ Grocy.Components.ProductAmountPicker.SetQuantityUnit(Grocy.EditObject.qu_id);
}
-
- $("#barcode").val(barcode);
-});
+
+ Grocy.FrontendHelpers.ValidateForm('barcode-form');
+ $('#barcode').focus();
+ RefreshLocaleNumberInput();
+ Grocy.Components.UserfieldsForm.Load()
+
+ $(document).on("Grocy.BarcodeScanned", function(e, barcode, target)
+ {
+ if (target !== "#barcode")
+ {
+ return;
+ }
+
+ $("#barcode").val(barcode);
+ });
+
+}
diff --git a/js/viewjs/productform.js b/js/viewjs/productform.js
index bc47bdb7..998b1d1a 100644
--- a/js/viewjs/productform.js
+++ b/js/viewjs/productform.js
@@ -1,513 +1,523 @@
-import { BoolVal } from '../helpers/extensions';
-
-Grocy.Use("numberpicker");
-Grocy.Use("shoppinglocationpicker");
-Grocy.Use("userfieldsform");
-
-function saveProductPicture(result, location, jsonData)
+function productformView(Grocy, scope = null)
{
- var productId = Grocy.EditObjectId || result.created_object_id;
-
- Grocy.Components.UserfieldsForm.Save(() =>
+ var $scope = $;
+ if (scope != null)
{
- if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteProductPictureOnSave)
- {
- Grocy.Api.UploadFile($("#product-picture")[0].files[0], 'productpictures', jsonData.picture_file_name,
- (result) =>
- {
- if (Grocy.ProductEditFormRedirectUri == "reload")
- {
- window.location.reload();
- return
- }
+ $scope = $(scope).find;
+ }
- var returnTo = GetUriParam('returnto');
- if (GetUriParam("closeAfterCreation") !== undefined)
+ import { BoolVal } from '../helpers/extensions';
+
+ Grocy.Use("numberpicker");
+ Grocy.Use("shoppinglocationpicker");
+ Grocy.Use("userfieldsform");
+
+ function saveProductPicture(result, location, jsonData)
+ {
+ var productId = Grocy.EditObjectId || result.created_object_id;
+
+ Grocy.Components.UserfieldsForm.Save(() =>
+ {
+ if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteProductPictureOnSave)
+ {
+ Grocy.Api.UploadFile($("#product-picture")[0].files[0], 'productpictures', jsonData.picture_file_name,
+ (result) =>
{
- window.close();
- }
- else if (returnTo !== undefined)
- {
- if (GetUriParam("flow") !== undefined)
+ if (Grocy.ProductEditFormRedirectUri == "reload")
{
- window.location.href = U(returnTo) + '&product-name=' + encodeURIComponent($('#name').val());
+ window.location.reload();
+ return
+ }
+
+ var returnTo = GetUriParam('returnto');
+ if (GetUriParam("closeAfterCreation") !== undefined)
+ {
+ window.close();
+ }
+ else if (returnTo !== undefined)
+ {
+ if (GetUriParam("flow") !== undefined)
+ {
+ window.location.href = U(returnTo) + '&product-name=' + encodeURIComponent($('#name').val());
+ }
+ else
+ {
+ window.location.href = U(returnTo);
+ }
+
}
else
{
- window.location.href = U(returnTo);
+ window.location.href = U(location + productId);
}
-
+
+ },
+ (xhr) =>
+ {
+ Grocy.FrontendHelpers.EndUiBusy("product-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
+ }
+ else
+ {
+ if (Grocy.ProductEditFormRedirectUri == "reload")
+ {
+ window.location.reload();
+ return
+ }
+
+ var returnTo = GetUriParam('returnto');
+ if (GetUriParam("closeAfterCreation") !== undefined)
+ {
+ window.close();
+ }
+ else if (returnTo !== undefined)
+ {
+ if (GetUriParam("flow") !== undefined)
+ {
+ window.location.href = U(returnTo) + '&product-name=' + encodeURIComponent($('#name').val());
}
else
{
- window.location.href = U(location + productId);
+ window.location.href = U(returnTo);
}
-
- },
+ }
+ else
+ {
+ window.location.href = U(location + productId);
+ }
+ }
+ });
+ }
+
+ $('.save-product-button').on('click', function(e)
+ {
+ e.preventDefault();
+
+ var jsonData = $('#product-form').serializeJSON();
+ var parentProductId = jsonData.product_id;
+ delete jsonData.product_id;
+ jsonData.parent_product_id = parentProductId;
+ Grocy.FrontendHelpers.BeginUiBusy("product-form");
+
+ if (jsonData.parent_product_id.toString().isEmpty())
+ {
+ jsonData.parent_product_id = null;
+ }
+
+ if ($("#product-picture")[0].files.length > 0)
+ {
+ var someRandomStuff = Math.random().toString(36).substring(2, 100) + Math.random().toString(36).substring(2, 100);
+ jsonData.picture_file_name = someRandomStuff + $("#product-picture")[0].files[0].name;
+ }
+
+ const location = $(e.currentTarget).attr('data-location') == 'return' ? '/products?product=' : '/product/';
+
+ if (Grocy.EditMode == 'create')
+ {
+ Grocy.Api.Post('objects/products', jsonData,
+ (result) => saveProductPicture(result, location, jsonData),
(xhr) =>
+ {
+ Grocy.FrontendHelpers.EndUiBusy("product-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ });
+ return;
+ }
+
+ if (Grocy.DeleteProductPictureOnSave)
+ {
+ jsonData.picture_file_name = null;
+
+ Grocy.Api.DeleteFile(Grocy.ProductPictureFileName, 'productpictures', {},
+ function(result)
+ {
+ // Nothing to do
+ },
+ function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("product-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
- else
- {
- if (Grocy.ProductEditFormRedirectUri == "reload")
- {
- window.location.reload();
- return
- }
-
- var returnTo = GetUriParam('returnto');
- if (GetUriParam("closeAfterCreation") !== undefined)
- {
- window.close();
- }
- else if (returnTo !== undefined)
- {
- if (GetUriParam("flow") !== undefined)
- {
- window.location.href = U(returnTo) + '&product-name=' + encodeURIComponent($('#name').val());
- }
- else
- {
- window.location.href = U(returnTo);
- }
- }
- else
- {
- window.location.href = U(location + productId);
- }
- }
- });
-}
-
-$('.save-product-button').on('click', function(e)
-{
- e.preventDefault();
-
- var jsonData = $('#product-form').serializeJSON();
- var parentProductId = jsonData.product_id;
- delete jsonData.product_id;
- jsonData.parent_product_id = parentProductId;
- Grocy.FrontendHelpers.BeginUiBusy("product-form");
-
- if (jsonData.parent_product_id.toString().isEmpty())
- {
- jsonData.parent_product_id = null;
- }
-
- if ($("#product-picture")[0].files.length > 0)
- {
- var someRandomStuff = Math.random().toString(36).substring(2, 100) + Math.random().toString(36).substring(2, 100);
- jsonData.picture_file_name = someRandomStuff + $("#product-picture")[0].files[0].name;
- }
-
- const location = $(e.currentTarget).attr('data-location') == 'return' ? '/products?product=' : '/product/';
-
- if (Grocy.EditMode == 'create')
- {
- Grocy.Api.Post('objects/products', jsonData,
+
+ Grocy.Api.Put('objects/products/' + Grocy.EditObjectId, jsonData,
(result) => saveProductPicture(result, location, jsonData),
- (xhr) =>
- {
- Grocy.FrontendHelpers.EndUiBusy("product-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- });
- return;
- }
-
- if (Grocy.DeleteProductPictureOnSave)
- {
- jsonData.picture_file_name = null;
-
- Grocy.Api.DeleteFile(Grocy.ProductPictureFileName, 'productpictures', {},
- function(result)
- {
- // Nothing to do
- },
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("product-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ console.error(xhr);
+ }
+ );
+ });
+
+ if (Grocy.EditMode == "edit")
+ {
+ Grocy.Api.Get('stock/products/' + Grocy.EditObjectId,
+ function(productDetails)
+ {
+ if (productDetails.last_purchased == null)
+ {
+ $('#qu_id_stock').removeAttr("disabled");
+ }
+ },
+ function(xhr)
+ {
+ console.error(xhr);
}
);
}
-
- Grocy.Api.Put('objects/products/' + Grocy.EditObjectId, jsonData,
- (result) => saveProductPicture(result, location, jsonData),
- function(xhr)
+
+ if (GetUriParam("flow") == "InplaceNewProductWithName")
+ {
+ $('#name').val(GetUriParam("name"));
+ $('#name').focus();
+ }
+
+ if (GetUriParam("flow") !== undefined || GetUriParam("returnto") !== undefined)
+ {
+ $("#save-hint").addClass("d-none");
+ $(".save-product-button[data-location='return']").addClass("d-none");
+ }
+
+ $('.input-group-qu').on('change', function(e)
+ {
+ var quIdPurchase = $("#qu_id_purchase").val();
+ var quIdStock = $("#qu_id_stock").val();
+ var factor = $('#qu_factor_purchase_to_stock').val();
+
+ if (factor > 1 || quIdPurchase != quIdStock)
{
- Grocy.FrontendHelpers.EndUiBusy("product-form");
- console.error(xhr);
- }
- );
-});
-
-if (Grocy.EditMode == "edit")
-{
- Grocy.Api.Get('stock/products/' + Grocy.EditObjectId,
- function(productDetails)
- {
- if (productDetails.last_purchased == null)
- {
- $('#qu_id_stock').removeAttr("disabled");
- }
- },
- function(xhr)
- {
- console.error(xhr);
- }
- );
-}
-
-if (GetUriParam("flow") == "InplaceNewProductWithName")
-{
- $('#name').val(GetUriParam("name"));
- $('#name').focus();
-}
-
-if (GetUriParam("flow") !== undefined || GetUriParam("returnto") !== undefined)
-{
- $("#save-hint").addClass("d-none");
- $(".save-product-button[data-location='return']").addClass("d-none");
-}
-
-$('.input-group-qu').on('change', function(e)
-{
- var quIdPurchase = $("#qu_id_purchase").val();
- var quIdStock = $("#qu_id_stock").val();
- var factor = $('#qu_factor_purchase_to_stock').val();
-
- if (factor > 1 || quIdPurchase != quIdStock)
- {
- $('#qu-conversion-info').text(__t('This means 1 %1$s purchased will be converted into %2$s %3$s in stock', $("#qu_id_purchase option:selected").text(), (1 * factor).toString(), __n((1 * factor).toString(), $("#qu_id_stock option:selected").text(), $("#qu_id_stock option:selected").data("plural-form"))));
- $('#qu-conversion-info').removeClass('d-none');
- }
- else
- {
- $('#qu-conversion-info').addClass('d-none');
- }
-
- $("#tare_weight_qu_info").text($("#qu_id_stock option:selected").text());
- $("#quick_consume_qu_info").text($("#qu_id_stock option:selected").text());
-
- Grocy.FrontendHelpers.ValidateForm('product-form');
-});
-
-$('#product-form input').keyup(function(event)
-{
- Grocy.FrontendHelpers.ValidateForm('product-form');
- $(".input-group-qu").trigger("change");
- $("#product-form select").trigger("select");
-
- if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error
- {
- $("#qu-conversion-add-button").addClass("disabled");
- }
- else
- {
- $("#qu-conversion-add-button").removeClass("disabled");
- }
-
- if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error
- {
- $("#barcode-add-button").addClass("disabled");
- }
-});
-
-$('#location_id').change(function(event)
-{
- Grocy.FrontendHelpers.ValidateForm('product-form');
-});
-
-$('#product-form input').keydown(function(event)
-{
- if (event.keyCode === 13) //Enter
- {
- event.preventDefault();
-
- if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error
- {
- return false;
+ $('#qu-conversion-info').text(__t('This means 1 %1$s purchased will be converted into %2$s %3$s in stock', $("#qu_id_purchase option:selected").text(), (1 * factor).toString(), __n((1 * factor).toString(), $("#qu_id_stock option:selected").text(), $("#qu_id_stock option:selected").data("plural-form"))));
+ $('#qu-conversion-info').removeClass('d-none');
}
else
{
- $('#save-product-button').click();
+ $('#qu-conversion-info').addClass('d-none');
}
- }
-});
-
-$("#enable_tare_weight_handling").on("click", function()
-{
- if (this.checked)
- {
- $("#tare_weight").removeAttr("disabled");
- }
- else
- {
- $("#tare_weight").attr("disabled", "");
- }
-
- Grocy.FrontendHelpers.ValidateForm("product-form");
-});
-
-$("#product-picture").on("change", function(e)
-{
- $("#product-picture-label").removeClass("d-none");
- $("#product-picture-label-none").addClass("d-none");
- $("#delete-current-product-picture-on-save-hint").addClass("d-none");
- $("#current-product-picture").addClass("d-none");
- Grocy.DeleteProductPictureOnSave = false;
-});
-
-Grocy.DeleteProductPictureOnSave = false;
-$("#delete-current-product-picture-button").on("click", function(e)
-{
- Grocy.DeleteProductPictureOnSave = true;
- $("#current-product-picture").addClass("d-none");
- $("#delete-current-product-picture-on-save-hint").removeClass("d-none");
- $("#product-picture-label").addClass("d-none");
- $("#product-picture-label-none").removeClass("d-none");
-});
-
-var quConversionsTable = $('#qu-conversions-table-products').DataTable({
- 'order': [[1, 'asc']],
- "orderFixed": [[4, 'asc']],
- 'columnDefs': [
- { 'orderable': false, 'targets': 0 },
- { 'searchable': false, "targets": 0 },
- { 'visible': false, 'targets': 4 }
- ].concat($.fn.dataTable.defaults.columnDefs),
- 'rowGroup': {
- enable: true,
- dataSrc: 4
- }
-});
-$('#qu-conversions-table-products tbody').removeClass("d-none");
-quConversionsTable.columns.adjust().draw();
-
-var barcodeTable = $('#barcode-table').DataTable({
- 'order': [[1, 'asc']],
- "orderFixed": [[1, 'asc']],
- 'columnDefs': [
- { 'orderable': false, 'targets': 0 },
- { 'searchable': false, "targets": 0 },
- { 'visible': false, 'targets': 5 },
- { 'visible': false, 'targets': 6 }
- ].concat($.fn.dataTable.defaults.columnDefs)
-});
-$('#barcode-table tbody').removeClass("d-none");
-barcodeTable.columns.adjust().draw();
-
-Grocy.Components.UserfieldsForm.Load();
-$("#name").trigger("keyup");
-$('#name').focus();
-$('.input-group-qu').trigger('change');
-Grocy.FrontendHelpers.ValidateForm('product-form');
-
-$(document).on('click', '.stockentry-grocycode-product-label-print', function(e)
-{
- e.preventDefault();
- document.activeElement.blur();
-
- var productId = $(e.currentTarget).attr('data-product-id');
- Grocy.Api.Get('stock/products/' + productId + '/printlabel', function(labelData)
- {
- if (Grocy.Webhooks.labelprinter !== undefined)
- {
- Grocy.FrontendHelpers.RunWebhook(Grocy.Webhooks.labelprinter, labelData);
- }
- });
-});
-
-$(document).on('click', '.qu-conversion-delete-button', function(e)
-{
- var objectId = $(e.currentTarget).attr('data-qu-conversion-id');
-
- bootbox.confirm({
- message: __t('Are you sure to remove this conversion?'),
- closeButton: false,
- buttons: {
- confirm: {
- label: __t('Yes'),
- className: 'btn-success'
- },
- cancel: {
- label: __t('No'),
- className: 'btn-danger'
- }
- },
- callback: function(result)
- {
- if (result === true)
- {
- Grocy.Api.Delete('objects/quantity_unit_conversions/' + objectId, {},
- function(result)
- {
- Grocy.ProductEditFormRedirectUri = "reload";
- $('#save-product-button').click();
- },
- function(xhr)
- {
- console.error(xhr);
- }
- );
- }
- }
- });
-});
-
-$(document).on('click', '.barcode-delete-button', function(e)
-{
- var objectId = $(e.currentTarget).attr('data-barcode-id');
-
- bootbox.confirm({
- message: __t('Are you sure to remove this barcode?'),
- closeButton: false,
- buttons: {
- confirm: {
- label: __t('Yes'),
- className: 'btn-success'
- },
- cancel: {
- label: __t('No'),
- className: 'btn-danger'
- }
- },
- callback: function(result)
- {
- if (result === true)
- {
- Grocy.Api.Delete('objects/product_barcodes/' + objectId, {},
- function(result)
- {
- Grocy.ProductEditFormRedirectUri = "reload";
- $('#save-product-button').click();
- },
- function(xhr)
- {
- console.error(xhr);
- }
- );
- }
- }
- });
-});
-
-$('#qu_id_stock').change(function(e)
-{
- // Preset QU purchase with stock QU if unset
- var quIdStock = $('#qu_id_stock');
- var quIdPurchase = $('#qu_id_purchase');
-
- if (quIdPurchase[0].selectedIndex === 0 && quIdStock[0].selectedIndex !== 0)
- {
- quIdPurchase[0].selectedIndex = quIdStock[0].selectedIndex;
+
+ $("#tare_weight_qu_info").text($("#qu_id_stock option:selected").text());
+ $("#quick_consume_qu_info").text($("#qu_id_stock option:selected").text());
+
Grocy.FrontendHelpers.ValidateForm('product-form');
- }
-});
-
-$('#allow_label_per_unit').on('change', function()
-{
- if (this.checked)
+ });
+
+ $('#product-form input').keyup(function(event)
{
- $('#label-option-per-unit').prop("disabled", false);
- }
- else
- {
- if ($('#default_print_stock_label').val() == "2")
+ Grocy.FrontendHelpers.ValidateForm('product-form');
+ $(".input-group-qu").trigger("change");
+ $("#product-form select").trigger("select");
+
+ if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error
{
- $("#default_print_stock_label").val("0");
+ $("#qu-conversion-add-button").addClass("disabled");
}
- $('#label-option-per-unit').prop("disabled", true);
- }
-});
-
-$(window).on("message", function(e)
-{
- var data = e.originalEvent.data;
-
- if (data.Message === "ProductBarcodesChanged" || data.Message === "ProductQUConversionChanged")
- {
- window.location.reload();
- }
-});
-
-if (Grocy.EditMode == "create" && GetUriParam("copy-of") != undefined)
-{
- Grocy.Api.Get('objects/products/' + GetUriParam("copy-of"),
- function(sourceProduct)
+ else
{
- if (sourceProduct.parent_product_id != null)
+ $("#qu-conversion-add-button").removeClass("disabled");
+ }
+
+ if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error
+ {
+ $("#barcode-add-button").addClass("disabled");
+ }
+ });
+
+ $('#location_id').change(function(event)
+ {
+ Grocy.FrontendHelpers.ValidateForm('product-form');
+ });
+
+ $('#product-form input').keydown(function(event)
+ {
+ if (event.keyCode === 13) //Enter
+ {
+ event.preventDefault();
+
+ if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error
{
- Grocy.Components.ProductPicker.SetId(sourceProduct.parent_product_id);
+ return false;
}
- if (sourceProduct.description != null)
+ else
{
- $("#description").summernote("pasteHTML", sourceProduct.description);
+ $('#save-product-button').click();
}
- $("#location_id").val(sourceProduct.location_id);
- if (sourceProduct.shopping_location_id != null)
+ }
+ });
+
+ $("#enable_tare_weight_handling").on("click", function()
+ {
+ if (this.checked)
+ {
+ $("#tare_weight").removeAttr("disabled");
+ }
+ else
+ {
+ $("#tare_weight").attr("disabled", "");
+ }
+
+ Grocy.FrontendHelpers.ValidateForm("product-form");
+ });
+
+ $("#product-picture").on("change", function(e)
+ {
+ $("#product-picture-label").removeClass("d-none");
+ $("#product-picture-label-none").addClass("d-none");
+ $("#delete-current-product-picture-on-save-hint").addClass("d-none");
+ $("#current-product-picture").addClass("d-none");
+ Grocy.DeleteProductPictureOnSave = false;
+ });
+
+ Grocy.DeleteProductPictureOnSave = false;
+ $("#delete-current-product-picture-button").on("click", function(e)
+ {
+ Grocy.DeleteProductPictureOnSave = true;
+ $("#current-product-picture").addClass("d-none");
+ $("#delete-current-product-picture-on-save-hint").removeClass("d-none");
+ $("#product-picture-label").addClass("d-none");
+ $("#product-picture-label-none").removeClass("d-none");
+ });
+
+ var quConversionsTable = $('#qu-conversions-table-products').DataTable({
+ 'order': [[1, 'asc']],
+ "orderFixed": [[4, 'asc']],
+ 'columnDefs': [
+ { 'orderable': false, 'targets': 0 },
+ { 'searchable': false, "targets": 0 },
+ { 'visible': false, 'targets': 4 }
+ ].concat($.fn.dataTable.defaults.columnDefs),
+ 'rowGroup': {
+ enable: true,
+ dataSrc: 4
+ }
+ });
+ $('#qu-conversions-table-products tbody').removeClass("d-none");
+ quConversionsTable.columns.adjust().draw();
+
+ var barcodeTable = $('#barcode-table').DataTable({
+ 'order': [[1, 'asc']],
+ "orderFixed": [[1, 'asc']],
+ 'columnDefs': [
+ { 'orderable': false, 'targets': 0 },
+ { 'searchable': false, "targets": 0 },
+ { 'visible': false, 'targets': 5 },
+ { 'visible': false, 'targets': 6 }
+ ].concat($.fn.dataTable.defaults.columnDefs)
+ });
+ $('#barcode-table tbody').removeClass("d-none");
+ barcodeTable.columns.adjust().draw();
+
+ Grocy.Components.UserfieldsForm.Load();
+ $("#name").trigger("keyup");
+ $('#name').focus();
+ $('.input-group-qu').trigger('change');
+ Grocy.FrontendHelpers.ValidateForm('product-form');
+
+ $(document).on('click', '.stockentry-grocycode-product-label-print', function(e)
+ {
+ e.preventDefault();
+ document.activeElement.blur();
+
+ var productId = $(e.currentTarget).attr('data-product-id');
+ Grocy.Api.Get('stock/products/' + productId + '/printlabel', function(labelData)
+ {
+ if (Grocy.Webhooks.labelprinter !== undefined)
{
- Grocy.Components.ShoppingLocationPicker.SetId(sourceProduct.shopping_location_id);
+ Grocy.FrontendHelpers.RunWebhook(Grocy.Webhooks.labelprinter, labelData);
}
- $("#min_stock_amount").val(sourceProduct.min_stock_amount);
- if (BoolVal(sourceProduct.cumulate_min_stock_amount_of_sub_products))
+ });
+ });
+
+ $(document).on('click', '.qu-conversion-delete-button', function(e)
+ {
+ var objectId = $(e.currentTarget).attr('data-qu-conversion-id');
+
+ bootbox.confirm({
+ message: __t('Are you sure to remove this conversion?'),
+ closeButton: false,
+ buttons: {
+ confirm: {
+ label: __t('Yes'),
+ className: 'btn-success'
+ },
+ cancel: {
+ label: __t('No'),
+ className: 'btn-danger'
+ }
+ },
+ callback: function(result)
{
- $("#cumulate_min_stock_amount_of_sub_products").prop("checked", true);
+ if (result === true)
+ {
+ Grocy.Api.Delete('objects/quantity_unit_conversions/' + objectId, {},
+ function(result)
+ {
+ Grocy.ProductEditFormRedirectUri = "reload";
+ $('#save-product-button').click();
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ }
}
- $("#default_best_before_days").val(sourceProduct.default_best_before_days);
- $("#default_best_before_days_after_open").val(sourceProduct.default_best_before_days_after_open);
- if (sourceProduct.product_group_id != null)
+ });
+ });
+
+ $(document).on('click', '.barcode-delete-button', function(e)
+ {
+ var objectId = $(e.currentTarget).attr('data-barcode-id');
+
+ bootbox.confirm({
+ message: __t('Are you sure to remove this barcode?'),
+ closeButton: false,
+ buttons: {
+ confirm: {
+ label: __t('Yes'),
+ className: 'btn-success'
+ },
+ cancel: {
+ label: __t('No'),
+ className: 'btn-danger'
+ }
+ },
+ callback: function(result)
{
- $("#product_group_id").val(sourceProduct.product_group_id);
+ if (result === true)
+ {
+ Grocy.Api.Delete('objects/product_barcodes/' + objectId, {},
+ function(result)
+ {
+ Grocy.ProductEditFormRedirectUri = "reload";
+ $('#save-product-button').click();
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ }
}
- $("#qu_id_stock").val(sourceProduct.qu_id_stock);
- $("#qu_id_purchase").val(sourceProduct.qu_id_purchase);
- $("#qu_factor_purchase_to_stock").val(sourceProduct.qu_factor_purchase_to_stock);
- if (BoolVal(sourceProduct.enable_tare_weight_handling))
- {
- $("#enable_tare_weight_handling").prop("checked", true);
- }
- $("#tare_weight").val(sourceProduct.tare_weight);
- if (BoolVal(sourceProduct.not_check_stock_fulfillment_for_recipes))
- {
- $("#not_check_stock_fulfillment_for_recipes").prop("checked", true);
- }
- if (sourceProduct.calories != null)
- {
- $("#calories").val(sourceProduct.calories);
- }
- $("#default_best_before_days_after_freezing").val(sourceProduct.default_best_before_days_after_freezing);
- $("#default_best_before_days_after_thawing").val(sourceProduct.default_best_before_days_after_thawing);
- $("#quick_consume_amount").val(sourceProduct.quick_consume_amount);
-
+ });
+ });
+
+ $('#qu_id_stock').change(function(e)
+ {
+ // Preset QU purchase with stock QU if unset
+ var quIdStock = $('#qu_id_stock');
+ var quIdPurchase = $('#qu_id_purchase');
+
+ if (quIdPurchase[0].selectedIndex === 0 && quIdStock[0].selectedIndex !== 0)
+ {
+ quIdPurchase[0].selectedIndex = quIdStock[0].selectedIndex;
Grocy.FrontendHelpers.ValidateForm('product-form');
- },
- function(xhr)
- {
- console.error(xhr);
}
- );
+ });
+
+ $('#allow_label_per_unit').on('change', function()
+ {
+ if (this.checked)
+ {
+ $('#label-option-per-unit').prop("disabled", false);
+ }
+ else
+ {
+ if ($('#default_print_stock_label').val() == "2")
+ {
+ $("#default_print_stock_label").val("0");
+ }
+ $('#label-option-per-unit').prop("disabled", true);
+ }
+ });
+
+ $(window).on("message", function(e)
+ {
+ var data = e.originalEvent.data;
+
+ if (data.Message === "ProductBarcodesChanged" || data.Message === "ProductQUConversionChanged")
+ {
+ window.location.reload();
+ }
+ });
+
+ if (Grocy.EditMode == "create" && GetUriParam("copy-of") != undefined)
+ {
+ Grocy.Api.Get('objects/products/' + GetUriParam("copy-of"),
+ function(sourceProduct)
+ {
+ if (sourceProduct.parent_product_id != null)
+ {
+ Grocy.Components.ProductPicker.SetId(sourceProduct.parent_product_id);
+ }
+ if (sourceProduct.description != null)
+ {
+ $("#description").summernote("pasteHTML", sourceProduct.description);
+ }
+ $("#location_id").val(sourceProduct.location_id);
+ if (sourceProduct.shopping_location_id != null)
+ {
+ Grocy.Components.ShoppingLocationPicker.SetId(sourceProduct.shopping_location_id);
+ }
+ $("#min_stock_amount").val(sourceProduct.min_stock_amount);
+ if (BoolVal(sourceProduct.cumulate_min_stock_amount_of_sub_products))
+ {
+ $("#cumulate_min_stock_amount_of_sub_products").prop("checked", true);
+ }
+ $("#default_best_before_days").val(sourceProduct.default_best_before_days);
+ $("#default_best_before_days_after_open").val(sourceProduct.default_best_before_days_after_open);
+ if (sourceProduct.product_group_id != null)
+ {
+ $("#product_group_id").val(sourceProduct.product_group_id);
+ }
+ $("#qu_id_stock").val(sourceProduct.qu_id_stock);
+ $("#qu_id_purchase").val(sourceProduct.qu_id_purchase);
+ $("#qu_factor_purchase_to_stock").val(sourceProduct.qu_factor_purchase_to_stock);
+ if (BoolVal(sourceProduct.enable_tare_weight_handling))
+ {
+ $("#enable_tare_weight_handling").prop("checked", true);
+ }
+ $("#tare_weight").val(sourceProduct.tare_weight);
+ if (BoolVal(sourceProduct.not_check_stock_fulfillment_for_recipes))
+ {
+ $("#not_check_stock_fulfillment_for_recipes").prop("checked", true);
+ }
+ if (sourceProduct.calories != null)
+ {
+ $("#calories").val(sourceProduct.calories);
+ }
+ $("#default_best_before_days_after_freezing").val(sourceProduct.default_best_before_days_after_freezing);
+ $("#default_best_before_days_after_thawing").val(sourceProduct.default_best_before_days_after_thawing);
+ $("#quick_consume_amount").val(sourceProduct.quick_consume_amount);
+
+ Grocy.FrontendHelpers.ValidateForm('product-form');
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ }
+ else if (Grocy.EditMode === 'create')
+ {
+ if (Grocy.UserSettings.product_presets_location_id.toString() !== '-1')
+ {
+ $("#location_id").val(Grocy.UserSettings.product_presets_location_id);
+ }
+
+ if (Grocy.UserSettings.product_presets_product_group_id.toString() !== '-1')
+ {
+ $("#product_group_id").val(Grocy.UserSettings.product_presets_product_group_id);
+ }
+
+ if (Grocy.UserSettings.product_presets_qu_id.toString() !== '-1')
+ {
+ $("select.input-group-qu").val(Grocy.UserSettings.product_presets_qu_id);
+ }
+ }
+
+ Grocy.FrontendHelpers.ValidateForm("product-form");
+
}
-else if (Grocy.EditMode === 'create')
-{
- if (Grocy.UserSettings.product_presets_location_id.toString() !== '-1')
- {
- $("#location_id").val(Grocy.UserSettings.product_presets_location_id);
- }
-
- if (Grocy.UserSettings.product_presets_product_group_id.toString() !== '-1')
- {
- $("#product_group_id").val(Grocy.UserSettings.product_presets_product_group_id);
- }
-
- if (Grocy.UserSettings.product_presets_qu_id.toString() !== '-1')
- {
- $("select.input-group-qu").val(Grocy.UserSettings.product_presets_qu_id);
- }
-}
-
-Grocy.FrontendHelpers.ValidateForm("product-form");
diff --git a/js/viewjs/productgroupform.js b/js/viewjs/productgroupform.js
index 8496e6c2..eda94970 100644
--- a/js/viewjs/productgroupform.js
+++ b/js/viewjs/productgroupform.js
@@ -1,78 +1,88 @@
-import { WindowMessageBag } from '../helpers/messagebag';
-
-Grocy.Use("userfieldsform");
-
-$('#save-product-group-button').on('click', function(e)
+function productgroupformView(Grocy, scope = null)
{
- e.preventDefault();
-
- if ($(".combobox-menu-visible").length)
+ var $scope = $;
+ if (scope != null)
{
- return;
+ $scope = $(scope).find;
}
- var jsonData = $('#product-group-form').serializeJSON();
- Grocy.FrontendHelpers.BeginUiBusy("product-group-form");
-
- if (Grocy.EditMode === 'create')
+ import { WindowMessageBag } from '../helpers/messagebag';
+
+ Grocy.Use("userfieldsform");
+
+ $('#save-product-group-button').on('click', function(e)
{
- Grocy.Api.Post('objects/product_groups', jsonData,
- function(result)
- {
- Grocy.EditObjectId = result.created_object_id;
- Grocy.Components.UserfieldsForm.Save(function()
- {
- window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/productgroups"));
- });
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy("product-group-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
- else
- {
- Grocy.Api.Put('objects/product_groups/' + Grocy.EditObjectId, jsonData,
- function(result)
- {
- Grocy.Components.UserfieldsForm.Save(function()
- {
- window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/productgroups"));
- });
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy("product-group-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
-});
-
-$('#product-group-form input').keyup(function(event)
-{
- Grocy.FrontendHelpers.ValidateForm('product-group-form');
-});
-
-$('#product-group-form input').keydown(function(event)
-{
- if (event.keyCode === 13) //Enter
- {
- event.preventDefault();
-
- if (document.getElementById('product-group-form').checkValidity() === false) //There is at least one validation error
+ e.preventDefault();
+
+ if ($(".combobox-menu-visible").length)
{
- return false;
+ return;
+ }
+
+ var jsonData = $('#product-group-form').serializeJSON();
+ Grocy.FrontendHelpers.BeginUiBusy("product-group-form");
+
+ if (Grocy.EditMode === 'create')
+ {
+ Grocy.Api.Post('objects/product_groups', jsonData,
+ function(result)
+ {
+ Grocy.EditObjectId = result.created_object_id;
+ Grocy.Components.UserfieldsForm.Save(function()
+ {
+ window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/productgroups"));
+ });
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy("product-group-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
}
else
{
- $('#save-product-group-button').click();
+ Grocy.Api.Put('objects/product_groups/' + Grocy.EditObjectId, jsonData,
+ function(result)
+ {
+ Grocy.Components.UserfieldsForm.Save(function()
+ {
+ window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/productgroups"));
+ });
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy("product-group-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
}
- }
-});
-
-Grocy.Components.UserfieldsForm.Load();
-$('#name').focus();
-Grocy.FrontendHelpers.ValidateForm('product-group-form');
+ });
+
+ $('#product-group-form input').keyup(function(event)
+ {
+ Grocy.FrontendHelpers.ValidateForm('product-group-form');
+ });
+
+ $('#product-group-form input').keydown(function(event)
+ {
+ if (event.keyCode === 13) //Enter
+ {
+ event.preventDefault();
+
+ if (document.getElementById('product-group-form').checkValidity() === false) //There is at least one validation error
+ {
+ return false;
+ }
+ else
+ {
+ $('#save-product-group-button').click();
+ }
+ }
+ });
+
+ Grocy.Components.UserfieldsForm.Load();
+ $('#name').focus();
+ Grocy.FrontendHelpers.ValidateForm('product-group-form');
+
+}
diff --git a/js/viewjs/productgroups.js b/js/viewjs/productgroups.js
index cf4a3975..e33dbde2 100644
--- a/js/viewjs/productgroups.js
+++ b/js/viewjs/productgroups.js
@@ -1,27 +1,37 @@
-var groupsTable = $('#productgroups-table').DataTable({
- 'order': [[1, 'asc']],
- 'columnDefs': [
- { 'orderable': false, 'targets': 0 },
- { 'searchable': false, "targets": 0 }
- ].concat($.fn.dataTable.defaults.columnDefs)
-});
-$('#productgroups-table tbody').removeClass("d-none");
-Grocy.FrontendHelpers.InitDataTable(groupsTable);
-Grocy.FrontendHelpers.MakeDeleteConfirmBox(
- 'Are you sure to delete product group "%s"?',
- '.product-group-delete-button',
- 'data-group-name',
- 'data-group-id',
- 'objects/product_groups/',
- '/productgroups'
-);
-
-$(window).on("message", function(e)
+function productgroupsView(Grocy, scope = null)
{
- var data = e.originalEvent.data;
-
- if (data.Message === "CloseAllModals")
+ var $scope = $;
+ if (scope != null)
{
- window.location.reload();
+ $scope = $(scope).find;
}
-});
+
+ var groupsTable = $('#productgroups-table').DataTable({
+ 'order': [[1, 'asc']],
+ 'columnDefs': [
+ { 'orderable': false, 'targets': 0 },
+ { 'searchable': false, "targets": 0 }
+ ].concat($.fn.dataTable.defaults.columnDefs)
+ });
+ $('#productgroups-table tbody').removeClass("d-none");
+ Grocy.FrontendHelpers.InitDataTable(groupsTable);
+ Grocy.FrontendHelpers.MakeDeleteConfirmBox(
+ 'Are you sure to delete product group "%s"?',
+ '.product-group-delete-button',
+ 'data-group-name',
+ 'data-group-id',
+ 'objects/product_groups/',
+ '/productgroups'
+ );
+
+ $(window).on("message", function(e)
+ {
+ var data = e.originalEvent.data;
+
+ if (data.Message === "CloseAllModals")
+ {
+ window.location.reload();
+ }
+ });
+
+}
diff --git a/js/viewjs/products.js b/js/viewjs/products.js
index 2fe575af..eb9e4252 100644
--- a/js/viewjs/products.js
+++ b/js/viewjs/products.js
@@ -1,81 +1,91 @@
-var productsTable = $('#products-table').DataTable({
- 'order': [[1, 'asc']],
- 'columnDefs': [
- { 'orderable': false, 'targets': 0 },
- { 'searchable': false, "targets": 0 },
- { 'visible': false, 'targets': 7 },
- { "type": "html-num-fmt", "targets": 3 }
- ].concat($.fn.dataTable.defaults.columnDefs)
-});
-$('#products-table tbody').removeClass("d-none");
-
-Grocy.FrontendHelpers.InitDataTable(productsTable, null, function()
+function productsView(Grocy, scope = null)
{
- $("#search").val("");
- productsTable.search("").draw();
- $("#show-disabled").prop('checked', false);
-})
-
-Grocy.FrontendHelpers.MakeFilterForColumn("#product-group-filter", 6, productsTable);
-if (typeof GetUriParam("product-group") !== "undefined")
-{
- $("#product-group-filter").val(GetUriParam("product-group"));
- $("#product-group-filter").trigger("change");
-}
-
-Grocy.FrontendHelpers.MakeDeleteConfirmBox(
- (objectId, objectName) =>
+ var $scope = $;
+ if (scope != null)
{
- return __t('Are you sure to delete product "%s"?', objectName) +
- '
' +
- __t('This also removes any stock amount, the journal and all other references of this product - consider disabling it instead, if you want to keep that and just hide the product.');
- },
- '.product-delete-button',
- 'data-product-name',
- 'data-product-id',
- 'objects/products/',
- '/products'
-);
-
-$("#show-disabled").change(function()
-{
- if (this.checked)
- {
- window.location.href = U('/products?include_disabled');
+ $scope = $(scope).find;
}
- else
+
+ var productsTable = $('#products-table').DataTable({
+ 'order': [[1, 'asc']],
+ 'columnDefs': [
+ { 'orderable': false, 'targets': 0 },
+ { 'searchable': false, "targets": 0 },
+ { 'visible': false, 'targets': 7 },
+ { "type": "html-num-fmt", "targets": 3 }
+ ].concat($.fn.dataTable.defaults.columnDefs)
+ });
+ $('#products-table tbody').removeClass("d-none");
+
+ Grocy.FrontendHelpers.InitDataTable(productsTable, null, function()
{
- window.location.href = U('/products');
+ $("#search").val("");
+ productsTable.search("").draw();
+ $("#show-disabled").prop('checked', false);
+ })
+
+ Grocy.FrontendHelpers.MakeFilterForColumn("#product-group-filter", 6, productsTable);
+ if (typeof GetUriParam("product-group") !== "undefined")
+ {
+ $("#product-group-filter").val(GetUriParam("product-group"));
+ $("#product-group-filter").trigger("change");
}
-});
-
-if (GetUriParam('include_disabled'))
-{
- $("#show-disabled").prop('checked', true);
-}
-
-
-$(".merge-products-button").on("click", function(e)
-{
- var productId = $(e.currentTarget).attr("data-product-id");
- $("#merge-products-keep").val(productId);
- $("#merge-products-remove").val("");
- $("#merge-products-modal").modal("show");
-});
-
-$("#merge-products-save-button").on("click", function()
-{
- var productIdToKeep = $("#merge-products-keep").val();
- var productIdToRemove = $("#merge-products-remove").val();
-
- Grocy.Api.Post("stock/products/" + productIdToKeep.toString() + "/merge/" + productIdToRemove.toString(), {},
- function(result)
+
+ Grocy.FrontendHelpers.MakeDeleteConfirmBox(
+ (objectId, objectName) =>
+ {
+ return __t('Are you sure to delete product "%s"?', objectName) +
+ '
' +
+ __t('This also removes any stock amount, the journal and all other references of this product - consider disabling it instead, if you want to keep that and just hide the product.');
+ },
+ '.product-delete-button',
+ 'data-product-name',
+ 'data-product-id',
+ 'objects/products/',
+ '/products'
+ );
+
+ $("#show-disabled").change(function()
+ {
+ if (this.checked)
+ {
+ window.location.href = U('/products?include_disabled');
+ }
+ else
{
window.location.href = U('/products');
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.ShowGenericError('Error while merging products', xhr.response);
}
- );
-});
+ });
+
+ if (GetUriParam('include_disabled'))
+ {
+ $("#show-disabled").prop('checked', true);
+ }
+
+
+ $(".merge-products-button").on("click", function(e)
+ {
+ var productId = $(e.currentTarget).attr("data-product-id");
+ $("#merge-products-keep").val(productId);
+ $("#merge-products-remove").val("");
+ $("#merge-products-modal").modal("show");
+ });
+
+ $("#merge-products-save-button").on("click", function()
+ {
+ var productIdToKeep = $("#merge-products-keep").val();
+ var productIdToRemove = $("#merge-products-remove").val();
+
+ Grocy.Api.Post("stock/products/" + productIdToKeep.toString() + "/merge/" + productIdToRemove.toString(), {},
+ function(result)
+ {
+ window.location.href = U('/products');
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.ShowGenericError('Error while merging products', xhr.response);
+ }
+ );
+ });
+
+}
diff --git a/js/viewjs/purchase.js b/js/viewjs/purchase.js
index f7c3427c..8aceb129 100644
--- a/js/viewjs/purchase.js
+++ b/js/viewjs/purchase.js
@@ -1,582 +1,592 @@
-import { BoolVal } from '../helpers/extensions';
-import { WindowMessageBag } from '../helpers/messagebag';
-
-Grocy.Use("datetimepicker");
-if (Grocy.UserSettings.show_purchased_date_on_purchase)
+function purchaseView(Grocy, scope = null)
{
- Grocy.Use("datetimepicker2");
-}
-Grocy.Use("locationpicker");
-Grocy.Use("numberpicker");
-Grocy.Use("productamountpicker");
-Grocy.Use("productcard");
-Grocy.Use("shoppinglocationpicker");
-
-var CurrentProductDetails;
-
-$('#save-purchase-button').on('click', function(e)
-{
- e.preventDefault();
-
- if ($(".combobox-menu-visible").length)
+ var $scope = $;
+ if (scope != null)
{
- return;
+ $scope = $(scope).find;
}
- if ($(".combobox-menu-visible").length)
+ import { BoolVal } from '../helpers/extensions';
+ import { WindowMessageBag } from '../helpers/messagebag';
+
+ Grocy.Use("datetimepicker");
+ if (Grocy.UserSettings.show_purchased_date_on_purchase)
{
- return;
+ Grocy.Use("datetimepicker2");
}
-
- var jsonForm = $('#purchase-form').serializeJSON();
-
- Grocy.FrontendHelpers.BeginUiBusy("purchase-form");
-
- Grocy.Api.Get('stock/products/' + jsonForm.product_id,
- function(productDetails)
+ Grocy.Use("locationpicker");
+ Grocy.Use("numberpicker");
+ Grocy.Use("productamountpicker");
+ Grocy.Use("productcard");
+ Grocy.Use("shoppinglocationpicker");
+
+ var CurrentProductDetails;
+
+ $('#save-purchase-button').on('click', function(e)
+ {
+ e.preventDefault();
+
+ if ($(".combobox-menu-visible").length)
{
- var jsonData = {};
- jsonData.amount = jsonForm.amount;
- jsonData.print_stock_label = jsonForm.print_stock_label
-
- if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
+ return;
+ }
+
+ if ($(".combobox-menu-visible").length)
+ {
+ return;
+ }
+
+ var jsonForm = $('#purchase-form').serializeJSON();
+
+ Grocy.FrontendHelpers.BeginUiBusy("purchase-form");
+
+ Grocy.Api.Get('stock/products/' + jsonForm.product_id,
+ function(productDetails)
{
- jsonData.price = 0;
- }
- else
- {
- var amount = jsonForm.display_amount;
- if (BoolVal(productDetails.product.enable_tare_weight_handling))
+ var jsonData = {};
+ jsonData.amount = jsonForm.amount;
+ jsonData.print_stock_label = jsonForm.print_stock_label
+
+ if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{
- amount -= parseFloat(productDetails.product.tare_weight);
+ jsonData.price = 0;
}
-
- var price = parseFloat(jsonForm.price * $("#qu_id option:selected").attr("data-qu-factor")).toFixed(Grocy.UserSettings.stock_decimal_places_prices);
- if ($("input[name='price-type']:checked").val() == "total-price")
+ else
{
- price = parseFloat(price / amount).toFixed(Grocy.UserSettings.stock_decimal_places_prices);
- }
-
- jsonData.price = price;
- }
-
- if (BoolVal(Grocy.UserSettings.show_purchased_date_on_purchase))
- {
- jsonData.purchased_date = Grocy.Components.DateTimePicker2.GetValue();
- }
-
- if (Grocy.Components.DateTimePicker)
- {
- jsonData.best_before_date = Grocy.Components.DateTimePicker.GetValue();
- }
- else
- {
- jsonData.best_before_date = null;
- }
-
- if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
- {
- jsonData.shopping_location_id = Grocy.Components.ShoppingLocationPicker.GetValue();
- }
- if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
- {
- jsonData.location_id = Grocy.Components.LocationPicker.GetValue();
- }
-
- Grocy.Api.Post('stock/products/' + jsonForm.product_id + '/add', jsonData,
- function(result)
- {
- if ($("#purchase-form").hasAttr("data-used-barcode"))
- {
- Grocy.Api.Put('objects/product_barcodes/' + $("#purchase-form").attr("data-used-barcode"), { last_price: $("#price").val() },
- function(result)
- { },
- function(xhr)
- { }
- );
- }
-
- if (BoolVal(Grocy.UserSettings.scan_mode_purchase_enabled))
- {
- Grocy.UISound.Success();
- }
-
- if (GetUriParam("flow") == "InplaceAddBarcodeToExistingProduct")
- {
- var jsonDataBarcode = {};
- jsonDataBarcode.barcode = GetUriParam("barcode");
- jsonDataBarcode.product_id = jsonForm.product_id;
- jsonDataBarcode.shopping_location_id = jsonForm.shopping_location_id;
-
- Grocy.Api.Post('objects/product_barcodes', jsonDataBarcode,
- function(result)
- {
- $("#flow-info-InplaceAddBarcodeToExistingProduct").addClass("d-none");
- $('#barcode-lookup-disabled-hint').addClass('d-none');
- $('#barcode-lookup-hint').removeClass('d-none');
- window.history.replaceState({}, document.title, U("/purchase"));
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy("purchase-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
- }
- );
- }
-
- var amountMessage = parseFloat(jsonForm.amount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts });
+ var amount = jsonForm.display_amount;
if (BoolVal(productDetails.product.enable_tare_weight_handling))
{
- amountMessage = parseFloat(jsonForm.amount) - parseFloat(productDetails.stock_amount) - parseFloat(productDetails.product.tare_weight);
+ amount -= parseFloat(productDetails.product.tare_weight);
}
- var successMessage = __t('Added %1$s of %2$s to stock', amountMessage + " " + __n(amountMessage, productDetails.quantity_unit_stock.name, productDetails.quantity_unit_stock.name_plural), productDetails.product.name) + '
' + __t("Undo") + '';
-
- if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_LABELPRINTER)
+
+ var price = parseFloat(jsonForm.price * $("#qu_id option:selected").attr("data-qu-factor")).toFixed(Grocy.UserSettings.stock_decimal_places_prices);
+ if ($("input[name='price-type']:checked").val() == "total-price")
{
- if (Grocy.Webhooks.labelprinter !== undefined)
- {
- var post_data = {};
- post_data.product = productDetails.product.name;
- post_data.grocycode = 'grcy:p:' + jsonForm.product_id + ":" + result[0].stock_id
- if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
- {
- post_data.duedate = __t('DD') + ': ' + result[0].best_before_date
- }
-
- if (jsonForm.print_stock_label > 0)
- {
- var reps = 1;
- if (jsonForm.print_stock_label == 2)
- {
- reps = Math.floor(jsonData.amount);
- }
- Grocy.FrontendHelpers.RunWebhook(Grocy.Webhooks.labelprinter, post_data, reps);
- }
- }
+ price = parseFloat(price / amount).toFixed(Grocy.UserSettings.stock_decimal_places_prices);
}
-
- if (GetUriParam("embedded") !== undefined)
- {
- window.parent.postMessage(WindowMessageBag("ProductChanged", jsonForm.product_id), Grocy.BaseUrl);
- window.parent.postMessage(WindowMessageBag("AfterItemAdded", GetUriParam("listitemid")), Grocy.BaseUrl);
- window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", successMessage), Grocy.BaseUrl);
- window.parent.postMessage(WindowMessageBag("Ready"), Grocy.BaseUrl);
- window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
- }
- else
- {
- Grocy.FrontendHelpers.EndUiBusy("purchase-form");
- toastr.success(successMessage);
- Grocy.Components.ProductPicker.FinishFlow();
-
- if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING && BoolVal(Grocy.UserSettings.show_warning_on_purchase_when_due_date_is_earlier_than_next))
- {
- if (moment(jsonData.best_before_date).isBefore(CurrentProductDetails.next_due_date))
- {
- toastr.warning(__t("This is due earlier than already in-stock items"));
- }
- }
-
- Grocy.Components.ProductAmountPicker.Reset();
- $("#purchase-form").removeAttr("data-used-barcode");
- $("#display_amount").attr("min", Grocy.DefaultMinAmount);
- $('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_purchase_amount));
- $(".input-group-productamountpicker").trigger("change");
- $('#price').val('');
- $("#tare-weight-handling-info").addClass("d-none");
- if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
- {
- Grocy.Components.LocationPicker.Clear();
- }
- if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
- {
- Grocy.Components.DateTimePicker.Clear();
- }
- Grocy.Components.ProductPicker.SetValue('');
- if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
- {
- Grocy.Components.ShoppingLocationPicker.SetValue('');
- }
- Grocy.Components.ProductPicker.GetInputElement().focus();
- Grocy.Components.ProductCard.Refresh(jsonForm.product_id);
-
- $('#price-hint').text("");
- var priceTypeUnitPrice = $("#price-type-unit-price");
- var priceTypeUnitPriceLabel = $("[for=" + priceTypeUnitPrice.attr("id") + "]");
- priceTypeUnitPriceLabel.text(__t("Unit price"));
-
- Grocy.FrontendHelpers.ValidateForm('purchase-form');
- }
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy("purchase-form");
- console.error(xhr);
+
+ jsonData.price = price;
}
- );
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy("purchase-form");
- console.error(xhr);
- }
- );
-});
-
-if (Grocy.Components.ProductPicker !== undefined)
-{
- Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
- {
- if (BoolVal(Grocy.UserSettings.scan_mode_purchase_enabled))
- {
- Grocy.UISound.BarcodeScannerBeep();
- }
-
- var productId = $(e.target).val();
-
- if (productId)
- {
- Grocy.Components.ProductCard.Refresh(productId);
-
- Grocy.Api.Get('stock/products/' + productId,
- function(productDetails)
+
+ if (BoolVal(Grocy.UserSettings.show_purchased_date_on_purchase))
{
- CurrentProductDetails = productDetails;
-
- Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
- Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.default_quantity_unit_purchase.id);
- $('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_purchase_amount));
- $(".input-group-productamountpicker").trigger("change");
-
- if (GetUriParam("flow") === "shoppinglistitemtostock")
+ jsonData.purchased_date = Grocy.Components.DateTimePicker2.GetValue();
+ }
+
+ if (Grocy.Components.DateTimePicker)
+ {
+ jsonData.best_before_date = Grocy.Components.DateTimePicker.GetValue();
+ }
+ else
+ {
+ jsonData.best_before_date = null;
+ }
+
+ if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
+ {
+ jsonData.shopping_location_id = Grocy.Components.ShoppingLocationPicker.GetValue();
+ }
+ if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
+ {
+ jsonData.location_id = Grocy.Components.LocationPicker.GetValue();
+ }
+
+ Grocy.Api.Post('stock/products/' + jsonForm.product_id + '/add', jsonData,
+ function(result)
{
- Grocy.Components.ProductAmountPicker.SetQuantityUnit(GetUriParam("quId"));
- $('#display_amount').val(parseFloat(GetUriParam("amount") * $("#qu_id option:selected").attr("data-qu-factor")));
- }
-
- $(".input-group-productamountpicker").trigger("change");
-
- if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
- {
- if (productDetails.last_shopping_location_id != null)
+ if ($("#purchase-form").hasAttr("data-used-barcode"))
{
- Grocy.Components.ShoppingLocationPicker.SetId(productDetails.last_shopping_location_id);
+ Grocy.Api.Put('objects/product_barcodes/' + $("#purchase-form").attr("data-used-barcode"), { last_price: $("#price").val() },
+ function(result)
+ { },
+ function(xhr)
+ { }
+ );
+ }
+
+ if (BoolVal(Grocy.UserSettings.scan_mode_purchase_enabled))
+ {
+ Grocy.UISound.Success();
+ }
+
+ if (GetUriParam("flow") == "InplaceAddBarcodeToExistingProduct")
+ {
+ var jsonDataBarcode = {};
+ jsonDataBarcode.barcode = GetUriParam("barcode");
+ jsonDataBarcode.product_id = jsonForm.product_id;
+ jsonDataBarcode.shopping_location_id = jsonForm.shopping_location_id;
+
+ Grocy.Api.Post('objects/product_barcodes', jsonDataBarcode,
+ function(result)
+ {
+ $("#flow-info-InplaceAddBarcodeToExistingProduct").addClass("d-none");
+ $('#barcode-lookup-disabled-hint').addClass('d-none');
+ $('#barcode-lookup-hint').removeClass('d-none');
+ window.history.replaceState({}, document.title, U("/purchase"));
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy("purchase-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
+ }
+ );
+ }
+
+ var amountMessage = parseFloat(jsonForm.amount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts });
+ if (BoolVal(productDetails.product.enable_tare_weight_handling))
+ {
+ amountMessage = parseFloat(jsonForm.amount) - parseFloat(productDetails.stock_amount) - parseFloat(productDetails.product.tare_weight);
+ }
+ var successMessage = __t('Added %1$s of %2$s to stock', amountMessage + " " + __n(amountMessage, productDetails.quantity_unit_stock.name, productDetails.quantity_unit_stock.name_plural), productDetails.product.name) + '
' + __t("Undo") + '';
+
+ if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_LABELPRINTER)
+ {
+ if (Grocy.Webhooks.labelprinter !== undefined)
+ {
+ var post_data = {};
+ post_data.product = productDetails.product.name;
+ post_data.grocycode = 'grcy:p:' + jsonForm.product_id + ":" + result[0].stock_id
+ if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
+ {
+ post_data.duedate = __t('DD') + ': ' + result[0].best_before_date
+ }
+
+ if (jsonForm.print_stock_label > 0)
+ {
+ var reps = 1;
+ if (jsonForm.print_stock_label == 2)
+ {
+ reps = Math.floor(jsonData.amount);
+ }
+ Grocy.FrontendHelpers.RunWebhook(Grocy.Webhooks.labelprinter, post_data, reps);
+ }
+ }
+ }
+
+ if (GetUriParam("embedded") !== undefined)
+ {
+ window.parent.postMessage(WindowMessageBag("ProductChanged", jsonForm.product_id), Grocy.BaseUrl);
+ window.parent.postMessage(WindowMessageBag("AfterItemAdded", GetUriParam("listitemid")), Grocy.BaseUrl);
+ window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", successMessage), Grocy.BaseUrl);
+ window.parent.postMessage(WindowMessageBag("Ready"), Grocy.BaseUrl);
+ window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
}
else
{
- Grocy.Components.ShoppingLocationPicker.SetId(productDetails.default_shopping_location_id);
- }
- }
-
- if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
- {
- Grocy.Components.LocationPicker.SetId(productDetails.location.id);
- }
-
- if (productDetails.last_price == null || productDetails.last_price == 0)
- {
- $("#price").val("")
- }
- else
- {
- $('#price').val(parseFloat(productDetails.last_price / $("#qu_id option:selected").attr("data-qu-factor")));
- }
-
- var priceTypeUnitPrice = $("#price-type-unit-price");
- var priceTypeUnitPriceLabel = $("[for=" + priceTypeUnitPrice.attr("id") + "]");
- priceTypeUnitPriceLabel.text($("#qu_id option:selected").text() + " " + __t("price"));
-
- refreshPriceHint();
-
- if (productDetails.product.enable_tare_weight_handling == 1)
- {
- var minAmount = parseFloat(productDetails.product.tare_weight) / $("#qu_id option:selected").attr("data-qu-factor") + parseFloat(productDetails.stock_amount);
- $("#display_amount").attr("min", minAmount);
- $("#tare-weight-handling-info").removeClass("d-none");
- }
- else
- {
- $("#display_amount").attr("min", Grocy.DefaultMinAmount);
- $("#tare-weight-handling-info").addClass("d-none");
- }
-
- if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
- {
- if (productDetails.product.default_best_before_days.toString() !== '0')
- {
- if (productDetails.product.default_best_before_days == -1)
+ Grocy.FrontendHelpers.EndUiBusy("purchase-form");
+ toastr.success(successMessage);
+ Grocy.Components.ProductPicker.FinishFlow();
+
+ if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING && BoolVal(Grocy.UserSettings.show_warning_on_purchase_when_due_date_is_earlier_than_next))
{
- if (!$("#datetimepicker-shortcut").is(":checked"))
+ if (moment(jsonData.best_before_date).isBefore(CurrentProductDetails.next_due_date))
{
- $("#datetimepicker-shortcut").click();
+ toastr.warning(__t("This is due earlier than already in-stock items"));
}
}
+
+ Grocy.Components.ProductAmountPicker.Reset();
+ $("#purchase-form").removeAttr("data-used-barcode");
+ $("#display_amount").attr("min", Grocy.DefaultMinAmount);
+ $('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_purchase_amount));
+ $(".input-group-productamountpicker").trigger("change");
+ $('#price').val('');
+ $("#tare-weight-handling-info").addClass("d-none");
+ if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
+ {
+ Grocy.Components.LocationPicker.Clear();
+ }
+ if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
+ {
+ Grocy.Components.DateTimePicker.Clear();
+ }
+ Grocy.Components.ProductPicker.SetValue('');
+ if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
+ {
+ Grocy.Components.ShoppingLocationPicker.SetValue('');
+ }
+ Grocy.Components.ProductPicker.GetInputElement().focus();
+ Grocy.Components.ProductCard.Refresh(jsonForm.product_id);
+
+ $('#price-hint').text("");
+ var priceTypeUnitPrice = $("#price-type-unit-price");
+ var priceTypeUnitPriceLabel = $("[for=" + priceTypeUnitPrice.attr("id") + "]");
+ priceTypeUnitPriceLabel.text(__t("Unit price"));
+
+ Grocy.FrontendHelpers.ValidateForm('purchase-form');
+ }
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy("purchase-form");
+ console.error(xhr);
+ }
+ );
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy("purchase-form");
+ console.error(xhr);
+ }
+ );
+ });
+
+ if (Grocy.Components.ProductPicker !== undefined)
+ {
+ Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
+ {
+ if (BoolVal(Grocy.UserSettings.scan_mode_purchase_enabled))
+ {
+ Grocy.UISound.BarcodeScannerBeep();
+ }
+
+ var productId = $(e.target).val();
+
+ if (productId)
+ {
+ Grocy.Components.ProductCard.Refresh(productId);
+
+ Grocy.Api.Get('stock/products/' + productId,
+ function(productDetails)
+ {
+ CurrentProductDetails = productDetails;
+
+ Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
+ Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.default_quantity_unit_purchase.id);
+ $('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_purchase_amount));
+ $(".input-group-productamountpicker").trigger("change");
+
+ if (GetUriParam("flow") === "shoppinglistitemtostock")
+ {
+ Grocy.Components.ProductAmountPicker.SetQuantityUnit(GetUriParam("quId"));
+ $('#display_amount').val(parseFloat(GetUriParam("amount") * $("#qu_id option:selected").attr("data-qu-factor")));
+ }
+
+ $(".input-group-productamountpicker").trigger("change");
+
+ if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
+ {
+ if (productDetails.last_shopping_location_id != null)
+ {
+ Grocy.Components.ShoppingLocationPicker.SetId(productDetails.last_shopping_location_id);
+ }
else
{
- Grocy.Components.DateTimePicker.SetValue(moment().add(productDetails.product.default_best_before_days, 'days').format('YYYY-MM-DD'));
+ Grocy.Components.ShoppingLocationPicker.SetId(productDetails.default_shopping_location_id);
}
}
- }
-
- if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_LABELPRINTER)
- {
- $("#print_stock_label").val(productDetails.product.default_print_stock_label);
- if (productDetails.product.allow_label_per_unit)
+
+ if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{
- if ($('#default_print_stock_label').val() == "2")
- {
- $("#default_print_stock_label").val("0");
- }
- $('#label-option-per-unit').prop("disabled", true);
+ Grocy.Components.LocationPicker.SetId(productDetails.location.id);
+ }
+
+ if (productDetails.last_price == null || productDetails.last_price == 0)
+ {
+ $("#price").val("")
}
else
{
- $('#label-option-per-unit').prop("disabled", false);
+ $('#price').val(parseFloat(productDetails.last_price / $("#qu_id option:selected").attr("data-qu-factor")));
}
- }
-
- $("#display_amount").focus();
-
- Grocy.FrontendHelpers.ValidateForm('purchase-form');
- if (GetUriParam("flow") === "shoppinglistitemtostock" && BoolVal(Grocy.UserSettings.shopping_list_to_stock_workflow_auto_submit_when_prefilled) && document.getElementById("purchase-form").checkValidity() === true)
- {
- $("#save-purchase-button").click();
- }
-
- RefreshLocaleNumberInput();
- var elem = document.getElementById("product_id");
- if (elem.getAttribute("barcode") != "null" && !elem.getAttribute("barcode").startsWith("grcy"))
- {
- Grocy.Api.Get('objects/product_barcodes?query[]=barcode=' + document.getElementById("product_id").getAttribute("barcode"),
- function(barcodeResult)
+
+ var priceTypeUnitPrice = $("#price-type-unit-price");
+ var priceTypeUnitPriceLabel = $("[for=" + priceTypeUnitPrice.attr("id") + "]");
+ priceTypeUnitPriceLabel.text($("#qu_id option:selected").text() + " " + __t("price"));
+
+ refreshPriceHint();
+
+ if (productDetails.product.enable_tare_weight_handling == 1)
+ {
+ var minAmount = parseFloat(productDetails.product.tare_weight) / $("#qu_id option:selected").attr("data-qu-factor") + parseFloat(productDetails.stock_amount);
+ $("#display_amount").attr("min", minAmount);
+ $("#tare-weight-handling-info").removeClass("d-none");
+ }
+ else
+ {
+ $("#display_amount").attr("min", Grocy.DefaultMinAmount);
+ $("#tare-weight-handling-info").addClass("d-none");
+ }
+
+ if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
+ {
+ if (productDetails.product.default_best_before_days.toString() !== '0')
{
- if (barcodeResult != null)
+ if (productDetails.product.default_best_before_days == -1)
{
- var barcode = barcodeResult[0];
- $("#purchase-form").attr("data-used-barcode", barcode.id);
-
- if (barcode != null)
+ if (!$("#datetimepicker-shortcut").is(":checked"))
{
- if (barcode.amount != null && !barcode.amount.isEmpty())
- {
- $("#display_amount").val(barcode.amount);
- $("#display_amount").select();
- }
-
- if (barcode.qu_id != null)
- {
- Grocy.Components.ProductAmountPicker.SetQuantityUnit(barcode.qu_id);
- }
-
- if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING && barcode.shopping_location_id != null)
- {
- Grocy.Components.ShoppingLocationPicker.SetId(barcode.shopping_location_id);
- }
-
- if (barcode.last_price != null && !barcode.last_price.isEmpty())
- {
- $("#price").val(barcode.last_price);
- $("#price-type-total-price").click();
- }
-
- $(".input-group-productamountpicker").trigger("change");
- Grocy.FrontendHelpers.ValidateForm('purchase-form');
- RefreshLocaleNumberInput();
+ $("#datetimepicker-shortcut").click();
}
}
-
- Grocy.ScanModeSubmit(false);
- },
- function(xhr)
- {
- console.error(xhr);
+ else
+ {
+ Grocy.Components.DateTimePicker.SetValue(moment().add(productDetails.product.default_best_before_days, 'days').format('YYYY-MM-DD'));
+ }
}
- );
- }
- else
+ }
+
+ if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_LABELPRINTER)
+ {
+ $("#print_stock_label").val(productDetails.product.default_print_stock_label);
+ if (productDetails.product.allow_label_per_unit)
+ {
+ if ($('#default_print_stock_label').val() == "2")
+ {
+ $("#default_print_stock_label").val("0");
+ }
+ $('#label-option-per-unit').prop("disabled", true);
+ }
+ else
+ {
+ $('#label-option-per-unit').prop("disabled", false);
+ }
+ }
+
+ $("#display_amount").focus();
+
+ Grocy.FrontendHelpers.ValidateForm('purchase-form');
+ if (GetUriParam("flow") === "shoppinglistitemtostock" && BoolVal(Grocy.UserSettings.shopping_list_to_stock_workflow_auto_submit_when_prefilled) && document.getElementById("purchase-form").checkValidity() === true)
+ {
+ $("#save-purchase-button").click();
+ }
+
+ RefreshLocaleNumberInput();
+ var elem = document.getElementById("product_id");
+ if (elem.getAttribute("barcode") != "null" && !elem.getAttribute("barcode").startsWith("grcy"))
+ {
+ Grocy.Api.Get('objects/product_barcodes?query[]=barcode=' + document.getElementById("product_id").getAttribute("barcode"),
+ function(barcodeResult)
+ {
+ if (barcodeResult != null)
+ {
+ var barcode = barcodeResult[0];
+ $("#purchase-form").attr("data-used-barcode", barcode.id);
+
+ if (barcode != null)
+ {
+ if (barcode.amount != null && !barcode.amount.isEmpty())
+ {
+ $("#display_amount").val(barcode.amount);
+ $("#display_amount").select();
+ }
+
+ if (barcode.qu_id != null)
+ {
+ Grocy.Components.ProductAmountPicker.SetQuantityUnit(barcode.qu_id);
+ }
+
+ if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING && barcode.shopping_location_id != null)
+ {
+ Grocy.Components.ShoppingLocationPicker.SetId(barcode.shopping_location_id);
+ }
+
+ if (barcode.last_price != null && !barcode.last_price.isEmpty())
+ {
+ $("#price").val(barcode.last_price);
+ $("#price-type-total-price").click();
+ }
+
+ $(".input-group-productamountpicker").trigger("change");
+ Grocy.FrontendHelpers.ValidateForm('purchase-form');
+ RefreshLocaleNumberInput();
+ }
+ }
+
+ Grocy.ScanModeSubmit(false);
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ }
+ else
+ {
+ $("#purchase-form").removeAttr("data-used-barcode");
+ Grocy.ScanModeSubmit();
+ }
+
+ $('#display_amount').trigger("keyup");
+ },
+ function(xhr)
{
- $("#purchase-form").removeAttr("data-used-barcode");
- Grocy.ScanModeSubmit();
+ console.error(xhr);
}
-
- $('#display_amount').trigger("keyup");
- },
- function(xhr)
- {
- console.error(xhr);
- }
- );
- }
- });
-}
-
-$('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_purchase_amount));
-RefreshLocaleNumberInput();
-$(".input-group-productamountpicker").trigger("change");
-Grocy.FrontendHelpers.ValidateForm('purchase-form');
-
-if (Grocy.Components.ProductPicker)
-{
- if (Grocy.Components.ProductPicker.InAnyFlow() === false && GetUriParam("embedded") === undefined)
- {
- Grocy.Components.ProductPicker.GetInputElement().focus();
+ );
+ }
+ });
}
- else
+
+ $('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_purchase_amount));
+ RefreshLocaleNumberInput();
+ $(".input-group-productamountpicker").trigger("change");
+ Grocy.FrontendHelpers.ValidateForm('purchase-form');
+
+ if (Grocy.Components.ProductPicker)
{
- Grocy.Components.ProductPicker.GetPicker().trigger('change');
-
- if (Grocy.Components.ProductPicker.InProductModifyWorkflow())
+ if (Grocy.Components.ProductPicker.InAnyFlow() === false && GetUriParam("embedded") === undefined)
{
Grocy.Components.ProductPicker.GetInputElement().focus();
}
- }
-}
-
-$('#display_amount').on('focus', function(e)
-{
- if (Grocy.Components.ProductPicker.GetValue().length === 0)
- {
- Grocy.Components.ProductPicker.GetInputElement().focus();
- }
- else
- {
- $(this).select();
- }
-});
-
-$('#price').on('focus', function(e)
-{
- $(this).select();
-});
-
-$('#purchase-form input').keyup(function(event)
-{
- Grocy.FrontendHelpers.ValidateForm('purchase-form');
-});
-
-$('#purchase-form input').keydown(function(event)
-{
- if (event.keyCode === 13) //Enter
- {
- event.preventDefault();
-
- if (document.getElementById('purchase-form').checkValidity() === false) //There is at least one validation error
+ else
{
- return false;
+ Grocy.Components.ProductPicker.GetPicker().trigger('change');
+
+ if (Grocy.Components.ProductPicker.InProductModifyWorkflow())
+ {
+ Grocy.Components.ProductPicker.GetInputElement().focus();
+ }
+ }
+ }
+
+ $('#display_amount').on('focus', function(e)
+ {
+ if (Grocy.Components.ProductPicker.GetValue().length === 0)
+ {
+ Grocy.Components.ProductPicker.GetInputElement().focus();
}
else
{
- $('#save-purchase-button').click();
+ $(this).select();
}
- }
-});
-
-if (Grocy.Components.DateTimePicker)
-{
- Grocy.Components.DateTimePicker.GetInputElement().on('change', function(e)
+ });
+
+ $('#price').on('focus', function(e)
+ {
+ $(this).select();
+ });
+
+ $('#purchase-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('purchase-form');
});
-
- Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e)
+
+ $('#purchase-form input').keydown(function(event)
{
- Grocy.FrontendHelpers.ValidateForm('purchase-form');
- });
-}
-
-if (Grocy.Components.DateTimePicker2)
-{
- Grocy.Components.DateTimePicker2.GetInputElement().on('change', function(e)
- {
- Grocy.FrontendHelpers.ValidateForm('purchase-form');
- });
-
- Grocy.Components.DateTimePicker2.GetInputElement().on('keypress', function(e)
- {
- Grocy.FrontendHelpers.ValidateForm('purchase-form');
- });
-
- Grocy.Components.DateTimePicker2.GetInputElement().trigger("input");
-}
-
-$('#price').on('keyup', function(e)
-{
- refreshPriceHint();
-});
-
-$('#price-type-unit-price').on('change', function(e)
-{
- refreshPriceHint();
-});
-
-$('#price-type-total-price').on('change', function(e)
-{
- refreshPriceHint();
-});
-
-$('#display_amount').on('change', function(e)
-{
- refreshPriceHint();
- Grocy.FrontendHelpers.ValidateForm('purchase-form');
-});
-
-function refreshPriceHint()
-{
- if ($('#amount').val() == 0 || $('#price').val() == 0)
- {
- $('#price-hint').text("");
- return;
- }
-
- if ($("input[name='price-type']:checked").val() == "total-price" || $("#qu_id").attr("data-destination-qu-name") != $("#qu_id option:selected").text())
- {
- var amount = $('#display_amount').val();
- if (BoolVal(CurrentProductDetails.product.enable_tare_weight_handling))
+ if (event.keyCode === 13) //Enter
{
- amount -= parseFloat(CurrentProductDetails.product.tare_weight);
+ event.preventDefault();
+
+ if (document.getElementById('purchase-form').checkValidity() === false) //There is at least one validation error
+ {
+ return false;
+ }
+ else
+ {
+ $('#save-purchase-button').click();
+ }
}
-
- var price = parseFloat($('#price').val() * $("#qu_id option:selected").attr("data-qu-factor")).toFixed(Grocy.UserSettings.stock_decimal_places_prices);
- if ($("input[name='price-type']:checked").val() == "total-price")
+ });
+
+ if (Grocy.Components.DateTimePicker)
+ {
+ Grocy.Components.DateTimePicker.GetInputElement().on('change', function(e)
{
- price = parseFloat(price / amount).toFixed(Grocy.UserSettings.stock_decimal_places_prices);
+ Grocy.FrontendHelpers.ValidateForm('purchase-form');
+ });
+
+ Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e)
+ {
+ Grocy.FrontendHelpers.ValidateForm('purchase-form');
+ });
+ }
+
+ if (Grocy.Components.DateTimePicker2)
+ {
+ Grocy.Components.DateTimePicker2.GetInputElement().on('change', function(e)
+ {
+ Grocy.FrontendHelpers.ValidateForm('purchase-form');
+ });
+
+ Grocy.Components.DateTimePicker2.GetInputElement().on('keypress', function(e)
+ {
+ Grocy.FrontendHelpers.ValidateForm('purchase-form');
+ });
+
+ Grocy.Components.DateTimePicker2.GetInputElement().trigger("input");
+ }
+
+ $('#price').on('keyup', function(e)
+ {
+ refreshPriceHint();
+ });
+
+ $('#price-type-unit-price').on('change', function(e)
+ {
+ refreshPriceHint();
+ });
+
+ $('#price-type-total-price').on('change', function(e)
+ {
+ refreshPriceHint();
+ });
+
+ $('#display_amount').on('change', function(e)
+ {
+ refreshPriceHint();
+ Grocy.FrontendHelpers.ValidateForm('purchase-form');
+ });
+
+ function refreshPriceHint()
+ {
+ if ($('#amount').val() == 0 || $('#price').val() == 0)
+ {
+ $('#price-hint').text("");
+ return;
+ }
+
+ if ($("input[name='price-type']:checked").val() == "total-price" || $("#qu_id").attr("data-destination-qu-name") != $("#qu_id option:selected").text())
+ {
+ var amount = $('#display_amount').val();
+ if (BoolVal(CurrentProductDetails.product.enable_tare_weight_handling))
+ {
+ amount -= parseFloat(CurrentProductDetails.product.tare_weight);
+ }
+
+ var price = parseFloat($('#price').val() * $("#qu_id option:selected").attr("data-qu-factor")).toFixed(Grocy.UserSettings.stock_decimal_places_prices);
+ if ($("input[name='price-type']:checked").val() == "total-price")
+ {
+ price = parseFloat(price / amount).toFixed(Grocy.UserSettings.stock_decimal_places_prices);
+ }
+
+ $('#price-hint').text(__t('means %1$s per %2$s', price.toLocaleString(undefined, { style: "currency", currency: Grocy.Currency, minimumFractionDigits: Grocy.UserSettings.stock_decimal_places_prices, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_prices }), $("#qu_id").attr("data-destination-qu-name")));
+ }
+ else
+ {
+ $('#price-hint').text("");
}
-
- $('#price-hint').text(__t('means %1$s per %2$s', price.toLocaleString(undefined, { style: "currency", currency: Grocy.Currency, minimumFractionDigits: Grocy.UserSettings.stock_decimal_places_prices, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_prices }), $("#qu_id").attr("data-destination-qu-name")));
}
- else
+
+ $("#scan-mode").on("change", function(e)
{
- $('#price-hint').text("");
- }
+ if ($(this).prop("checked"))
+ {
+ Grocy.UISound.AskForPermission();
+ }
+ });
+
+ $("#scan-mode-button").on("click", function(e)
+ {
+ document.activeElement.blur();
+ $("#scan-mode").click();
+ $("#scan-mode-button").toggleClass("btn-success").toggleClass("btn-danger");
+ if ($("#scan-mode").prop("checked"))
+ {
+ $("#scan-mode-status").text(__t("on"));
+ }
+ else
+ {
+ $("#scan-mode-status").text(__t("off"));
+ }
+ });
+
+ $('#qu_id').on('change', function(e)
+ {
+ var priceTypeUnitPrice = $("#price-type-unit-price");
+ var priceTypeUnitPriceLabel = $("[for=" + priceTypeUnitPrice.attr("id") + "]");
+ priceTypeUnitPriceLabel.text($("#qu_id option:selected").text() + " " + __t("price"));
+ refreshPriceHint();
+ });
+
}
-
-$("#scan-mode").on("change", function(e)
-{
- if ($(this).prop("checked"))
- {
- Grocy.UISound.AskForPermission();
- }
-});
-
-$("#scan-mode-button").on("click", function(e)
-{
- document.activeElement.blur();
- $("#scan-mode").click();
- $("#scan-mode-button").toggleClass("btn-success").toggleClass("btn-danger");
- if ($("#scan-mode").prop("checked"))
- {
- $("#scan-mode-status").text(__t("on"));
- }
- else
- {
- $("#scan-mode-status").text(__t("off"));
- }
-});
-
-$('#qu_id').on('change', function(e)
-{
- var priceTypeUnitPrice = $("#price-type-unit-price");
- var priceTypeUnitPriceLabel = $("[for=" + priceTypeUnitPrice.attr("id") + "]");
- priceTypeUnitPriceLabel.text($("#qu_id option:selected").text() + " " + __t("price"));
- refreshPriceHint();
-});
diff --git a/js/viewjs/quantityunitconversionform.js b/js/viewjs/quantityunitconversionform.js
index 4b3d26bf..083d3cff 100644
--- a/js/viewjs/quantityunitconversionform.js
+++ b/js/viewjs/quantityunitconversionform.js
@@ -1,73 +1,114 @@
-import { WindowMessageBag } from '../helpers/messagebag';
-
-Grocy.Use("numberpicker");
-Grocy.Use("userfieldsform");
-
-$('#save-quconversion-button').on('click', function(e)
+function quantityunitconversionformView(Grocy, scope = null)
{
- e.preventDefault();
-
- if ($(".combobox-menu-visible").length)
+ var $scope = $;
+ if (scope != null)
{
- return;
+ $scope = $(scope).find;
}
- var jsonData = $('#quconversion-form').serializeJSON();
- jsonData.from_qu_id = $("#from_qu_id").val();
- Grocy.FrontendHelpers.BeginUiBusy("quconversion-form");
- if ($("#create_inverse").is(":checked"))
+ import { WindowMessageBag } from '../helpers/messagebag';
+
+ Grocy.Use("numberpicker");
+ Grocy.Use("userfieldsform");
+
+ $('#save-quconversion-button').on('click', function(e)
{
- var inverse_to_qu_id = $("#from_qu_id").val();
- var inverse_from_qu_id = $("#to_qu_id").val();
- }
-
- if (Grocy.EditMode === 'create')
- {
- Grocy.Api.Post('objects/quantity_unit_conversions', jsonData,
- function(result)
- {
- Grocy.EditObjectId = result.created_object_id;
- Grocy.Components.UserfieldsForm.Save(function()
+ e.preventDefault();
+
+ if ($(".combobox-menu-visible").length)
+ {
+ return;
+ }
+
+ var jsonData = $('#quconversion-form').serializeJSON();
+ jsonData.from_qu_id = $("#from_qu_id").val();
+ Grocy.FrontendHelpers.BeginUiBusy("quconversion-form");
+ if ($("#create_inverse").is(":checked"))
+ {
+ var inverse_to_qu_id = $("#from_qu_id").val();
+ var inverse_from_qu_id = $("#to_qu_id").val();
+ }
+
+ if (Grocy.EditMode === 'create')
+ {
+ Grocy.Api.Post('objects/quantity_unit_conversions', jsonData,
+ function(result)
{
- if ($("#create_inverse").is(":checked"))
+ Grocy.EditObjectId = result.created_object_id;
+ Grocy.Components.UserfieldsForm.Save(function()
{
- jsonData.to_qu_id = inverse_to_qu_id;
- jsonData.from_qu_id = inverse_from_qu_id;
- jsonData.factor = 1 / jsonData.factor;
-
- //Create Inverse
- Grocy.Api.Post('objects/quantity_unit_conversions', jsonData,
- function(result)
- {
- Grocy.EditObjectId = result.created_object_id;
- Grocy.Components.UserfieldsForm.Save(function()
+ if ($("#create_inverse").is(":checked"))
+ {
+ jsonData.to_qu_id = inverse_to_qu_id;
+ jsonData.from_qu_id = inverse_from_qu_id;
+ jsonData.factor = 1 / jsonData.factor;
+
+ //Create Inverse
+ Grocy.Api.Post('objects/quantity_unit_conversions', jsonData,
+ function(result)
{
- if (typeof GetUriParam("qu-unit") !== "undefined")
+ Grocy.EditObjectId = result.created_object_id;
+ Grocy.Components.UserfieldsForm.Save(function()
{
- if (GetUriParam("embedded") !== undefined)
+ if (typeof GetUriParam("qu-unit") !== "undefined")
{
- window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
+ if (GetUriParam("embedded") !== undefined)
+ {
+ window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
+ }
+ else
+ {
+ window.location.href = U("/quantityunit/" + GetUriParam("qu-unit"));
+ }
}
else
{
- window.location.href = U("/quantityunit/" + GetUriParam("qu-unit"));
+ window.parent.postMessage(WindowMessageBag("ProductQUConversionChanged"), U("/product/" + GetUriParam("product")));
+ window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
}
- }
- else
- {
- window.parent.postMessage(WindowMessageBag("ProductQUConversionChanged"), U("/product/" + GetUriParam("product")));
- window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
- }
- });
- },
- function(xhr)
+ });
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy("quconversion-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
+ }
+ else
+ {
+ if (typeof GetUriParam("qu-unit") !== "undefined")
{
- Grocy.FrontendHelpers.EndUiBusy("quconversion-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ if (GetUriParam("embedded") !== undefined)
+ {
+ window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
+ }
+ else
+ {
+ window.location.href = U("/quantityunit/" + GetUriParam("qu-unit"));
+ }
}
- );
- }
- else
+ else
+ {
+ window.parent.postMessage(WindowMessageBag("ProductQUConversionChanged"), U("/product/" + GetUriParam("product")));
+ window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
+ }
+ }
+ });
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy("quconversion-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
+ }
+ else
+ {
+ Grocy.Api.Put('objects/quantity_unit_conversions/' + Grocy.EditObjectId, jsonData,
+ function(result)
+ {
+ Grocy.Components.UserfieldsForm.Save(function()
{
if (typeof GetUriParam("qu-unit") !== "undefined")
{
@@ -85,129 +126,98 @@ $('#save-quconversion-button').on('click', function(e)
window.parent.postMessage(WindowMessageBag("ProductQUConversionChanged"), U("/product/" + GetUriParam("product")));
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
}
- }
- });
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy("quconversion-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
- else
- {
- Grocy.Api.Put('objects/quantity_unit_conversions/' + Grocy.EditObjectId, jsonData,
- function(result)
- {
- Grocy.Components.UserfieldsForm.Save(function()
+ });
+ },
+ function(xhr)
{
- if (typeof GetUriParam("qu-unit") !== "undefined")
- {
- if (GetUriParam("embedded") !== undefined)
- {
- window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
- }
- else
- {
- window.location.href = U("/quantityunit/" + GetUriParam("qu-unit"));
- }
- }
- else
- {
- window.parent.postMessage(WindowMessageBag("ProductQUConversionChanged"), U("/product/" + GetUriParam("product")));
- window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
- }
- });
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy("quconversion-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
-});
-
-$('#quconversion-form input').keyup(function(event)
-{
- $('.input-group-qu').trigger('change');
- Grocy.FrontendHelpers.ValidateForm('quconversion-form');
-});
-
-$('#quconversion-form input').keydown(function(event)
-{
- if (event.keyCode === 13) //Enter
+ Grocy.FrontendHelpers.EndUiBusy("quconversion-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
+ }
+ });
+
+ $('#quconversion-form input').keyup(function(event)
{
- event.preventDefault();
-
- if (document.getElementById('quconversion-form').checkValidity() === false) //There is at least one validation error
+ $('.input-group-qu').trigger('change');
+ Grocy.FrontendHelpers.ValidateForm('quconversion-form');
+ });
+
+ $('#quconversion-form input').keydown(function(event)
+ {
+ if (event.keyCode === 13) //Enter
{
- return false;
+ event.preventDefault();
+
+ if (document.getElementById('quconversion-form').checkValidity() === false) //There is at least one validation error
+ {
+ return false;
+ }
+ else
+ {
+ $('#save-quconversion-button').click();
+ }
+ }
+ });
+
+ $("#create_inverse").on("change", function()
+ {
+ var value = $(this).is(":checked");
+
+ if (value)
+ {
+ $('#qu-conversion-inverse-info').removeClass('d-none');
}
else
{
- $('#save-quconversion-button').click();
+ $('#qu-conversion-inverse-info').addClass('d-none');
}
- }
-});
-
-$("#create_inverse").on("change", function()
-{
- var value = $(this).is(":checked");
-
- if (value)
+ });
+
+ $('.input-group-qu').on('change', function(e)
{
- $('#qu-conversion-inverse-info').removeClass('d-none');
- }
- else
- {
- $('#qu-conversion-inverse-info').addClass('d-none');
- }
-});
-
-$('.input-group-qu').on('change', function(e)
-{
- var fromQuId = $("#from_qu_id").val();
- var toQuId = $("#to_qu_id").val();
- var factor = $('#factor').val();
-
- if (fromQuId == toQuId)
- {
- $("#to_qu_id").parent().find(".invalid-feedback").text(__t('This cannot be equal to %s', $("#from_qu_id option:selected").text()));
- $("#to_qu_id")[0].setCustomValidity("error");
- }
- else
- {
- $("#to_qu_id")[0].setCustomValidity("");
- }
-
- if (fromQuId && toQuId)
- {
- $('#qu-conversion-info').text(__t('This means 1 %1$s is the same as %2$s %3$s', $("#from_qu_id option:selected").text(), parseFloat((1 * factor)).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }), __n((1 * factor).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }), $("#to_qu_id option:selected").text(), $("#to_qu_id option:selected").data("plural-form"))));
- $('#qu-conversion-info').removeClass('d-none');
-
- if (Grocy.EditMode === 'create')
+ var fromQuId = $("#from_qu_id").val();
+ var toQuId = $("#to_qu_id").val();
+ var factor = $('#factor').val();
+
+ if (fromQuId == toQuId)
{
- $('#qu-conversion-inverse-info').text(__t('This means 1 %1$s is the same as %2$s %3$s', $("#to_qu_id option:selected").text(), parseFloat((1 / factor)).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }), __n((1 / factor).toString(), $("#from_qu_id option:selected").text(), $("#from_qu_id option:selected").data("plural-form"))));
- $('#qu-conversion-inverse-info').removeClass('d-none');
+ $("#to_qu_id").parent().find(".invalid-feedback").text(__t('This cannot be equal to %s', $("#from_qu_id option:selected").text()));
+ $("#to_qu_id")[0].setCustomValidity("error");
}
- }
- else
- {
- $('#qu-conversion-info').addClass('d-none');
- $('#qu-conversion-inverse-info').addClass('d-none');
- }
-
+ else
+ {
+ $("#to_qu_id")[0].setCustomValidity("");
+ }
+
+ if (fromQuId && toQuId)
+ {
+ $('#qu-conversion-info').text(__t('This means 1 %1$s is the same as %2$s %3$s', $("#from_qu_id option:selected").text(), parseFloat((1 * factor)).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }), __n((1 * factor).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }), $("#to_qu_id option:selected").text(), $("#to_qu_id option:selected").data("plural-form"))));
+ $('#qu-conversion-info').removeClass('d-none');
+
+ if (Grocy.EditMode === 'create')
+ {
+ $('#qu-conversion-inverse-info').text(__t('This means 1 %1$s is the same as %2$s %3$s', $("#to_qu_id option:selected").text(), parseFloat((1 / factor)).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }), __n((1 / factor).toString(), $("#from_qu_id option:selected").text(), $("#from_qu_id option:selected").data("plural-form"))));
+ $('#qu-conversion-inverse-info').removeClass('d-none');
+ }
+ }
+ else
+ {
+ $('#qu-conversion-info').addClass('d-none');
+ $('#qu-conversion-inverse-info').addClass('d-none');
+ }
+
+ Grocy.FrontendHelpers.ValidateForm('quconversion-form');
+ });
+
+ Grocy.Components.UserfieldsForm.Load();
+ $('.input-group-qu').trigger('change');
+ $('#from_qu_id').focus();
Grocy.FrontendHelpers.ValidateForm('quconversion-form');
-});
-
-Grocy.Components.UserfieldsForm.Load();
-$('.input-group-qu').trigger('change');
-$('#from_qu_id').focus();
-Grocy.FrontendHelpers.ValidateForm('quconversion-form');
-
-if (GetUriParam("qu-unit") !== undefined)
-{
- $("#from_qu_id").attr("disabled", "");
+
+ if (GetUriParam("qu-unit") !== undefined)
+ {
+ $("#from_qu_id").attr("disabled", "");
+ }
+
}
diff --git a/js/viewjs/quantityunitform.js b/js/viewjs/quantityunitform.js
index f752ceda..9a478ea6 100644
--- a/js/viewjs/quantityunitform.js
+++ b/js/viewjs/quantityunitform.js
@@ -1,179 +1,189 @@
-import { WindowMessageBag } from '../helpers/messagebag';
-
-Grocy.Use("userfieldsform");
-
-$('.save-quantityunit-button').on('click', function(e)
+function quantityunitformView(Grocy, scope = null)
{
- e.preventDefault();
-
- var jsonData = $('#quantityunit-form').serializeJSON();
- Grocy.FrontendHelpers.BeginUiBusy("quantityunit-form");
-
- var redirectDestination = U('/quantityunits');
- if (Grocy.QuantityUnitEditFormRedirectUri !== undefined)
+ var $scope = $;
+ if (scope != null)
{
- redirectDestination = Grocy.QuantityUnitEditFormRedirectUri;
+ $scope = $(scope).find;
}
- if ($(e.currentTarget).attr('data-location') == "continue")
+ import { WindowMessageBag } from '../helpers/messagebag';
+
+ Grocy.Use("userfieldsform");
+
+ $('.save-quantityunit-button').on('click', function(e)
{
- redirectDestination = "reload";
- }
-
- if (Grocy.EditMode === 'create')
- {
- Grocy.Api.Post('objects/quantity_units', jsonData,
- function(result)
- {
- Grocy.EditObjectId = result.created_object_id;
- Grocy.Components.UserfieldsForm.Save(function()
- {
- if (GetUriParam("embedded") !== undefined)
- {
- window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
- }
- else
- {
-
- if (redirectDestination == "reload")
- {
- window.location.href = U("/quantityunit/" + result.created_object_id.toString());
- }
- else if (redirectDestination == "stay")
- {
- // Do nothing
- }
- else
- {
- window.location.href = redirectDestination.replace("editobjectid", Grocy.EditObjectId);
- }
- }
- });
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy("quantityunit-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
- else
- {
- Grocy.Api.Put('objects/quantity_units/' + Grocy.EditObjectId, jsonData,
- function(result)
- {
- Grocy.Components.UserfieldsForm.Save(function()
- {
- if (GetUriParam("embedded") !== undefined)
- {
- window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
- }
- else
- {
-
- if (redirectDestination == "reload")
- {
- window.location.reload();
- }
- else if (redirectDestination == "stay")
- {
- // Do nothing
- }
- else
- {
- window.location.href = redirectDestination.replace("editobjectid", Grocy.EditObjectId);
- }
- }
- });
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy("quantityunit-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
-});
-
-$('#quantityunit-form input').keyup(function(event)
-{
- if (!$("#name").val().isEmpty())
- {
- $("#qu-conversion-headline-info").text(__t('1 %s is the same as...', $("#name").val()));
- }
- else
- {
- $("#qu-conversion-headline-info").text("");
- }
-
- if (document.getElementById('quantityunit-form').checkValidity() === false) //There is at least one validation error
- {
- $("#qu-conversion-add-button").addClass("disabled");
- }
- else
- {
- $("#qu-conversion-add-button").removeClass("disabled");
- }
-
- Grocy.FrontendHelpers.ValidateForm('quantityunit-form');
-});
-
-$('#quantityunit-form input').keydown(function(event)
-{
- if (event.keyCode === 13) //Enter
- {
- event.preventDefault();
-
- if (document.getElementById('quantityunit-form').checkValidity() === false) //There is at least one validation error
+ e.preventDefault();
+
+ var jsonData = $('#quantityunit-form').serializeJSON();
+ Grocy.FrontendHelpers.BeginUiBusy("quantityunit-form");
+
+ var redirectDestination = U('/quantityunits');
+ if (Grocy.QuantityUnitEditFormRedirectUri !== undefined)
{
- return false;
+ redirectDestination = Grocy.QuantityUnitEditFormRedirectUri;
+ }
+
+ if ($(e.currentTarget).attr('data-location') == "continue")
+ {
+ redirectDestination = "reload";
+ }
+
+ if (Grocy.EditMode === 'create')
+ {
+ Grocy.Api.Post('objects/quantity_units', jsonData,
+ function(result)
+ {
+ Grocy.EditObjectId = result.created_object_id;
+ Grocy.Components.UserfieldsForm.Save(function()
+ {
+ if (GetUriParam("embedded") !== undefined)
+ {
+ window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
+ }
+ else
+ {
+
+ if (redirectDestination == "reload")
+ {
+ window.location.href = U("/quantityunit/" + result.created_object_id.toString());
+ }
+ else if (redirectDestination == "stay")
+ {
+ // Do nothing
+ }
+ else
+ {
+ window.location.href = redirectDestination.replace("editobjectid", Grocy.EditObjectId);
+ }
+ }
+ });
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy("quantityunit-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
}
else
{
- $('#save-quantityunit-button').click();
- }
- }
-});
-
-var quConversionsTable = $('#qu-conversions-table').DataTable({
- 'order': [[1, 'asc']],
- 'columnDefs': [
- { 'orderable': false, 'targets': 0 },
- { 'searchable': false, "targets": 0 }
- ].concat($.fn.dataTable.defaults.columnDefs)
-});
-$('#qu-conversions-table tbody').removeClass("d-none");
-quConversionsTable.columns.adjust().draw();
-
-Grocy.Components.UserfieldsForm.Load();
-$("#name").trigger("keyup");
-$('#name').focus();
-Grocy.FrontendHelpers.ValidateForm('quantityunit-form');
-
-Grocy.FrontendHelpers.MakeDeleteConfirmBox(
- 'Are you sure to remove this conversion?',
- '.qu-conversion-delete-button',
- 'data-qu-conversion-id',
- 'data-qu-conversion-id',
- 'objects/quantity_unit_conversions/',
- () => window.location.reload(),
-);
-
-$("#test-quantityunit-plural-forms-button").on("click", function(e)
-{
- e.preventDefault();
-
- Grocy.QuantityUnitEditFormRedirectUri = "stay";
- $("#save-quantityunit-button").click();
-
- bootbox.alert({
- message: '',
- closeButton: false,
- size: "large",
- callback: function(result)
- {
- Grocy.QuantityUnitEditFormRedirectUri = undefined;
- Grocy.FrontendHelpers.EndUiBusy("quantityunit-form");
+ Grocy.Api.Put('objects/quantity_units/' + Grocy.EditObjectId, jsonData,
+ function(result)
+ {
+ Grocy.Components.UserfieldsForm.Save(function()
+ {
+ if (GetUriParam("embedded") !== undefined)
+ {
+ window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
+ }
+ else
+ {
+
+ if (redirectDestination == "reload")
+ {
+ window.location.reload();
+ }
+ else if (redirectDestination == "stay")
+ {
+ // Do nothing
+ }
+ else
+ {
+ window.location.href = redirectDestination.replace("editobjectid", Grocy.EditObjectId);
+ }
+ }
+ });
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy("quantityunit-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
}
});
-});
+
+ $('#quantityunit-form input').keyup(function(event)
+ {
+ if (!$("#name").val().isEmpty())
+ {
+ $("#qu-conversion-headline-info").text(__t('1 %s is the same as...', $("#name").val()));
+ }
+ else
+ {
+ $("#qu-conversion-headline-info").text("");
+ }
+
+ if (document.getElementById('quantityunit-form').checkValidity() === false) //There is at least one validation error
+ {
+ $("#qu-conversion-add-button").addClass("disabled");
+ }
+ else
+ {
+ $("#qu-conversion-add-button").removeClass("disabled");
+ }
+
+ Grocy.FrontendHelpers.ValidateForm('quantityunit-form');
+ });
+
+ $('#quantityunit-form input').keydown(function(event)
+ {
+ if (event.keyCode === 13) //Enter
+ {
+ event.preventDefault();
+
+ if (document.getElementById('quantityunit-form').checkValidity() === false) //There is at least one validation error
+ {
+ return false;
+ }
+ else
+ {
+ $('#save-quantityunit-button').click();
+ }
+ }
+ });
+
+ var quConversionsTable = $('#qu-conversions-table').DataTable({
+ 'order': [[1, 'asc']],
+ 'columnDefs': [
+ { 'orderable': false, 'targets': 0 },
+ { 'searchable': false, "targets": 0 }
+ ].concat($.fn.dataTable.defaults.columnDefs)
+ });
+ $('#qu-conversions-table tbody').removeClass("d-none");
+ quConversionsTable.columns.adjust().draw();
+
+ Grocy.Components.UserfieldsForm.Load();
+ $("#name").trigger("keyup");
+ $('#name').focus();
+ Grocy.FrontendHelpers.ValidateForm('quantityunit-form');
+
+ Grocy.FrontendHelpers.MakeDeleteConfirmBox(
+ 'Are you sure to remove this conversion?',
+ '.qu-conversion-delete-button',
+ 'data-qu-conversion-id',
+ 'data-qu-conversion-id',
+ 'objects/quantity_unit_conversions/',
+ () => window.location.reload(),
+ );
+
+ $("#test-quantityunit-plural-forms-button").on("click", function(e)
+ {
+ e.preventDefault();
+
+ Grocy.QuantityUnitEditFormRedirectUri = "stay";
+ $("#save-quantityunit-button").click();
+
+ bootbox.alert({
+ message: '',
+ closeButton: false,
+ size: "large",
+ callback: function(result)
+ {
+ Grocy.QuantityUnitEditFormRedirectUri = undefined;
+ Grocy.FrontendHelpers.EndUiBusy("quantityunit-form");
+ }
+ });
+ });
+
+}
diff --git a/js/viewjs/quantityunitpluraltesting.js b/js/viewjs/quantityunitpluraltesting.js
index 742aa960..cc8338b4 100644
--- a/js/viewjs/quantityunitpluraltesting.js
+++ b/js/viewjs/quantityunitpluraltesting.js
@@ -1,39 +1,49 @@
-Grocy.Use("numberpicker");
-
-$("#qu_id").change(function(event)
+function quantityunitpluraltestingView(Grocy, scope = null)
{
- RefreshQuPluralTestingResult();
-});
-
-$("#amount").keyup(function(event)
-{
- RefreshQuPluralTestingResult();
-});
-
-$("#amount").change(function(event)
-{
- RefreshQuPluralTestingResult();
-});
-
-function RefreshQuPluralTestingResult()
-{
- var singularForm = $("#qu_id option:selected").data("singular-form");
- var pluralForm = $("#qu_id option:selected").data("plural-form");
- var amount = $("#amount").val();
-
- if (singularForm.toString().isEmpty() || amount.toString().isEmpty())
+ var $scope = $;
+ if (scope != null)
{
- return;
+ $scope = $(scope).find;
}
- animateCSS("h2", "shake");
- $("#result").text(__n(amount, singularForm, pluralForm));
+ Grocy.Use("numberpicker");
+
+ $("#qu_id").change(function(event)
+ {
+ RefreshQuPluralTestingResult();
+ });
+
+ $("#amount").keyup(function(event)
+ {
+ RefreshQuPluralTestingResult();
+ });
+
+ $("#amount").change(function(event)
+ {
+ RefreshQuPluralTestingResult();
+ });
+
+ function RefreshQuPluralTestingResult()
+ {
+ var singularForm = $("#qu_id option:selected").data("singular-form");
+ var pluralForm = $("#qu_id option:selected").data("plural-form");
+ var amount = $("#amount").val();
+
+ if (singularForm.toString().isEmpty() || amount.toString().isEmpty())
+ {
+ return;
+ }
+
+ animateCSS("h2", "shake");
+ $("#result").text(__n(amount, singularForm, pluralForm));
+ }
+
+ if (GetUriParam("qu") !== undefined)
+ {
+ $("#qu_id").val(GetUriParam("qu"));
+ $("#qu_id").trigger("change");
+ }
+
+ $("#amount").focus();
+
}
-
-if (GetUriParam("qu") !== undefined)
-{
- $("#qu_id").val(GetUriParam("qu"));
- $("#qu_id").trigger("change");
-}
-
-$("#amount").focus();
diff --git a/js/viewjs/quantityunits.js b/js/viewjs/quantityunits.js
index 46f4002b..8002722a 100644
--- a/js/viewjs/quantityunits.js
+++ b/js/viewjs/quantityunits.js
@@ -1,17 +1,26 @@
-var quantityUnitsTable = $('#quantityunits-table').DataTable({
- 'order': [[1, 'asc']],
- 'columnDefs': [
- { 'orderable': false, 'targets': 0 },
- { 'searchable': false, "targets": 0 }
- ].concat($.fn.dataTable.defaults.columnDefs)
-});
-$('#quantityunits-table tbody').removeClass("d-none");
-Grocy.FrontendHelpers.InitDataTable(quantityUnitsTable);
-Grocy.FrontendHelpers.MakeDeleteConfirmBox(
- 'Are you sure to delete quantity unit "%s"?',
- '.quantityunit-delete-button',
- 'data-quantityunit-name',
- 'data-quantityunit-id',
- 'objects/quantity_units/',
- '/quantityunits'
-);
\ No newline at end of file
+function quantityunitsView(Grocy, scope = null)
+{
+ var $scope = $;
+ if (scope != null)
+ {
+ $scope = $(scope).find;
+ }
+
+ var quantityUnitsTable = $('#quantityunits-table').DataTable({
+ 'order': [[1, 'asc']],
+ 'columnDefs': [
+ { 'orderable': false, 'targets': 0 },
+ { 'searchable': false, "targets": 0 }
+ ].concat($.fn.dataTable.defaults.columnDefs)
+ });
+ $('#quantityunits-table tbody').removeClass("d-none");
+ Grocy.FrontendHelpers.InitDataTable(quantityUnitsTable);
+ Grocy.FrontendHelpers.MakeDeleteConfirmBox(
+ 'Are you sure to delete quantity unit "%s"?',
+ '.quantityunit-delete-button',
+ 'data-quantityunit-name',
+ 'data-quantityunit-id',
+ 'objects/quantity_units/',
+ '/quantityunits'
+ );
+}
diff --git a/js/viewjs/recipeform.js b/js/viewjs/recipeform.js
index cffa1f54..ddc08cbd 100644
--- a/js/viewjs/recipeform.js
+++ b/js/viewjs/recipeform.js
@@ -1,336 +1,346 @@
-import { WindowMessageBag } from '../helpers/messagebag';
-
-Grocy.Use("numberpicker");
-Grocy.Use("recipepicker");
-Grocy.Use("userfieldsform");
-
-function saveRecipePicture(result, location, jsonData)
+function recipeformView(Grocy, scope = null)
{
- var recipeId = Grocy.EditObjectId || result.created_object_id;
- Grocy.Components.UserfieldsForm.Save(() =>
+ var $scope = $;
+ if (scope != null)
{
- if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteRecipePictureOnSave)
+ $scope = $(scope).find;
+ }
+
+ import { WindowMessageBag } from '../helpers/messagebag';
+
+ Grocy.Use("numberpicker");
+ Grocy.Use("recipepicker");
+ Grocy.Use("userfieldsform");
+
+ function saveRecipePicture(result, location, jsonData)
+ {
+ var recipeId = Grocy.EditObjectId || result.created_object_id;
+ Grocy.Components.UserfieldsForm.Save(() =>
{
- Grocy.Api.UploadFile($("#recipe-picture")[0].files[0], 'recipepictures', jsonData.picture_file_name,
- (result) =>
+ if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteRecipePictureOnSave)
+ {
+ Grocy.Api.UploadFile($("#recipe-picture")[0].files[0], 'recipepictures', jsonData.picture_file_name,
+ (result) =>
+ {
+ window.location.href = U(location + recipeId);
+ },
+ (xhr) =>
+ {
+ Grocy.FrontendHelpers.EndUiBusy("recipe-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
+ }
+ else
+ {
+ window.location.href = U(location + recipeId);
+ }
+ });
+ }
+
+ $('.save-recipe').on('click', function(e)
+ {
+ e.preventDefault();
+
+ var jsonData = $('#recipe-form').serializeJSON();
+ Grocy.FrontendHelpers.BeginUiBusy("recipe-form");
+
+ if ($("#recipe-picture")[0].files.length > 0)
+ {
+ var someRandomStuff = Math.random().toString(36).substring(2, 100) + Math.random().toString(36).substring(2, 100);
+ jsonData.picture_file_name = someRandomStuff + $("#recipe-picture")[0].files[0].name;
+ }
+
+ const location = $(e.currentTarget).attr('data-location') == 'return' ? '/recipes?recipe=' : '/recipe/';
+
+ if (Grocy.EditMode == 'create')
+ {
+ Grocy.Api.Post('objects/recipes', jsonData,
+ (result) => saveRecipePicture(result, location, jsonData));
+ return;
+ }
+
+ if (Grocy.DeleteRecipePictureOnSave)
+ {
+ jsonData.picture_file_name = null;
+
+ Grocy.Api.DeleteFile(Grocy.RecipePictureFileName, 'recipepictures', {},
+ function(result)
{
- window.location.href = U(location + recipeId);
+ // Nothing to do
},
- (xhr) =>
+ function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("recipe-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
- else
- {
- window.location.href = U(location + recipeId);
- }
- });
-}
-
-$('.save-recipe').on('click', function(e)
-{
- e.preventDefault();
-
- var jsonData = $('#recipe-form').serializeJSON();
- Grocy.FrontendHelpers.BeginUiBusy("recipe-form");
-
- if ($("#recipe-picture")[0].files.length > 0)
- {
- var someRandomStuff = Math.random().toString(36).substring(2, 100) + Math.random().toString(36).substring(2, 100);
- jsonData.picture_file_name = someRandomStuff + $("#recipe-picture")[0].files[0].name;
- }
-
- const location = $(e.currentTarget).attr('data-location') == 'return' ? '/recipes?recipe=' : '/recipe/';
-
- if (Grocy.EditMode == 'create')
- {
- Grocy.Api.Post('objects/recipes', jsonData,
- (result) => saveRecipePicture(result, location, jsonData));
- return;
- }
-
- if (Grocy.DeleteRecipePictureOnSave)
- {
- jsonData.picture_file_name = null;
-
- Grocy.Api.DeleteFile(Grocy.RecipePictureFileName, 'recipepictures', {},
- function(result)
- {
- // Nothing to do
- },
+
+ Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, jsonData,
+ (result) => saveRecipePicture(result, location, jsonData),
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("recipe-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ console.error(xhr);
}
);
- }
-
- Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, jsonData,
- (result) => saveRecipePicture(result, location, jsonData),
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy("recipe-form");
- console.error(xhr);
+ });
+
+ var recipesPosTables = $('#recipes-pos-table').DataTable({
+ 'order': [[1, 'asc']],
+ "orderFixed": [[4, 'asc']],
+ 'columnDefs': [
+ { 'orderable': false, 'targets': 0 },
+ { 'searchable': false, "targets": 0 },
+ { 'visible': false, 'targets': 4 }
+ ].concat($.fn.dataTable.defaults.columnDefs),
+ 'rowGroup': {
+ enable: true,
+ dataSrc: 4
}
- );
-});
-
-var recipesPosTables = $('#recipes-pos-table').DataTable({
- 'order': [[1, 'asc']],
- "orderFixed": [[4, 'asc']],
- 'columnDefs': [
- { 'orderable': false, 'targets': 0 },
- { 'searchable': false, "targets": 0 },
- { 'visible': false, 'targets': 4 }
- ].concat($.fn.dataTable.defaults.columnDefs),
- 'rowGroup': {
- enable: true,
- dataSrc: 4
- }
-});
-$('#recipes-pos-table tbody').removeClass("d-none");
-recipesPosTables.columns.adjust().draw();
-
-var recipesIncludesTables = $('#recipes-includes-table').DataTable({
- 'order': [[1, 'asc']],
- 'columnDefs': [
- { 'orderable': false, 'targets': 0 },
- { 'searchable': false, "targets": 0 }
- ].concat($.fn.dataTable.defaults.columnDefs)
-});
-$('#recipes-includes-table tbody').removeClass("d-none");
-recipesIncludesTables.columns.adjust().draw();
-
-Grocy.FrontendHelpers.ValidateForm('recipe-form');
-$("#name").focus();
-
-$('#recipe-form input').keyup(function(event)
-{
+ });
+ $('#recipes-pos-table tbody').removeClass("d-none");
+ recipesPosTables.columns.adjust().draw();
+
+ var recipesIncludesTables = $('#recipes-includes-table').DataTable({
+ 'order': [[1, 'asc']],
+ 'columnDefs': [
+ { 'orderable': false, 'targets': 0 },
+ { 'searchable': false, "targets": 0 }
+ ].concat($.fn.dataTable.defaults.columnDefs)
+ });
+ $('#recipes-includes-table tbody').removeClass("d-none");
+ recipesIncludesTables.columns.adjust().draw();
+
Grocy.FrontendHelpers.ValidateForm('recipe-form');
-});
-
-$('#recipe-form input').keydown(function(event)
-{
- if (event.keyCode === 13) //Enter
+ $("#name").focus();
+
+ $('#recipe-form input').keyup(function(event)
{
- event.preventDefault();
-
- if (document.getElementById('recipe-form').checkValidity() === false) //There is at least one validation error
+ Grocy.FrontendHelpers.ValidateForm('recipe-form');
+ });
+
+ $('#recipe-form input').keydown(function(event)
+ {
+ if (event.keyCode === 13) //Enter
{
- return false;
- }
- else
- {
- $('#save-recipe-button').click();
- }
- }
-});
-
-Grocy.FrontendHelpers.MakeDeleteConfirmBox(
- 'Are you sure to delete recipe ingredient "%s"?',
- '.recipe-pos-delete-button',
- 'data-recipe-pos-name',
- 'data-recipe-pos-id',
- 'objects/recipes_pos/',
- () => window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl)
-);
-
-Grocy.FrontendHelpers.MakeDeleteConfirmBox(
- 'Are you sure to remove the included recipe "%s"?',
- '.recipe-include-delete-button',
- 'data-recipe-include-name',
- 'data-recipe-include-id',
- 'objects/recipes_nesting/',
- () => window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl)
-);
-
-$(document).on('click', '.recipe-pos-show-note-button', function(e)
-{
- var note = $(e.currentTarget).attr('data-recipe-pos-note');
-
- bootbox.alert(note);
-});
-
-$(document).on('click', '.recipe-pos-edit-button', function(e)
-{
- e.preventDefault();
-
- var productId = $(e.currentTarget).attr("data-product-id");
- var recipePosId = $(e.currentTarget).attr('data-recipe-pos-id');
-
- bootbox.dialog({
- message: '',
- size: 'large',
- backdrop: true,
- closeButton: false,
- buttons: {
- cancel: {
- label: __t('Cancel'),
- className: 'btn-secondary responsive-button',
- callback: function()
- {
- bootbox.hideAll();
- }
+ event.preventDefault();
+
+ if (document.getElementById('recipe-form').checkValidity() === false) //There is at least one validation error
+ {
+ return false;
+ }
+ else
+ {
+ $('#save-recipe-button').click();
}
}
});
-});
-
-$(document).on('click', '.recipe-include-edit-button', function(e)
-{
- var id = $(e.currentTarget).attr('data-recipe-include-id');
- var recipeId = $(e.currentTarget).attr('data-recipe-included-recipe-id');
- var recipeServings = $(e.currentTarget).attr('data-recipe-included-recipe-servings');
-
- Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(),
- function(result)
- {
- $("#recipe-include-editform-title").text(__t("Edit included recipe"));
- $("#recipe-include-form").data("edit-mode", "edit");
- $("#recipe-include-form").data("recipe-nesting-id", id);
- Grocy.Components.RecipePicker.SetId(recipeId);
- $("#includes_servings").val(recipeServings);
- $("#recipe-include-editform-modal").modal("show");
- Grocy.FrontendHelpers.ValidateForm("recipe-include-form");
- },
- function(xhr)
- {
- console.error(xhr);
- }
+
+ Grocy.FrontendHelpers.MakeDeleteConfirmBox(
+ 'Are you sure to delete recipe ingredient "%s"?',
+ '.recipe-pos-delete-button',
+ 'data-recipe-pos-name',
+ 'data-recipe-pos-id',
+ 'objects/recipes_pos/',
+ () => window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl)
);
-});
-
-$("#recipe-pos-add-button").on("click", function(e)
-{
- e.preventDefault();
-
- bootbox.dialog({
- message: '',
- size: 'large',
- backdrop: true,
- closeButton: false,
- buttons: {
- cancel: {
- label: __t('Cancel'),
- className: 'btn-secondary responsive-button',
- callback: function()
- {
- bootbox.hideAll();
+
+ Grocy.FrontendHelpers.MakeDeleteConfirmBox(
+ 'Are you sure to remove the included recipe "%s"?',
+ '.recipe-include-delete-button',
+ 'data-recipe-include-name',
+ 'data-recipe-include-id',
+ 'objects/recipes_nesting/',
+ () => window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl)
+ );
+
+ $(document).on('click', '.recipe-pos-show-note-button', function(e)
+ {
+ var note = $(e.currentTarget).attr('data-recipe-pos-note');
+
+ bootbox.alert(note);
+ });
+
+ $(document).on('click', '.recipe-pos-edit-button', function(e)
+ {
+ e.preventDefault();
+
+ var productId = $(e.currentTarget).attr("data-product-id");
+ var recipePosId = $(e.currentTarget).attr('data-recipe-pos-id');
+
+ bootbox.dialog({
+ message: '',
+ size: 'large',
+ backdrop: true,
+ closeButton: false,
+ buttons: {
+ cancel: {
+ label: __t('Cancel'),
+ className: 'btn-secondary responsive-button',
+ callback: function()
+ {
+ bootbox.hideAll();
+ }
}
}
- }
+ });
});
-});
-
-$("#recipe-include-add-button").on("click", function(e)
-{
- Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(),
- function(result)
- {
- $("#recipe-include-editform-title").text(__t("Add included recipe"));
- $("#recipe-include-form").data("edit-mode", "create");
- Grocy.Components.RecipePicker.Clear();
- Grocy.Components.RecipePicker.GetInputElement().focus();
- $("#recipe-include-editform-modal").modal("show");
- Grocy.FrontendHelpers.ValidateForm("recipe-include-form");
- },
- function(xhr)
- {
- console.error(xhr);
- }
- );
-});
-
-$('#save-recipe-include-button').on('click', function(e)
-{
- e.preventDefault();
-
- if ($(".combobox-menu-visible").length)
- {
- return;
- }
-
- if (document.getElementById("recipe-include-form").checkValidity() === false) //There is at least one validation error
- {
- return false;
- }
-
- var nestingId = $("#recipe-include-form").data("recipe-nesting-id");
- var editMode = $("#recipe-include-form").data("edit-mode");
-
- var jsonData = {};
- jsonData.includes_recipe_id = Grocy.Components.RecipePicker.GetValue();
- jsonData.servings = $("#includes_servings").val();
- jsonData.recipe_id = Grocy.EditObjectId;
-
- if (editMode === 'create')
- {
- Grocy.Api.Post('objects/recipes_nestings', jsonData,
- function(result)
- {
- window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
- else
- {
- Grocy.Api.Put('objects/recipes_nestings/' + nestingId, jsonData,
- function(result)
- {
- window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
-});
-
-$("#recipe-picture").on("change", function(e)
-{
- $("#recipe-picture-label").removeClass("d-none");
- $("#recipe-picture-label-none").addClass("d-none");
- $("#delete-current-recipe-picture-on-save-hint").addClass("d-none");
- $("#current-recipe-picture").addClass("d-none");
- Grocy.DeleteRecipePictureOnSave = false;
-});
-
-Grocy.DeleteRecipePictureOnSave = false;
-$("#delete-current-recipe-picture-button").on("click", function(e)
-{
- Grocy.DeleteRecipePictureOnSave = true;
- $("#current-recipe-picture").addClass("d-none");
- $("#delete-current-recipe-picture-on-save-hint").removeClass("d-none");
- $("#recipe-picture-label").addClass("d-none");
- $("#recipe-picture-label-none").removeClass("d-none");
-});
-
-Grocy.Components.UserfieldsForm.Load();
-
-$(window).on("message", function(e)
-{
- var data = e.originalEvent.data;
-
- if (data.Message === "IngredientsChanged")
+
+ $(document).on('click', '.recipe-include-edit-button', function(e)
{
+ var id = $(e.currentTarget).attr('data-recipe-include-id');
+ var recipeId = $(e.currentTarget).attr('data-recipe-included-recipe-id');
+ var recipeServings = $(e.currentTarget).attr('data-recipe-included-recipe-servings');
+
Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(),
function(result)
{
- window.location.href = U('/recipe/' + Grocy.EditObjectId);
+ $("#recipe-include-editform-title").text(__t("Edit included recipe"));
+ $("#recipe-include-form").data("edit-mode", "edit");
+ $("#recipe-include-form").data("recipe-nesting-id", id);
+ Grocy.Components.RecipePicker.SetId(recipeId);
+ $("#includes_servings").val(recipeServings);
+ $("#recipe-include-editform-modal").modal("show");
+ Grocy.FrontendHelpers.ValidateForm("recipe-include-form");
},
function(xhr)
{
console.error(xhr);
}
);
- }
-});
+ });
+
+ $("#recipe-pos-add-button").on("click", function(e)
+ {
+ e.preventDefault();
+
+ bootbox.dialog({
+ message: '',
+ size: 'large',
+ backdrop: true,
+ closeButton: false,
+ buttons: {
+ cancel: {
+ label: __t('Cancel'),
+ className: 'btn-secondary responsive-button',
+ callback: function()
+ {
+ bootbox.hideAll();
+ }
+ }
+ }
+ });
+ });
+
+ $("#recipe-include-add-button").on("click", function(e)
+ {
+ Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(),
+ function(result)
+ {
+ $("#recipe-include-editform-title").text(__t("Add included recipe"));
+ $("#recipe-include-form").data("edit-mode", "create");
+ Grocy.Components.RecipePicker.Clear();
+ Grocy.Components.RecipePicker.GetInputElement().focus();
+ $("#recipe-include-editform-modal").modal("show");
+ Grocy.FrontendHelpers.ValidateForm("recipe-include-form");
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ });
+
+ $('#save-recipe-include-button').on('click', function(e)
+ {
+ e.preventDefault();
+
+ if ($(".combobox-menu-visible").length)
+ {
+ return;
+ }
+
+ if (document.getElementById("recipe-include-form").checkValidity() === false) //There is at least one validation error
+ {
+ return false;
+ }
+
+ var nestingId = $("#recipe-include-form").data("recipe-nesting-id");
+ var editMode = $("#recipe-include-form").data("edit-mode");
+
+ var jsonData = {};
+ jsonData.includes_recipe_id = Grocy.Components.RecipePicker.GetValue();
+ jsonData.servings = $("#includes_servings").val();
+ jsonData.recipe_id = Grocy.EditObjectId;
+
+ if (editMode === 'create')
+ {
+ Grocy.Api.Post('objects/recipes_nestings', jsonData,
+ function(result)
+ {
+ window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
+ }
+ else
+ {
+ Grocy.Api.Put('objects/recipes_nestings/' + nestingId, jsonData,
+ function(result)
+ {
+ window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
+ }
+ });
+
+ $("#recipe-picture").on("change", function(e)
+ {
+ $("#recipe-picture-label").removeClass("d-none");
+ $("#recipe-picture-label-none").addClass("d-none");
+ $("#delete-current-recipe-picture-on-save-hint").addClass("d-none");
+ $("#current-recipe-picture").addClass("d-none");
+ Grocy.DeleteRecipePictureOnSave = false;
+ });
+
+ Grocy.DeleteRecipePictureOnSave = false;
+ $("#delete-current-recipe-picture-button").on("click", function(e)
+ {
+ Grocy.DeleteRecipePictureOnSave = true;
+ $("#current-recipe-picture").addClass("d-none");
+ $("#delete-current-recipe-picture-on-save-hint").removeClass("d-none");
+ $("#recipe-picture-label").addClass("d-none");
+ $("#recipe-picture-label-none").removeClass("d-none");
+ });
+
+ Grocy.Components.UserfieldsForm.Load();
+
+ $(window).on("message", function(e)
+ {
+ var data = e.originalEvent.data;
+
+ if (data.Message === "IngredientsChanged")
+ {
+ Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(),
+ function(result)
+ {
+ window.location.href = U('/recipe/' + Grocy.EditObjectId);
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ }
+ });
+
+}
diff --git a/js/viewjs/recipeposform.js b/js/viewjs/recipeposform.js
index 67edb759..53e67555 100644
--- a/js/viewjs/recipeposform.js
+++ b/js/viewjs/recipeposform.js
@@ -1,170 +1,180 @@
-import { WindowMessageBag } from '../helpers/messagebag';
-
-Grocy.Use("numberpicker");
-Grocy.Use("productamountpicker");
-Grocy.Use("productcard");
-
-Grocy.RecipePosFormInitialLoadDone = false;
-
-$('#save-recipe-pos-button').on('click', function(e)
+function recipeposformView(Grocy, scope = null)
{
- e.preventDefault();
-
- if ($(".combobox-menu-visible").length)
+ var $scope = $;
+ if (scope != null)
{
- return;
+ $scope = $(scope).find;
}
- var jsonData = $('#recipe-pos-form').serializeJSON();
- jsonData.recipe_id = Grocy.EditObjectParentId;
- delete jsonData.display_amount;
-
- Grocy.FrontendHelpers.BeginUiBusy("recipe-pos-form");
-
- if (Grocy.EditMode === 'create')
+ import { WindowMessageBag } from '../helpers/messagebag';
+
+ Grocy.Use("numberpicker");
+ Grocy.Use("productamountpicker");
+ Grocy.Use("productcard");
+
+ Grocy.RecipePosFormInitialLoadDone = false;
+
+ $('#save-recipe-pos-button').on('click', function(e)
{
- Grocy.Api.Post('objects/recipes_pos', jsonData,
- function(result)
- {
- window.parent.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
- window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy("recipe-pos-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
- else
- {
- Grocy.Api.Put('objects/recipes_pos/' + Grocy.EditObjectId, jsonData,
- function(result)
- {
- window.parent.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
- window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy("recipe-pos-form");
- Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
- }
- );
- }
-});
-
-Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
-{
- var productId = $(e.target).val();
-
- if (productId)
- {
- Grocy.Components.ProductCard.Refresh(productId);
-
- Grocy.Api.Get('stock/products/' + productId,
- function(productDetails)
- {
- if (!Grocy.RecipePosFormInitialLoadDone)
- {
- Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id, true);
- }
- else
- {
- Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
- }
-
- if (Grocy.Mode == "create")
- {
- $("#not_check_stock_fulfillment").prop("checked", productDetails.product.not_check_stock_fulfillment_for_recipes == 1);
- }
-
- if (!$("#only_check_single_unit_in_stock").prop("checked") && Grocy.RecipePosFormInitialLoadDone)
- {
- Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.quantity_unit_stock.id);
- }
-
- $('#display_amount').focus();
- Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
- Grocy.RecipePosFormInitialLoadDone = true;
- },
- function(xhr)
- {
- console.error(xhr);
- }
- );
- }
-});
-
-Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
-
-if (Grocy.Components.ProductPicker.InProductAddWorkflow() === false)
-{
- Grocy.Components.ProductPicker.GetInputElement().focus();
-}
-Grocy.Components.ProductPicker.GetPicker().trigger('change');
-
-if (Grocy.EditMode == "create")
-{
- Grocy.RecipePosFormInitialLoadDone = true;
-}
-
-$('#display_amount').on('focus', function(e)
-{
- if (Grocy.Components.ProductPicker.GetValue().length === 0)
- {
- Grocy.Components.ProductPicker.GetInputElement().focus();
- }
- else
- {
- $(this).select();
- }
-});
-
-$('#recipe-pos-form input').keyup(function(event)
-{
- Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
-});
-
-$('#qu_id').change(function(event)
-{
- Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
-});
-
-$('#recipe-pos-form input').keydown(function(event)
-{
- if (event.keyCode === 13) //Enter
- {
- event.preventDefault();
-
- if (document.getElementById('recipe-pos-form').checkValidity() === false) //There is at least one validation error
+ e.preventDefault();
+
+ if ($(".combobox-menu-visible").length)
{
- return false;
+ return;
+ }
+
+ var jsonData = $('#recipe-pos-form').serializeJSON();
+ jsonData.recipe_id = Grocy.EditObjectParentId;
+ delete jsonData.display_amount;
+
+ Grocy.FrontendHelpers.BeginUiBusy("recipe-pos-form");
+
+ if (Grocy.EditMode === 'create')
+ {
+ Grocy.Api.Post('objects/recipes_pos', jsonData,
+ function(result)
+ {
+ window.parent.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
+ window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy("recipe-pos-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
}
else
{
- $('#save-recipe-pos-button').click();
+ Grocy.Api.Put('objects/recipes_pos/' + Grocy.EditObjectId, jsonData,
+ function(result)
+ {
+ window.parent.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
+ window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy("recipe-pos-form");
+ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
+ }
+ );
}
- }
-});
-
-$("#only_check_single_unit_in_stock").on("change", function()
-{
- if (this.checked)
+ });
+
+ Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
+ {
+ var productId = $(e.target).val();
+
+ if (productId)
+ {
+ Grocy.Components.ProductCard.Refresh(productId);
+
+ Grocy.Api.Get('stock/products/' + productId,
+ function(productDetails)
+ {
+ if (!Grocy.RecipePosFormInitialLoadDone)
+ {
+ Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id, true);
+ }
+ else
+ {
+ Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
+ }
+
+ if (Grocy.Mode == "create")
+ {
+ $("#not_check_stock_fulfillment").prop("checked", productDetails.product.not_check_stock_fulfillment_for_recipes == 1);
+ }
+
+ if (!$("#only_check_single_unit_in_stock").prop("checked") && Grocy.RecipePosFormInitialLoadDone)
+ {
+ Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.quantity_unit_stock.id);
+ }
+
+ $('#display_amount').focus();
+ Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
+ Grocy.RecipePosFormInitialLoadDone = true;
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ }
+ });
+
+ Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
+
+ if (Grocy.Components.ProductPicker.InProductAddWorkflow() === false)
+ {
+ Grocy.Components.ProductPicker.GetInputElement().focus();
+ }
+ Grocy.Components.ProductPicker.GetPicker().trigger('change');
+
+ if (Grocy.EditMode == "create")
+ {
+ Grocy.RecipePosFormInitialLoadDone = true;
+ }
+
+ $('#display_amount').on('focus', function(e)
+ {
+ if (Grocy.Components.ProductPicker.GetValue().length === 0)
+ {
+ Grocy.Components.ProductPicker.GetInputElement().focus();
+ }
+ else
+ {
+ $(this).select();
+ }
+ });
+
+ $('#recipe-pos-form input').keyup(function(event)
+ {
+ Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
+ });
+
+ $('#qu_id').change(function(event)
+ {
+ Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
+ });
+
+ $('#recipe-pos-form input').keydown(function(event)
+ {
+ if (event.keyCode === 13) //Enter
+ {
+ event.preventDefault();
+
+ if (document.getElementById('recipe-pos-form').checkValidity() === false) //There is at least one validation error
+ {
+ return false;
+ }
+ else
+ {
+ $('#save-recipe-pos-button').click();
+ }
+ }
+ });
+
+ $("#only_check_single_unit_in_stock").on("change", function()
+ {
+ if (this.checked)
+ {
+ $("#display_amount").attr("min", Grocy.DefaultMinAmount);
+ Grocy.Components.ProductAmountPicker.AllowAnyQu(true);
+ Grocy.FrontendHelpers.ValidateForm("recipe-pos-form");
+ }
+ else
+ {
+ $("#display_amount").attr("min", "0");
+ Grocy.Components.ProductPicker.GetPicker().trigger("change"); // Selects the default quantity unit of the selected product
+ Grocy.Components.ProductAmountPicker.AllowAnyQuEnabled = false;
+ Grocy.FrontendHelpers.ValidateForm("recipe-pos-form");
+ }
+ });
+
+ if ($("#only_check_single_unit_in_stock").prop("checked"))
{
- $("#display_amount").attr("min", Grocy.DefaultMinAmount);
Grocy.Components.ProductAmountPicker.AllowAnyQu(true);
- Grocy.FrontendHelpers.ValidateForm("recipe-pos-form");
}
- else
- {
- $("#display_amount").attr("min", "0");
- Grocy.Components.ProductPicker.GetPicker().trigger("change"); // Selects the default quantity unit of the selected product
- Grocy.Components.ProductAmountPicker.AllowAnyQuEnabled = false;
- Grocy.FrontendHelpers.ValidateForm("recipe-pos-form");
- }
-});
-
-if ($("#only_check_single_unit_in_stock").prop("checked"))
-{
- Grocy.Components.ProductAmountPicker.AllowAnyQu(true);
+
}
diff --git a/js/viewjs/recipes.js b/js/viewjs/recipes.js
index 0abd9c66..ebd242d5 100644
--- a/js/viewjs/recipes.js
+++ b/js/viewjs/recipes.js
@@ -1,267 +1,277 @@
-Grocy.Use("numberpicker");
-
-var recipesTables = $('#recipes-table').DataTable({
- 'order': [[1, 'asc']],
- 'columnDefs': [
- { 'orderable': false, 'targets': 0 },
- { 'searchable': false, "targets": 0 },
- { "type": "html-num-fmt", "targets": 2 },
- ].concat($.fn.dataTable.defaults.columnDefs),
- select: {
- style: 'single',
- selector: 'tr td:not(:first-child)'
- },
- 'initComplete': function()
+function recipesView(Grocy, scope = null)
+{
+ var $scope = $;
+ if (scope != null)
{
- this.api().row({ order: 'current' }, 0).select();
+ $scope = $(scope).find;
}
-});
-$('#recipes-table tbody').removeClass("d-none");
-Grocy.FrontendHelpers.InitDataTable(recipesTables,
- function()
+
+ Grocy.Use("numberpicker");
+
+ var recipesTables = $('#recipes-table').DataTable({
+ 'order': [[1, 'asc']],
+ 'columnDefs': [
+ { 'orderable': false, 'targets': 0 },
+ { 'searchable': false, "targets": 0 },
+ { "type": "html-num-fmt", "targets": 2 },
+ ].concat($.fn.dataTable.defaults.columnDefs),
+ select: {
+ style: 'single',
+ selector: 'tr td:not(:first-child)'
+ },
+ 'initComplete': function()
+ {
+ this.api().row({ order: 'current' }, 0).select();
+ }
+ });
+ $('#recipes-table tbody').removeClass("d-none");
+ Grocy.FrontendHelpers.InitDataTable(recipesTables,
+ function()
+ {
+ var value = $(this).val();
+
+ recipesTables.search(value).draw();
+
+ $(".recipe-gallery-item").removeClass("d-none");
+
+ $(".recipe-gallery-item .card-title:not(:contains_case_insensitive(" + value + "))").parent().parent().parent().addClass("d-none");
+ },
+ function() // custom status filter below
+ {
+ $("#search").val("");
+ $("#status-filter").val("all");
+ $("#search").trigger("keyup");
+ $("#status-filter").trigger("change");
+ })
+
+ if ((typeof GetUriParam("tab") !== "undefined" && GetUriParam("tab") === "gallery") || window.localStorage.getItem("recipes_last_tab_id") == "gallery-tab")
+ {
+ $(".nav-tabs a[href='#gallery']").tab("show");
+ }
+
+ var recipe = GetUriParam("recipe");
+ if (typeof recipe !== "undefined")
+ {
+ $("#recipes-table tr").removeClass("selected");
+ var rowId = "#recipe-row-" + recipe;
+ $(rowId).addClass("selected")
+
+ var cardId = "#RecipeGalleryCard-" + recipe;
+ $(cardId).addClass("border-primary");
+
+ if ($(window).width() < 768)
+ {
+ // Scroll to recipe card on mobile
+ $("#selectedRecipeCard")[0].scrollIntoView();
+ }
+ }
+
+ if (GetUriParam("search") !== undefined)
+ {
+ $("#search").val(GetUriParam("search"));
+ setTimeout(function()
+ {
+ $("#search").keyup();
+ }, 50);
+ }
+
+ $("a[data-toggle='tab']").on("shown.bs.tab", function(e)
+ {
+ var tabId = $(e.target).attr("id");
+ window.localStorage.setItem("recipes_last_tab_id", tabId);
+ });
+
+ $("#status-filter").on("change", function()
{
var value = $(this).val();
-
- recipesTables.search(value).draw();
-
- $(".recipe-gallery-item").removeClass("d-none");
-
- $(".recipe-gallery-item .card-title:not(:contains_case_insensitive(" + value + "))").parent().parent().parent().addClass("d-none");
- },
- function() // custom status filter below
- {
- $("#search").val("");
- $("#status-filter").val("all");
- $("#search").trigger("keyup");
- $("#status-filter").trigger("change");
- })
-
-if ((typeof GetUriParam("tab") !== "undefined" && GetUriParam("tab") === "gallery") || window.localStorage.getItem("recipes_last_tab_id") == "gallery-tab")
-{
- $(".nav-tabs a[href='#gallery']").tab("show");
-}
-
-var recipe = GetUriParam("recipe");
-if (typeof recipe !== "undefined")
-{
- $("#recipes-table tr").removeClass("selected");
- var rowId = "#recipe-row-" + recipe;
- $(rowId).addClass("selected")
-
- var cardId = "#RecipeGalleryCard-" + recipe;
- $(cardId).addClass("border-primary");
-
- if ($(window).width() < 768)
- {
- // Scroll to recipe card on mobile
- $("#selectedRecipeCard")[0].scrollIntoView();
- }
-}
-
-if (GetUriParam("search") !== undefined)
-{
- $("#search").val(GetUriParam("search"));
- setTimeout(function()
- {
- $("#search").keyup();
- }, 50);
-}
-
-$("a[data-toggle='tab']").on("shown.bs.tab", function(e)
-{
- var tabId = $(e.target).attr("id");
- window.localStorage.setItem("recipes_last_tab_id", tabId);
-});
-
-$("#status-filter").on("change", function()
-{
- var value = $(this).val();
- if (value === "all")
- {
- value = "";
- }
-
- recipesTables.column(5).search(value).draw();
-
- $('.recipe-gallery-item').removeClass('d-none');
- if (value !== "")
- {
- if (value === 'Xenoughinstock')
+ if (value === "all")
{
- $('.recipe-gallery-item').not('.recipe-enoughinstock').addClass('d-none');
+ value = "";
}
- else if (value === 'enoughinstockwithshoppinglist')
+
+ recipesTables.column(5).search(value).draw();
+
+ $('.recipe-gallery-item').removeClass('d-none');
+ if (value !== "")
{
- $('.recipe-gallery-item').not('.recipe-enoughinstockwithshoppinglist').addClass('d-none');
- }
- if (value === 'notenoughinstock')
- {
- $('.recipe-gallery-item').not('.recipe-notenoughinstock').addClass('d-none');
- }
- }
-});
-
-Grocy.FrontendHelpers.MakeDeleteConfirmBox(
- 'Are you sure to delete recipe "%s"?',
- '.recipe-delete',
- 'data-recipe-name',
- 'data-recipe-id',
- 'objects/recipes/',
- '/recipes'
-);
-
-Grocy.FrontendHelpers.MakeYesNoBox(
- (e) =>
- {
- var objectName = $(e.currentTarget).attr('data-recipe-name');
- return __t('Are you sure to put all missing ingredients for recipe "%s" on the shopping list?', objectName) +
- "
" +
- __t("Uncheck ingredients to not put them on the shopping list") +
- ":" +
- $("#missing-recipe-pos-list")[0].outerHTML.replace("d-none", "");
- },
- '.recipe-shopping-list',
- (result, e) =>
- {
- var objectId = $(e.currentTarget).attr('data-recipe-id');
- if (result === true)
- {
- Grocy.FrontendHelpers.BeginUiBusy();
-
- var excludedProductIds = new Array();
- $(".missing-recipe-pos-product-checkbox:checkbox:not(:checked)").each(function()
+ if (value === 'Xenoughinstock')
{
- excludedProductIds.push($(this).data("product-id"));
- });
-
- Grocy.Api.Post('recipes/' + objectId + '/add-not-fulfilled-products-to-shoppinglist', { "excludedProductIds": excludedProductIds },
- function(result)
- {
- window.location.href = U('/recipes');
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy();
- console.error(xhr);
- }
- );
+ $('.recipe-gallery-item').not('.recipe-enoughinstock').addClass('d-none');
+ }
+ else if (value === 'enoughinstockwithshoppinglist')
+ {
+ $('.recipe-gallery-item').not('.recipe-enoughinstockwithshoppinglist').addClass('d-none');
+ }
+ if (value === 'notenoughinstock')
+ {
+ $('.recipe-gallery-item').not('.recipe-notenoughinstock').addClass('d-none');
+ }
}
- }
-);
-
-Grocy.FrontendHelpers.MakeYesNoBox(
- (e) =>
- {
- var objectName = $(e.currentTarget).attr('data-recipe-name');
- return __t('Are you sure to consume all ingredients needed by recipe "%s" (ingredients marked with "only check if any amount is in stock" will be ignored)?', objectName);
- },
- '.recipe-consume',
- (result, e) =>
- {
- var target = $(e.currentTarget);
- var objectName = target.attr('data-recipe-name');
- var objectId = target.attr('data-recipe-id');
- if (result === true)
+ });
+
+ Grocy.FrontendHelpers.MakeDeleteConfirmBox(
+ 'Are you sure to delete recipe "%s"?',
+ '.recipe-delete',
+ 'data-recipe-name',
+ 'data-recipe-id',
+ 'objects/recipes/',
+ '/recipes'
+ );
+
+ Grocy.FrontendHelpers.MakeYesNoBox(
+ (e) =>
{
- Grocy.FrontendHelpers.BeginUiBusy();
-
- Grocy.Api.Post('recipes/' + objectId + '/consume', {},
- function(result)
- {
- Grocy.FrontendHelpers.EndUiBusy();
- toastr.success(__t('Removed all ingredients of recipe "%s" from stock', objectName));
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy();
- toastr.warning(__t('Not all ingredients of recipe "%s" are in stock, nothing removed', objectName));
- console.error(xhr);
- }
- );
- }
- }
-);
-
-recipesTables.on('select', function(e, dt, type, indexes)
-{
- if (type === 'row')
- {
- var selectedRecipeId = $(recipesTables.row(indexes[0]).node()).data("recipe-id");
- var currentRecipeId = window.location.search.split('recipe=')[1];
- if (selectedRecipeId.toString() !== currentRecipeId)
- {
- window.location.href = U('/recipes?recipe=' + selectedRecipeId.toString());
- }
- }
-});
-
-$(".recipe-gallery-item").on("click", function(e)
-{
- e.preventDefault();
-
- window.location.href = U('/recipes?tab=gallery&recipe=' + $(this).data("recipe-id"));
-});
-
-$(".recipe-fullscreen").on('click', function(e)
-{
- e.preventDefault();
-
- $("#selectedRecipeCard").toggleClass("fullscreen");
- $("body").toggleClass("fullscreen-card");
- $("#selectedRecipeCard .card-header").toggleClass("fixed-top");
- $("#selectedRecipeCard .card-body").toggleClass("mt-5");
-
- if ($("body").hasClass("fullscreen-card"))
- {
- window.location.hash = "#fullscreen";
- }
- else
- {
- window.history.replaceState(null, null, " ");
- }
-});
-
-$(".recipe-print").on('click', function(e)
-{
- e.preventDefault();
-
- $("#selectedRecipeCard").removeClass("fullscreen");
- $("body").removeClass("fullscreen-card");
- $("#selectedRecipeCard .card-header").removeClass("fixed-top");
- $("#selectedRecipeCard .card-body").removeClass("mt-5");
-
- window.history.replaceState(null, null, " ");
- window.print();
-});
-
-$('#servings-scale').keyup(function(event)
-{
- var data = {};
- data.desired_servings = $(this).val();
-
- Grocy.Api.Put('objects/recipes/' + $(this).data("recipe-id"), data,
- function(result)
- {
- window.location.reload();
+ var objectName = $(e.currentTarget).attr('data-recipe-name');
+ return __t('Are you sure to put all missing ingredients for recipe "%s" on the shopping list?', objectName) +
+ "
" +
+ __t("Uncheck ingredients to not put them on the shopping list") +
+ ":" +
+ $("#missing-recipe-pos-list")[0].outerHTML.replace("d-none", "");
},
- function(xhr)
+ '.recipe-shopping-list',
+ (result, e) =>
{
- console.error(xhr);
+ var objectId = $(e.currentTarget).attr('data-recipe-id');
+ if (result === true)
+ {
+ Grocy.FrontendHelpers.BeginUiBusy();
+
+ var excludedProductIds = new Array();
+ $(".missing-recipe-pos-product-checkbox:checkbox:not(:checked)").each(function()
+ {
+ excludedProductIds.push($(this).data("product-id"));
+ });
+
+ Grocy.Api.Post('recipes/' + objectId + '/add-not-fulfilled-products-to-shoppinglist', { "excludedProductIds": excludedProductIds },
+ function(result)
+ {
+ window.location.href = U('/recipes');
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy();
+ console.error(xhr);
+ }
+ );
+ }
}
);
-});
-
-$(document).on("click", ".missing-recipe-pos-select-button", function(e)
-{
- e.preventDefault();
-
- var checkbox = $(this).find(".form-check-input");
- checkbox.prop("checked", !checkbox.prop("checked"));
-
- $(this).toggleClass("list-group-item-primary");
-});
-
-if (window.location.hash === "#fullscreen")
-{
- $("#selectedRecipeToggleFullscreenButton").click();
+
+ Grocy.FrontendHelpers.MakeYesNoBox(
+ (e) =>
+ {
+ var objectName = $(e.currentTarget).attr('data-recipe-name');
+ return __t('Are you sure to consume all ingredients needed by recipe "%s" (ingredients marked with "only check if any amount is in stock" will be ignored)?', objectName);
+ },
+ '.recipe-consume',
+ (result, e) =>
+ {
+ var target = $(e.currentTarget);
+ var objectName = target.attr('data-recipe-name');
+ var objectId = target.attr('data-recipe-id');
+ if (result === true)
+ {
+ Grocy.FrontendHelpers.BeginUiBusy();
+
+ Grocy.Api.Post('recipes/' + objectId + '/consume', {},
+ function(result)
+ {
+ Grocy.FrontendHelpers.EndUiBusy();
+ toastr.success(__t('Removed all ingredients of recipe "%s" from stock', objectName));
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy();
+ toastr.warning(__t('Not all ingredients of recipe "%s" are in stock, nothing removed', objectName));
+ console.error(xhr);
+ }
+ );
+ }
+ }
+ );
+
+ recipesTables.on('select', function(e, dt, type, indexes)
+ {
+ if (type === 'row')
+ {
+ var selectedRecipeId = $(recipesTables.row(indexes[0]).node()).data("recipe-id");
+ var currentRecipeId = window.location.search.split('recipe=')[1];
+ if (selectedRecipeId.toString() !== currentRecipeId)
+ {
+ window.location.href = U('/recipes?recipe=' + selectedRecipeId.toString());
+ }
+ }
+ });
+
+ $(".recipe-gallery-item").on("click", function(e)
+ {
+ e.preventDefault();
+
+ window.location.href = U('/recipes?tab=gallery&recipe=' + $(this).data("recipe-id"));
+ });
+
+ $(".recipe-fullscreen").on('click', function(e)
+ {
+ e.preventDefault();
+
+ $("#selectedRecipeCard").toggleClass("fullscreen");
+ $("body").toggleClass("fullscreen-card");
+ $("#selectedRecipeCard .card-header").toggleClass("fixed-top");
+ $("#selectedRecipeCard .card-body").toggleClass("mt-5");
+
+ if ($("body").hasClass("fullscreen-card"))
+ {
+ window.location.hash = "#fullscreen";
+ }
+ else
+ {
+ window.history.replaceState(null, null, " ");
+ }
+ });
+
+ $(".recipe-print").on('click', function(e)
+ {
+ e.preventDefault();
+
+ $("#selectedRecipeCard").removeClass("fullscreen");
+ $("body").removeClass("fullscreen-card");
+ $("#selectedRecipeCard .card-header").removeClass("fixed-top");
+ $("#selectedRecipeCard .card-body").removeClass("mt-5");
+
+ window.history.replaceState(null, null, " ");
+ window.print();
+ });
+
+ $('#servings-scale').keyup(function(event)
+ {
+ var data = {};
+ data.desired_servings = $(this).val();
+
+ Grocy.Api.Put('objects/recipes/' + $(this).data("recipe-id"), data,
+ function(result)
+ {
+ window.location.reload();
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ });
+
+ $(document).on("click", ".missing-recipe-pos-select-button", function(e)
+ {
+ e.preventDefault();
+
+ var checkbox = $(this).find(".form-check-input");
+ checkbox.prop("checked", !checkbox.prop("checked"));
+
+ $(this).toggleClass("list-group-item-primary");
+ });
+
+ if (window.location.hash === "#fullscreen")
+ {
+ $("#selectedRecipeToggleFullscreenButton").click();
+ }
+
}
diff --git a/js/viewjs/recipessettings.js b/js/viewjs/recipessettings.js
index f28e88d7..435d78c6 100644
--- a/js/viewjs/recipessettings.js
+++ b/js/viewjs/recipessettings.js
@@ -1,8 +1,18 @@
-import { BoolVal } from '../helpers/extensions';
-
-if (BoolVal(Grocy.UserSettings.recipe_ingredients_group_by_product_group))
+function recipessettingsView(Grocy, scope = null)
{
- $("#recipe_ingredients_group_by_product_group").prop("checked", true);
-}
+ var $scope = $;
+ if (scope != null)
+ {
+ $scope = $(scope).find;
+ }
-RefreshLocaleNumberInput();
+ import { BoolVal } from '../helpers/extensions';
+
+ if (BoolVal(Grocy.UserSettings.recipe_ingredients_group_by_product_group))
+ {
+ $("#recipe_ingredients_group_by_product_group").prop("checked", true);
+ }
+
+ RefreshLocaleNumberInput();
+
+}
diff --git a/js/viewjs/shoppinglist.js b/js/viewjs/shoppinglist.js
index 43251b5b..d0f67acb 100644
--- a/js/viewjs/shoppinglist.js
+++ b/js/viewjs/shoppinglist.js
@@ -1,545 +1,555 @@
-// this needs to be explicitly imported for some reason,
-// otherwise rollup complains.
-import bwipjs from '../../node_modules/bwip-js/dist/bwip-js.mjs';
-import { WindowMessageBag } from '../helpers/messagebag';
-
-Grocy.Use("calendarcard");
-Grocy.Use("productcard");
-
-var shoppingListTable = $('#shoppinglist-table').DataTable({
- 'order': [[1, 'asc']],
- "orderFixed": [[3, 'asc']],
- 'columnDefs': [
- { 'orderable': false, 'targets': 0 },
- { 'searchable': false, "targets": 0 },
- { 'visible': false, 'targets': 3 },
- { 'visible': false, 'targets': 5 },
- { 'visible': false, 'targets': 6 },
- { 'visible': false, 'targets': 7 },
- { 'visible': false, 'targets': 8 },
- { "type": "num", "targets": 2 },
- { "type": "html-num-fmt", "targets": 5 },
- { "type": "html-num-fmt", "targets": 6 }
- ].concat($.fn.dataTable.defaults.columnDefs),
- 'rowGroup': {
- enable: true,
- dataSrc: 3
- }
-});
-$('#shoppinglist-table tbody').removeClass("d-none");
-Grocy.FrontendHelpers.InitDataTable(shoppingListTable);
-Grocy.FrontendHelpers.MakeStatusFilter(shoppingListTable, 4);
-
-var shoppingListPrintShadowTable = $('#shopping-list-print-shadow-table').DataTable({
- 'order': [[1, 'asc']],
- "orderFixed": [[2, 'asc']],
- 'columnDefs': [
- { 'visible': false, 'targets': 2 },
- { 'orderable': false, 'targets': '_all' }
- ].concat($.fn.dataTable.defaults.columnDefs),
- 'rowGroup': {
- enable: true,
- dataSrc: 2
- }
-});
-Grocy.FrontendHelpers.InitDataTable(shoppingListPrintShadowTable);
-
-
-$("#selected-shopping-list").on("change", function()
+function shoppinglistView(Grocy, scope = null)
{
- var value = $(this).val();
- window.location.href = U('/shoppinglist?list=' + value);
-});
+ var $scope = $;
+ if (scope != null)
+ {
+ $scope = $(scope).find;
+ }
-Grocy.FrontendHelpers.MakeDeleteConfirmBox(
- 'Are you sure to delete shopping list "%s"?',
- '#delete-selected-shopping-list',
- () => $("#selected-shopping-list option:selected").text(),
- () => $("#selected-shopping-list").val(),
- 'objects/shopping_lists/',
- '/shoppinglist'
-);
-
-$(document).on('click', '.shoppinglist-delete-button', function(e)
-{
- e.preventDefault();
-
- // Remove the focus from the current button
- // to prevent that the tooltip stays until clicked anywhere else
- document.activeElement.blur();
-
- var shoppingListItemId = $(e.currentTarget).attr('data-shoppinglist-id');
- Grocy.FrontendHelpers.BeginUiBusy();
-
- Grocy.Api.Delete('objects/shopping_list/' + shoppingListItemId, {},
- function(result)
- {
- animateCSS("#shoppinglistitem-" + shoppingListItemId + "-row", "fadeOut", function()
+ // this needs to be explicitly imported for some reason,
+ // otherwise rollup complains.
+ import bwipjs from '../../node_modules/bwip-js/dist/bwip-js.mjs';
+ import { WindowMessageBag } from '../helpers/messagebag';
+
+ Grocy.Use("calendarcard");
+ Grocy.Use("productcard");
+
+ var shoppingListTable = $('#shoppinglist-table').DataTable({
+ 'order': [[1, 'asc']],
+ "orderFixed": [[3, 'asc']],
+ 'columnDefs': [
+ { 'orderable': false, 'targets': 0 },
+ { 'searchable': false, "targets": 0 },
+ { 'visible': false, 'targets': 3 },
+ { 'visible': false, 'targets': 5 },
+ { 'visible': false, 'targets': 6 },
+ { 'visible': false, 'targets': 7 },
+ { 'visible': false, 'targets': 8 },
+ { "type": "num", "targets": 2 },
+ { "type": "html-num-fmt", "targets": 5 },
+ { "type": "html-num-fmt", "targets": 6 }
+ ].concat($.fn.dataTable.defaults.columnDefs),
+ 'rowGroup': {
+ enable: true,
+ dataSrc: 3
+ }
+ });
+ $('#shoppinglist-table tbody').removeClass("d-none");
+ Grocy.FrontendHelpers.InitDataTable(shoppingListTable);
+ Grocy.FrontendHelpers.MakeStatusFilter(shoppingListTable, 4);
+
+ var shoppingListPrintShadowTable = $('#shopping-list-print-shadow-table').DataTable({
+ 'order': [[1, 'asc']],
+ "orderFixed": [[2, 'asc']],
+ 'columnDefs': [
+ { 'visible': false, 'targets': 2 },
+ { 'orderable': false, 'targets': '_all' }
+ ].concat($.fn.dataTable.defaults.columnDefs),
+ 'rowGroup': {
+ enable: true,
+ dataSrc: 2
+ }
+ });
+ Grocy.FrontendHelpers.InitDataTable(shoppingListPrintShadowTable);
+
+
+ $("#selected-shopping-list").on("change", function()
+ {
+ var value = $(this).val();
+ window.location.href = U('/shoppinglist?list=' + value);
+ });
+
+ Grocy.FrontendHelpers.MakeDeleteConfirmBox(
+ 'Are you sure to delete shopping list "%s"?',
+ '#delete-selected-shopping-list',
+ () => $("#selected-shopping-list option:selected").text(),
+ () => $("#selected-shopping-list").val(),
+ 'objects/shopping_lists/',
+ '/shoppinglist'
+ );
+
+ $(document).on('click', '.shoppinglist-delete-button', function(e)
+ {
+ e.preventDefault();
+
+ // Remove the focus from the current button
+ // to prevent that the tooltip stays until clicked anywhere else
+ document.activeElement.blur();
+
+ var shoppingListItemId = $(e.currentTarget).attr('data-shoppinglist-id');
+ Grocy.FrontendHelpers.BeginUiBusy();
+
+ Grocy.Api.Delete('objects/shopping_list/' + shoppingListItemId, {},
+ function(result)
{
- Grocy.FrontendHelpers.EndUiBusy();
- $("#shoppinglistitem-" + shoppingListItemId + "-row").remove();
- OnListItemRemoved();
- });
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy();
- console.error(xhr);
- }
- );
-});
-
-$(document).on("click", ".product-name-cell", function(e)
-{
- if ($(e.currentTarget).attr("data-product-id") != "")
- {
- Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-product-id"));
- $("#shoppinglist-productcard-modal").modal("show");
- }
-});
-
-$(document).on('click', '#add-products-below-min-stock-amount', function(e)
-{
- Grocy.Api.Post('stock/shoppinglist/add-missing-products', { "list_id": $("#selected-shopping-list").val() },
- function(result)
- {
- window.location.href = U('/shoppinglist?list=' + $("#selected-shopping-list").val());
- },
- function(xhr)
- {
- console.error(xhr);
- }
- );
-});
-
-$(document).on('click', '#add-overdue-expired-products', function(e)
-{
- Grocy.Api.Post('stock/shoppinglist/add-overdue-products', { "list_id": $("#selected-shopping-list").val() },
- function(result)
- {
- Grocy.Api.Post('stock/shoppinglist/add-expired-products', { "list_id": $("#selected-shopping-list").val() },
- function(result)
- {
- window.location.href = U('/shoppinglist?list=' + $("#selected-shopping-list").val());
- },
- function(xhr)
- {
- console.error(xhr);
- }
- );
- },
- function(xhr)
- {
- console.error(xhr);
- }
- );
-});
-
-Grocy.FrontendHelpers.MakeYesNoBox(
- () => __t('Are you sure to empty shopping list "%s"?', $("#selected-shopping-list option:selected").text()),
- '#clear-shopping-list',
- (result) =>
- {
- if (result === true)
- {
- Grocy.FrontendHelpers.BeginUiBusy();
-
- Grocy.Api.Post('stock/shoppinglist/clear', { "list_id": $("#selected-shopping-list").val() },
- function(result)
- {
- animateCSS("#shoppinglist-table tbody tr", "fadeOut", function()
- {
- Grocy.FrontendHelpers.EndUiBusy();
- $("#shoppinglist-table tbody tr").remove();
- OnListItemRemoved();
- });
- },
- function(xhr)
+ animateCSS("#shoppinglistitem-" + shoppingListItemId + "-row", "fadeOut", function()
{
Grocy.FrontendHelpers.EndUiBusy();
- console.error(xhr);
- }
- );
- }
- }
-);
-
-$(document).on('click', '.shopping-list-stock-add-workflow-list-item-button', function(e)
-{
- e.preventDefault();
-
- // Remove the focus from the current button
- // to prevent that the tooltip stays until clicked anywhere else
- document.activeElement.blur();
-
- var href = $(e.currentTarget).attr('href');
-
- $("#shopping-list-stock-add-workflow-purchase-form-frame").attr("src", href);
- $("#shopping-list-stock-add-workflow-modal").modal("show");
-
- if (Grocy.ShoppingListToStockWorkflowAll)
+ $("#shoppinglistitem-" + shoppingListItemId + "-row").remove();
+ OnListItemRemoved();
+ });
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy();
+ console.error(xhr);
+ }
+ );
+ });
+
+ $(document).on("click", ".product-name-cell", function(e)
{
- $("#shopping-list-stock-add-workflow-purchase-item-count").removeClass("d-none");
- $("#shopping-list-stock-add-workflow-purchase-item-count").text(__t("Adding shopping list item %1$s of %2$s", Grocy.ShoppingListToStockWorkflowCurrent, Grocy.ShoppingListToStockWorkflowCount));
- $("#shopping-list-stock-add-workflow-skip-button").removeClass("d-none");
- }
- else
- {
- $("#shopping-list-stock-add-workflow-skip-button").addClass("d-none");
- }
-});
-
-Grocy.ShoppingListToStockWorkflowAll = false;
-Grocy.ShoppingListToStockWorkflowCount = 0;
-Grocy.ShoppingListToStockWorkflowCurrent = 0;
-$(document).on('click', '#add-all-items-to-stock-button', function(e)
-{
- Grocy.ShoppingListToStockWorkflowAll = true;
- Grocy.ShoppingListToStockWorkflowCount = $(".shopping-list-stock-add-workflow-list-item-button").length;
- Grocy.ShoppingListToStockWorkflowCurrent++;
- $(".shopping-list-stock-add-workflow-list-item-button").first().click();
-});
-
-$("#shopping-list-stock-add-workflow-modal").on("hidden.bs.modal", function(e)
-{
- Grocy.ShoppingListToStockWorkflowAll = false;
- Grocy.ShoppingListToStockWorkflowCount = 0;
- Grocy.ShoppingListToStockWorkflowCurrent = 0;
-})
-
-$(window).on("message", function(e)
-{
- var data = e.originalEvent.data;
-
- if (data.Message === "AfterItemAdded")
- {
- $(".shoppinglist-delete-button[data-shoppinglist-id='" + data.Payload + "']").click();
- }
- else if (data.Message === "Ready")
- {
- if (!Grocy.ShoppingListToStockWorkflowAll)
+ if ($(e.currentTarget).attr("data-product-id") != "")
{
- $("#shopping-list-stock-add-workflow-modal").modal("hide");
+ Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-product-id"));
+ $("#shoppinglist-productcard-modal").modal("show");
+ }
+ });
+
+ $(document).on('click', '#add-products-below-min-stock-amount', function(e)
+ {
+ Grocy.Api.Post('stock/shoppinglist/add-missing-products', { "list_id": $("#selected-shopping-list").val() },
+ function(result)
+ {
+ window.location.href = U('/shoppinglist?list=' + $("#selected-shopping-list").val());
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ });
+
+ $(document).on('click', '#add-overdue-expired-products', function(e)
+ {
+ Grocy.Api.Post('stock/shoppinglist/add-overdue-products', { "list_id": $("#selected-shopping-list").val() },
+ function(result)
+ {
+ Grocy.Api.Post('stock/shoppinglist/add-expired-products', { "list_id": $("#selected-shopping-list").val() },
+ function(result)
+ {
+ window.location.href = U('/shoppinglist?list=' + $("#selected-shopping-list").val());
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ },
+ function(xhr)
+ {
+ console.error(xhr);
+ }
+ );
+ });
+
+ Grocy.FrontendHelpers.MakeYesNoBox(
+ () => __t('Are you sure to empty shopping list "%s"?', $("#selected-shopping-list option:selected").text()),
+ '#clear-shopping-list',
+ (result) =>
+ {
+ if (result === true)
+ {
+ Grocy.FrontendHelpers.BeginUiBusy();
+
+ Grocy.Api.Post('stock/shoppinglist/clear', { "list_id": $("#selected-shopping-list").val() },
+ function(result)
+ {
+ animateCSS("#shoppinglist-table tbody tr", "fadeOut", function()
+ {
+ Grocy.FrontendHelpers.EndUiBusy();
+ $("#shoppinglist-table tbody tr").remove();
+ OnListItemRemoved();
+ });
+ },
+ function(xhr)
+ {
+ Grocy.FrontendHelpers.EndUiBusy();
+ console.error(xhr);
+ }
+ );
+ }
+ }
+ );
+
+ $(document).on('click', '.shopping-list-stock-add-workflow-list-item-button', function(e)
+ {
+ e.preventDefault();
+
+ // Remove the focus from the current button
+ // to prevent that the tooltip stays until clicked anywhere else
+ document.activeElement.blur();
+
+ var href = $(e.currentTarget).attr('href');
+
+ $("#shopping-list-stock-add-workflow-purchase-form-frame").attr("src", href);
+ $("#shopping-list-stock-add-workflow-modal").modal("show");
+
+ if (Grocy.ShoppingListToStockWorkflowAll)
+ {
+ $("#shopping-list-stock-add-workflow-purchase-item-count").removeClass("d-none");
+ $("#shopping-list-stock-add-workflow-purchase-item-count").text(__t("Adding shopping list item %1$s of %2$s", Grocy.ShoppingListToStockWorkflowCurrent, Grocy.ShoppingListToStockWorkflowCount));
+ $("#shopping-list-stock-add-workflow-skip-button").removeClass("d-none");
}
else
{
- Grocy.ShoppingListToStockWorkflowCurrent++;
- if (Grocy.ShoppingListToStockWorkflowCurrent <= Grocy.ShoppingListToStockWorkflowCount)
- {
- $(".shopping-list-stock-add-workflow-list-item-button")[Grocy.ShoppingListToStockWorkflowCurrent - 1].click();
- }
- else
+ $("#shopping-list-stock-add-workflow-skip-button").addClass("d-none");
+ }
+ });
+
+ Grocy.ShoppingListToStockWorkflowAll = false;
+ Grocy.ShoppingListToStockWorkflowCount = 0;
+ Grocy.ShoppingListToStockWorkflowCurrent = 0;
+ $(document).on('click', '#add-all-items-to-stock-button', function(e)
+ {
+ Grocy.ShoppingListToStockWorkflowAll = true;
+ Grocy.ShoppingListToStockWorkflowCount = $(".shopping-list-stock-add-workflow-list-item-button").length;
+ Grocy.ShoppingListToStockWorkflowCurrent++;
+ $(".shopping-list-stock-add-workflow-list-item-button").first().click();
+ });
+
+ $("#shopping-list-stock-add-workflow-modal").on("hidden.bs.modal", function(e)
+ {
+ Grocy.ShoppingListToStockWorkflowAll = false;
+ Grocy.ShoppingListToStockWorkflowCount = 0;
+ Grocy.ShoppingListToStockWorkflowCurrent = 0;
+ })
+
+ $(window).on("message", function(e)
+ {
+ var data = e.originalEvent.data;
+
+ if (data.Message === "AfterItemAdded")
+ {
+ $(".shoppinglist-delete-button[data-shoppinglist-id='" + data.Payload + "']").click();
+ }
+ else if (data.Message === "Ready")
+ {
+ if (!Grocy.ShoppingListToStockWorkflowAll)
{
$("#shopping-list-stock-add-workflow-modal").modal("hide");
}
- }
- }
-});
-
-$(document).on('click', '#shopping-list-stock-add-workflow-skip-button', function(e)
-{
- e.preventDefault();
-
- window.postMessage(WindowMessageBag("Ready"), Grocy.BaseUrl);
-});
-
-$(document).on('click', '.order-listitem-button', function(e)
-{
- e.preventDefault();
-
- // Remove the focus from the current button
- // to prevent that the tooltip stays until clicked anywhere else
- document.activeElement.blur();
-
- Grocy.FrontendHelpers.BeginUiBusy();
-
- var listItemId = $(e.currentTarget).attr('data-item-id');
-
- var done = 1;
- if ($(e.currentTarget).attr('data-item-done') == 1)
- {
- done = 0;
- }
-
- $(e.currentTarget).attr('data-item-done', done);
-
- Grocy.Api.Put('objects/shopping_list/' + listItemId, { 'done': done },
- function()
- {
- if (done == 1)
- {
- $('#shoppinglistitem-' + listItemId + '-row').addClass("text-muted");
- $('#shoppinglistitem-' + listItemId + '-row').addClass("text-strike-through");
- }
else
{
- $('#shoppinglistitem-' + listItemId + '-row').removeClass("text-muted");
- $('#shoppinglistitem-' + listItemId + '-row').removeClass("text-strike-through");
- }
-
- Grocy.FrontendHelpers.EndUiBusy();
- },
- function(xhr)
- {
- Grocy.FrontendHelpers.EndUiBusy();
- console.error(xhr);
- }
- );
-
-
- var statusInfoCell = $("#shoppinglistitem-" + listItemId + "-status-info");
- if (done == 1)
- {
- statusInfoCell.text(statusInfoCell.text().replace("xxUNDONExx", ""));
- }
- else
- {
- statusInfoCell.text(statusInfoCell.text() + " xxUNDONExx");
- }
- shoppingListTable.rows().invalidate().draw(false);
-
- $("#status-filter").trigger("change");
-});
-
-function OnListItemRemoved()
-{
- if ($(".shopping-list-stock-add-workflow-list-item-button").length === 0)
- {
- $("#add-all-items-to-stock-button").addClass("disabled");
- }
-}
-OnListItemRemoved();
-
-$(document).on("click", "#print-shopping-list-button", function(e)
-{
- var dialogHtml = ' \
-
' + __t('Print options') + '
\
- \
- \
- \
-
\
- \
- \
- \
-
\
- ' + __t('Layout type') + '
\
- \
- \
- \
-
\
- \
- \
- \
-
';
-
- var sizePrintDialog = 'medium';
- var printButtons = {
- cancel: {
- label: __t('Cancel'),
- className: 'btn-secondary',
- callback: function()
- {
- bootbox.hideAll();
- }
- },
- printtp: {
- label: __t('Thermal printer'),
- className: 'btn-secondary',
- callback: function()
- {
- bootbox.hideAll();
- var printHeader = $("#print-show-header").prop("checked");
- var thermalPrintDialog = bootbox.dialog({
- title: __t('Printing'),
- message: '