viewjs: scoped jquery

Most instances of $ have been replaced by $scope.
This commit is contained in:
Katharina Bogad 2021-06-23 15:00:53 +02:00
parent fd61d1ef62
commit 2fbcefa8fd
67 changed files with 2646 additions and 2603 deletions

View File

@ -6,7 +6,7 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
$('[data-toggle="collapse-next"]').on("click", function(e) $scope('[data-toggle="collapse-next"]').on("click", function(e)
{ {
e.preventDefault(); e.preventDefault();
$(this).parent().next().collapse("toggle"); $(this).parent().next().collapse("toggle");
@ -14,7 +14,7 @@
if ((typeof GetUriParam("tab") !== "undefined" && GetUriParam("tab") === "changelog")) if ((typeof GetUriParam("tab") !== "undefined" && GetUriParam("tab") === "changelog"))
{ {
$(".nav-tabs a[href='#changelog']").tab("show"); $scope(".nav-tabs a[href='#changelog']").tab("show");
} }
} }

View File

@ -10,50 +10,50 @@
Grocy.BarCodeScannerTestingHitCount = 0; Grocy.BarCodeScannerTestingHitCount = 0;
Grocy.BarCodeScannerTestingMissCount = 0; Grocy.BarCodeScannerTestingMissCount = 0;
$("#scanned_barcode").on("blur", function(e) $scope("#scanned_barcode").on("blur", function(e)
{ {
OnBarcodeScanned($("#scanned_barcode").val()); OnBarcodeScanned($scope("#scanned_barcode").val());
}); });
$("#scanned_barcode").keydown(function(event) $scope("#scanned_barcode").keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
event.preventDefault(); event.preventDefault();
OnBarcodeScanned($("#scanned_barcode").val()); OnBarcodeScanned($scope("#scanned_barcode").val());
} }
}); });
$("#expected_barcode").on("keyup", function(e) $scope("#expected_barcode").on("keyup", function(e)
{ {
if ($("#expected_barcode").val().length > 1) if ($scope("#expected_barcode").val().length > 1)
{ {
$("#scanned_barcode").removeAttr("disabled"); $scope("#scanned_barcode").removeAttr("disabled");
$("#barcodescanner-start-button").removeAttr("disabled"); $scope("#barcodescanner-start-button").removeAttr("disabled");
$("#barcodescanner-start-button").removeClass("disabled"); $scope("#barcodescanner-start-button").removeClass("disabled");
} }
else else
{ {
$("#scanned_barcode").attr("disabled", ""); $scope("#scanned_barcode").attr("disabled", "");
$("#barcodescanner-start-button").attr("disabled", ""); $scope("#barcodescanner-start-button").attr("disabled", "");
$("#barcodescanner-start-button").addClass("disabled"); $scope("#barcodescanner-start-button").addClass("disabled");
} }
}); });
$("#expected_barcode").focus(); $scope("#expected_barcode").focus();
setTimeout(function() setTimeout(function()
{ {
$("#barcodescanner-start-button").attr("disabled", ""); $scope("#barcodescanner-start-button").attr("disabled", "");
$("#barcodescanner-start-button").addClass("disabled"); $scope("#barcodescanner-start-button").addClass("disabled");
}, 200); }, 200);
if (GetUriParam("barcode") !== undefined) if (GetUriParam("barcode") !== undefined)
{ {
$("#expected_barcode").val(GetUriParam("barcode")); $scope("#expected_barcode").val(GetUriParam("barcode"));
setTimeout(function() setTimeout(function()
{ {
$("#expected_barcode").keyup(); $scope("#expected_barcode").keyup();
$("#scanned_barcode").focus(); $scope("#scanned_barcode").focus();
}, 200); }, 200);
} }
@ -65,12 +65,12 @@
} }
var bgClass = ""; var bgClass = "";
if (barcode != $("#expected_barcode").val()) if (barcode != $scope("#expected_barcode").val())
{ {
Grocy.BarCodeScannerTestingMissCount++; Grocy.BarCodeScannerTestingMissCount++;
bgClass = "bg-danger"; bgClass = "bg-danger";
$("#miss-count").text(Grocy.BarCodeScannerTestingMissCount); $scope("#miss-count").text(Grocy.BarCodeScannerTestingMissCount);
animateCSS("#miss-count", "pulse"); animateCSS("#miss-count", "pulse");
} }
else else
@ -78,18 +78,18 @@
Grocy.BarCodeScannerTestingHitCount++; Grocy.BarCodeScannerTestingHitCount++;
bgClass = "bg-success"; bgClass = "bg-success";
$("#hit-count").text(Grocy.BarCodeScannerTestingHitCount); $scope("#hit-count").text(Grocy.BarCodeScannerTestingHitCount);
animateCSS("#hit-count", "pulse"); animateCSS("#hit-count", "pulse");
} }
$("#scanned_codes").prepend("<option class='" + bgClass + "'>" + barcode + "</option>"); $scope("#scanned_codes").prepend("<option class='" + bgClass + "'>" + barcode + "</option>");
setTimeout(function() setTimeout(function()
{ {
$("#scanned_barcode").val(""); $("#scanned_barcode").val("");
if (!$(":focus").is($("#expected_barcode"))) if (!$scope(":focus").is($scope("#expected_barcode")))
{ {
$("#scanned_barcode").focus(); $scope("#scanned_barcode").focus();
} }
}, 200); }, 200);
} }

View File

@ -6,7 +6,7 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var batteriesTable = $('#batteries-table').DataTable({ var batteriesTable = $scope('#batteries-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
@ -14,12 +14,12 @@
{ "type": "num", "targets": 4 } { "type": "num", "targets": 4 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#batteries-table tbody').removeClass("d-none"); $scope('#batteries-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(batteriesTable, null, function() Grocy.FrontendHelpers.InitDataTable(batteriesTable, null, function()
{ {
$("#search").val(""); $scope("#search").val("");
batteriesTable.search("").draw(); batteriesTable.search("").draw();
$("#show-disabled").prop('checked', false); $scope("#show-disabled").prop('checked', false);
}); });
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
@ -31,7 +31,7 @@
'/batteries' '/batteries'
); );
$("#show-disabled").change(function() $scope("#show-disabled").change(function()
{ {
if (this.checked) if (this.checked)
{ {
@ -45,7 +45,7 @@
if (GetUriParam('include_disabled')) if (GetUriParam('include_disabled'))
{ {
$("#show-disabled").prop('checked', true); $scope("#show-disabled").prop('checked', true);
} }
} }

View File

@ -6,7 +6,7 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var batteriesJournalTable = $('#batteries-journal-table').DataTable({ var batteriesJournalTable = $scope('#batteries-journal-table').DataTable({
'paginate': true, 'paginate': true,
'order': [[2, 'desc']], 'order': [[2, 'desc']],
'columnDefs': [ 'columnDefs': [
@ -14,17 +14,19 @@
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#batteries-journal-table tbody').removeClass("d-none"); $scope('#batteries-journal-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(batteriesJournalTable); Grocy.FrontendHelpers.InitDataTable(batteriesJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#battery-filter", 1, batteriesJournalTable); Grocy.FrontendHelpers.MakeFilterForColumn("#battery-filter", 1, batteriesJournalTable);
if (typeof GetUriParam("battery") !== "undefined") if (typeof GetUriParam("battery") !== "undefined")
{ {
$("#battery-filter").val(GetUriParam("battery")); $scope("#battery-filter").val(GetUriParam("battery"));
$("#battery-filter").trigger("change"); $scope("#battery-filter").trigger("change");
} }
$(document).on('click', '.undo-battery-execution-button', function(e) var top = scope != null ? $(scope) : $(document);
top.on('click', '.undo-battery-execution-button', function(e)
{ {
e.preventDefault(); e.preventDefault();

View File

@ -6,9 +6,9 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
Grocy.Use("batterycard"); Grocy.Use("batterycard", scope);
var batteriesOverviewTable = $('#batteries-overview-table').DataTable({ var batteriesOverviewTable = $scope('#batteries-overview-table').DataTable({
'order': [[4, 'asc']], 'order': [[4, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
@ -17,12 +17,14 @@
{ "type": "html", "targets": 4 } { "type": "html", "targets": 4 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#batteries-overview-table tbody').removeClass("d-none"); $scope('#batteries-overview-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(batteriesOverviewTable); Grocy.FrontendHelpers.InitDataTable(batteriesOverviewTable);
Grocy.FrontendHelpers.MakeStatusFilter(batteriesOverviewTable, 5); Grocy.FrontendHelpers.MakeStatusFilter(batteriesOverviewTable, 5);
$(document).on('click', '.track-charge-cycle-button', function(e) var top = scope != null ? $(scope) : $(document);
top.on('click', '.track-charge-cycle-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -32,8 +34,8 @@
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
var batteryId = $(e.currentTarget).attr('data-battery-id'); var batteryId = $scope(e.currentTarget).attr('data-battery-id');
var batteryName = $(e.currentTarget).attr('data-battery-name'); var batteryName = $scope(e.currentTarget).attr('data-battery-name');
var trackedTime = moment().format('YYYY-MM-DD HH:mm:ss'); var trackedTime = moment().format('YYYY-MM-DD HH:mm:ss');
Grocy.Api.Post('batteries/' + batteryId + '/charge', { 'tracked_time': trackedTime }, Grocy.Api.Post('batteries/' + batteryId + '/charge', { 'tracked_time': trackedTime },
@ -42,7 +44,7 @@
Grocy.Api.Get('batteries/' + batteryId, Grocy.Api.Get('batteries/' + batteryId,
function(result) function(result)
{ {
var batteryRow = $('#battery-' + batteryId + '-row'); var batteryRow = $scope('#battery-' + batteryId + '-row');
var nextXDaysThreshold = moment().add($("#info-due-batteries").data("next-x-days"), "days"); var nextXDaysThreshold = moment().add($("#info-due-batteries").data("next-x-days"), "days");
var now = moment(); var now = moment();
var nextExecutionTime = moment(result.next_estimated_charge_time); var nextExecutionTime = moment(result.next_estimated_charge_time);
@ -60,12 +62,12 @@
animateCSS("#battery-" + batteryId + "-row td:not(:first)", "shake"); animateCSS("#battery-" + batteryId + "-row td:not(:first)", "shake");
$('#battery-' + batteryId + '-last-tracked-time').text(trackedTime); $scope('#battery-' + batteryId + '-last-tracked-time').text(trackedTime);
$('#battery-' + batteryId + '-last-tracked-time-timeago').attr('datetime', trackedTime); $scope('#battery-' + batteryId + '-last-tracked-time-timeago').attr('datetime', trackedTime);
if (result.battery.charge_interval_days != 0) if (result.battery.charge_interval_days != 0)
{ {
$('#battery-' + batteryId + '-next-charge-time').text(result.next_estimated_charge_time); $scope('#battery-' + batteryId + '-next-charge-time').text(result.next_estimated_charge_time);
$('#battery-' + batteryId + '-next-charge-time-timeago').attr('datetime', result.next_estimated_charge_time); $scope('#battery-' + batteryId + '-next-charge-time-timeago').attr('datetime', result.next_estimated_charge_time);
} }
Grocy.FrontendHelpers.EndUiBusy(); Grocy.FrontendHelpers.EndUiBusy();
@ -88,15 +90,17 @@
); );
}); });
$(document).on("click", ".battery-name-cell", function(e)
top.on("click", ".battery-name-cell", function(e)
{ {
Grocy.Components.BatteryCard.Refresh($(e.currentTarget).attr("data-battery-id")); Grocy.Components.BatteryCard.Refresh($scope(e.currentTarget).attr("data-battery-id"));
$("#batteriesoverview-batterycard-modal").modal("show"); $scope("#batteriesoverview-batterycard-modal").modal("show");
}); });
function RefreshStatistics() function RefreshStatistics()
{ {
var nextXDays = $("#info-due-batteries").data("next-x-days"); var nextXDays = $scope("#info-due-batteries").data("next-x-days");
Grocy.Api.Get('batteries', Grocy.Api.Get('batteries',
function(result) function(result)
{ {
@ -117,8 +121,8 @@
} }
}); });
$("#info-due-batteries").html('<span class="d-block d-md-none">' + dueCount + ' <i class="fas fa-clock"></i></span><span class="d-none d-md-block">' + __n(dueCount, '%s battery is due to be charged', '%s batteries are due to be charged') + ' ' + __n(nextXDays, 'within the next day', 'within the next %s days')); $scope("#info-due-batteries").html('<span class="d-block d-md-none">' + dueCount + ' <i class="fas fa-clock"></i></span><span class="d-none d-md-block">' + __n(dueCount, '%s battery is due to be charged', '%s batteries are due to be charged') + ' ' + __n(nextXDays, 'within the next day', 'within the next %s days'));
$("#info-overdue-batteries").html('<span class="d-block d-md-none">' + overdueCount + ' <i class="fas fa-times-circle"></i></span><span class="d-none d-md-block">' + __n(overdueCount, '%s battery is overdue to be charged', '%s batteries are overdue to be charged')); $scope("#info-overdue-batteries").html('<span class="d-block d-md-none">' + overdueCount + ' <i class="fas fa-times-circle"></i></span><span class="d-none d-md-block">' + __n(overdueCount, '%s battery is overdue to be charged', '%s batteries are overdue to be charged'));
}, },
function(xhr) function(xhr)
{ {

View File

@ -8,7 +8,7 @@
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
$("#batteries_due_soon_days").val(Grocy.UserSettings.batteries_due_soon_days); $scope("#batteries_due_soon_days").val(Grocy.UserSettings.batteries_due_soon_days);
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();

View File

@ -1,4 +1,6 @@
function batteryformView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function batteryformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,12 +8,10 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
$('#save-battery-button').on('click', function(e) $scope('#save-battery-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -20,7 +20,7 @@
return; return;
} }
var jsonData = $('#battery-form').serializeJSON(); var jsonData = $scope('#battery-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("battery-form"); Grocy.FrontendHelpers.BeginUiBusy("battery-form");
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
@ -74,12 +74,12 @@
} }
}); });
$('#battery-form input').keyup(function(event) $scope('#battery-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('battery-form'); Grocy.FrontendHelpers.ValidateForm('battery-form');
}); });
$('#battery-form input').keydown(function(event) $scope('#battery-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -97,7 +97,7 @@
}); });
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
$('#name').focus(); $scope('#name').focus();
Grocy.FrontendHelpers.ValidateForm('battery-form'); Grocy.FrontendHelpers.ValidateForm('battery-form');
} }

View File

@ -9,34 +9,34 @@
Grocy.Use("batterycard"); Grocy.Use("batterycard");
Grocy.Use("datetimepicker"); Grocy.Use("datetimepicker");
$('#save-batterytracking-button').on('click', function(e) $scope('#save-batterytracking-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonForm = $('#batterytracking-form').serializeJSON(); var jsonForm = $scope('#batterytracking-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("batterytracking-form"); Grocy.FrontendHelpers.BeginUiBusy("batterytracking-form");
Grocy.Api.Get('batteries/' + jsonForm.battery_id, Grocy.Api.Get('batteries/' + jsonForm.battery_id,
function(batteryDetails) function(batteryDetails)
{ {
Grocy.Api.Post('batteries/' + jsonForm.battery_id + '/charge', { 'tracked_time': $('#tracked_time').find('input').val() }, Grocy.Api.Post('batteries/' + jsonForm.battery_id + '/charge', { 'tracked_time': $scope('#tracked_time').find('input').val() },
function(result) function(result)
{ {
Grocy.FrontendHelpers.EndUiBusy("batterytracking-form"); Grocy.FrontendHelpers.EndUiBusy("batterytracking-form");
toastr.success(__t('Tracked charge cycle of battery %1$s on %2$s', batteryDetails.battery.name, $('#tracked_time').find('input').val()) + '<br><a class="btn btn-secondary btn-sm mt-2" href="#" onclick="Grocy.UndoChargeCycle(' + result.id + ')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>'); toastr.success(__t('Tracked charge cycle of battery %1$s on %2$s', batteryDetails.battery.name, $scope('#tracked_time').find('input').val()) + '<br><a class="btn btn-secondary btn-sm mt-2" href="#" onclick="Grocy.UndoChargeCycle(' + result.id + ')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>');
Grocy.Components.BatteryCard.Refresh($('#battery_id').val()); Grocy.Components.BatteryCard.Refresh($('#battery_id').val());
$('#battery_id').val(''); $scope('#battery_id').val('');
$('#battery_id_text_input').focus(); $scope('#battery_id_text_input').focus();
$('#battery_id_text_input').val(''); $scope('#battery_id_text_input').val('');
$('#tracked_time').find('input').val(moment().format('YYYY-MM-DD HH:mm:ss')); $scope('#tracked_time').find('input').val(moment().format('YYYY-MM-DD HH:mm:ss'));
$('#tracked_time').find('input').trigger('change'); $scope('#tracked_time').find('input').trigger('change');
$('#battery_id_text_input').trigger('change'); $scope('#battery_id_text_input').trigger('change');
Grocy.FrontendHelpers.ValidateForm('batterytracking-form'); Grocy.FrontendHelpers.ValidateForm('batterytracking-form');
}, },
function(xhr) function(xhr)
@ -54,39 +54,39 @@
); );
}); });
$('#battery_id').on('change', function(e) $scope('#battery_id').on('change', function(e)
{ {
var input = $('#battery_id_text_input').val().toString(); var input = $scope('#battery_id_text_input').val().toString();
$('#battery_id_text_input').val(input); $scope('#battery_id_text_input').val(input);
$('#battery_id').data('combobox').refresh(); $scope('#battery_id').data('combobox').refresh();
var batteryId = $(e.target).val(); var batteryId = $scope(e.target).val();
if (batteryId) if (batteryId)
{ {
Grocy.Components.BatteryCard.Refresh(batteryId); Grocy.Components.BatteryCard.Refresh(batteryId);
$('#tracked_time').find('input').focus(); $scope('#tracked_time').find('input').focus();
Grocy.FrontendHelpers.ValidateForm('batterytracking-form'); Grocy.FrontendHelpers.ValidateForm('batterytracking-form');
} }
}); });
$('.combobox').combobox({ $scope('.combobox').combobox({
appendId: '_text_input', appendId: '_text_input',
bsVersion: '4' bsVersion: '4'
}); });
$('#battery_id').val(''); $scope('#battery_id').val('');
$('#battery_id_text_input').focus(); $scope('#battery_id_text_input').focus();
$('#battery_id_text_input').val(''); $scope('#battery_id_text_input').val('');
$('#battery_id_text_input').trigger('change'); $scope('#battery_id_text_input').trigger('change');
Grocy.Components.DateTimePicker.GetInputElement().trigger('input'); Grocy.Components.DateTimePicker.GetInputElement().trigger('input');
Grocy.FrontendHelpers.ValidateForm('batterytracking-form'); Grocy.FrontendHelpers.ValidateForm('batterytracking-form');
$('#batterytracking-form input').keyup(function(event) $scope('#batterytracking-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('batterytracking-form'); Grocy.FrontendHelpers.ValidateForm('batterytracking-form');
}); });
$('#batterytracking-form input').keydown(function(event) $scope('#batterytracking-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -98,16 +98,13 @@
} }
else else
{ {
$('#save-batterytracking-button').click(); $scope('#save-batterytracking-button').click();
} }
} }
}); });
$('#tracked_time').find('input').on('keypress', function(e) $scope('#tracked_time').find('input').on('keypress', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('batterytracking-form'); Grocy.FrontendHelpers.ValidateForm('batterytracking-form');
}); });
} }

View File

@ -1,11 +1,4 @@
function calendarView(Grocy, scope = null) 
{
var $scope = $;
if (scope != null)
{
$scope = $(scope).find;
}
/* global fullcalendarEventSources */ /* global fullcalendarEventSources */
import { Calendar } from '@fullcalendar/core'; import { Calendar } from '@fullcalendar/core';
@ -21,6 +14,17 @@
import '@fullcalendar/list/main.css'; import '@fullcalendar/list/main.css';
import '@fullcalendar/bootstrap/main.css'; import '@fullcalendar/bootstrap/main.css';
function calendarView(Grocy, scope = null)
{
var $scope = $;
var $viewport = $(window);
if (scope != null)
{
$scope = $(scope).find;
$viewport = $(scope);
}
var calendarOptions = { var calendarOptions = {
plugins: [bootstrapPlugin, dayGridPlugin, listPlugin, timeGridPlugin], plugins: [bootstrapPlugin, dayGridPlugin, listPlugin, timeGridPlugin],
themeSystem: "bootstrap", themeSystem: "bootstrap",
@ -30,7 +34,7 @@
right: "prev,next" right: "prev,next"
}, },
weekNumbers: Grocy.CalendarShowWeekNumbers, weekNumbers: Grocy.CalendarShowWeekNumbers,
defaultView: ($(window).width() < 768) ? "timeGridDay" : "dayGridMonth", defaultView: ($viewport.width() < 768) ? "timeGridDay" : "dayGridMonth",
firstDay: firstDay, firstDay: firstDay,
eventLimit: false, eventLimit: false,
height: "auto", height: "auto",
@ -64,7 +68,7 @@
var calendar = new Calendar(document.getElementById("calendar"), calendarOptions); var calendar = new Calendar(document.getElementById("calendar"), calendarOptions);
calendar.render(); calendar.render();
$("#ical-button").on("click", function(e) $scope("#ical-button").on("click", function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -89,7 +93,7 @@
{ {
// Automatically switch the calendar to "basicDay" view on small screens // Automatically switch the calendar to "basicDay" view on small screens
// and to "month" otherwise // and to "month" otherwise
if ($(window).width() < 768) if ($viewport.width() < 768)
{ {
calendar.changeView("timeGridDay"); calendar.changeView("timeGridDay");
} }
@ -100,3 +104,5 @@
}); });
} }
window.calendarView = calendarView;

View File

@ -9,19 +9,19 @@
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
$('#save-chore-button').on('click', function(e) $scope('#save-chore-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#chore-form').serializeJSON(); var jsonData = $scope('#chore-form').serializeJSON();
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_CHORES_ASSIGNMENTS) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_CHORES_ASSIGNMENTS)
{ {
jsonData.assignment_config = $("#assignment_config").val().join(","); jsonData.assignment_config = $scope("#assignment_config").val().join(",");
} }
Grocy.FrontendHelpers.BeginUiBusy("chore-form"); Grocy.FrontendHelpers.BeginUiBusy("chore-form");
@ -100,131 +100,131 @@
} }
else else
{ {
$('#save-chore-button').click(); $scope('#save-chore-button').click();
} }
} }
}); });
var checkboxValues = $("#period_config").val().split(","); var checkboxValues = $scope("#period_config").val().split(",");
for (var i = 0; i < checkboxValues.length; i++) for (var i = 0; i < checkboxValues.length; i++)
{ {
if (!checkboxValues[i].isEmpty()) if (!checkboxValues[i].isEmpty())
{ {
$("#" + checkboxValues[i]).prop('checked', true); $scope("#" + checkboxValues[i]).prop('checked', true);
} }
} }
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
$('#name').focus(); $scope('#name').focus();
Grocy.FrontendHelpers.ValidateForm('chore-form'); Grocy.FrontendHelpers.ValidateForm('chore-form');
setTimeout(function() setTimeout(function()
{ {
$(".input-group-chore-period-type").trigger("change"); $scope(".input-group-chore-period-type").trigger("change");
$(".input-group-chore-assignment-type").trigger("change"); $scope(".input-group-chore-assignment-type").trigger("change");
// Click twice to trigger on-click but not change the actual checked state // Click twice to trigger on-click but not change the actual checked state
$("#consume_product_on_execution").click(); $scope("#consume_product_on_execution").click();
$("#consume_product_on_execution").click(); $scope("#consume_product_on_execution").click();
Grocy.Components.ProductPicker.GetPicker().trigger('change'); Grocy.Components.ProductPicker.GetPicker().trigger('change');
}, 100); }, 100);
$('.input-group-chore-period-type').on('change', function(e) $scope('.input-group-chore-period-type').on('change', function(e)
{ {
var periodType = $('#period_type').val(); var periodType = $scope('#period_type').val();
var periodDays = $('#period_days').val(); var periodDays = $scope('#period_days').val();
var periodInterval = $('#period_interval').val(); var periodInterval = $scope('#period_interval').val();
$(".period-type-input").addClass("d-none"); $scope(".period-type-input").addClass("d-none");
$(".period-type-" + periodType).removeClass("d-none"); $scope(".period-type-" + periodType).removeClass("d-none");
$('#chore-period-type-info').attr("data-original-title", ""); $scope('#chore-period-type-info').attr("data-original-title", "");
$("#period_config").val(""); $scope("#period_config").val("");
if (periodType === 'manually') if (periodType === 'manually')
{ {
$('#chore-period-type-info').attr("data-original-title", __t('This means the next execution of this chore is not scheduled')); $scope('#chore-period-type-info').attr("data-original-title", __t('This means the next execution of this chore is not scheduled'));
} }
else if (periodType === 'dynamic-regular') else if (periodType === 'dynamic-regular')
{ {
$("label[for='period_days']").text(__t("Period days")); $scope("label[for='period_days']").text(__t("Period days"));
$("#period_days").attr("min", "0"); $scope("#period_days").attr("min", "0");
$("#period_days").removeAttr("max"); $scope("#period_days").removeAttr("max");
$('#chore-period-type-info').attr("data-original-title", __t('This means the next execution of this chore is scheduled %s days after the last execution', periodDays.toString())); $scope('#chore-period-type-info').attr("data-original-title", __t('This means the next execution of this chore is scheduled %s days after the last execution', periodDays.toString()));
} }
else if (periodType === 'daily') else if (periodType === 'daily')
{ {
$('#chore-period-type-info').attr("data-original-title", __t('This means the next execution of this chore is scheduled 1 day after the last execution')); $scope('#chore-period-type-info').attr("data-original-title", __t('This means the next execution of this chore is scheduled 1 day after the last execution'));
$('#chore-period-interval-info').attr("data-original-title", __t('This means the next execution of this chore should only be scheduled every %s days', periodInterval.toString())); $scope('#chore-period-interval-info').attr("data-original-title", __t('This means the next execution of this chore should only be scheduled every %s days', periodInterval.toString()));
} }
else if (periodType === 'weekly') else if (periodType === 'weekly')
{ {
$('#chore-period-type-info').attr("data-original-title", __t('This means the next execution of this chore is scheduled 1 day after the last execution, but only for the weekdays selected below')); $scope('#chore-period-type-info').attr("data-original-title", __t('This means the next execution of this chore is scheduled 1 day after the last execution, but only for the weekdays selected below'));
$("#period_config").val($(".period-type-weekly input:checkbox:checked").map(function() { return this.value; }).get().join(",")); $scope("#period_config").val($(".period-type-weekly input:checkbox:checked").map(function() { return this.value; }).get().join(","));
$('#chore-period-interval-info').attr("data-original-title", __t('This means the next execution of this chore should only be scheduled every %s weeks', periodInterval.toString())); $scope('#chore-period-interval-info').attr("data-original-title", __t('This means the next execution of this chore should only be scheduled every %s weeks', periodInterval.toString()));
} }
else if (periodType === 'monthly') else if (periodType === 'monthly')
{ {
$('#chore-period-type-info').attr("data-original-title", __t('This means the next execution of this chore is scheduled on the below selected day of each month')); $scope('#chore-period-type-info').attr("data-original-title", __t('This means the next execution of this chore is scheduled on the below selected day of each month'));
$("label[for='period_days']").text(__t("Day of month")); $scope("label[for='period_days']").text(__t("Day of month"));
$("#period_days").attr("min", "1"); $scope("#period_days").attr("min", "1");
$("#period_days").attr("max", "31"); $scope("#period_days").attr("max", "31");
$('#chore-period-interval-info').attr("data-original-title", __t('This means the next execution of this chore should only be scheduled every %s months', periodInterval.toString())); $scope('#chore-period-interval-info').attr("data-original-title", __t('This means the next execution of this chore should only be scheduled every %s months', periodInterval.toString()));
} }
else if (periodType === 'yearly') else if (periodType === 'yearly')
{ {
$('#chore-period-type-info').attr("data-original-title", __t('This means the next execution of this chore is scheduled 1 year after the last execution')); $scope('#chore-period-type-info').attr("data-original-title", __t('This means the next execution of this chore is scheduled 1 year after the last execution'));
$('#chore-period-interval-info').attr("data-original-title", __t('This means the next execution of this chore should only be scheduled every %s years', periodInterval.toString())); $scope('#chore-period-interval-info').attr("data-original-title", __t('This means the next execution of this chore should only be scheduled every %s years', periodInterval.toString()));
} }
Grocy.FrontendHelpers.ValidateForm('chore-form'); Grocy.FrontendHelpers.ValidateForm('chore-form');
}); });
$('.input-group-chore-assignment-type').on('change', function(e) $scope('.input-group-chore-assignment-type').on('change', function(e)
{ {
var assignmentType = $('#assignment_type').val(); var assignmentType = $scope('#assignment_type').val();
$('#chore-period-assignment-info').text(""); $scope('#chore-period-assignment-info').text("");
$("#assignment_config").removeAttr("required"); $scope("#assignment_config").removeAttr("required");
$("#assignment_config").attr("disabled", ""); $scope("#assignment_config").attr("disabled", "");
if (assignmentType === 'no-assignment') if (assignmentType === 'no-assignment')
{ {
$('#chore-assignment-type-info').attr("data-original-title", __t('This means the next execution of this chore will not be assigned to anyone')); $scope('#chore-assignment-type-info').attr("data-original-title", __t('This means the next execution of this chore will not be assigned to anyone'));
} }
else if (assignmentType === 'who-least-did-first') else if (assignmentType === 'who-least-did-first')
{ {
$('#chore-assignment-type-info').attr("data-original-title", __t('This means the next execution of this chore will be assigned to the one who executed it least')); $scope('#chore-assignment-type-info').attr("data-original-title", __t('This means the next execution of this chore will be assigned to the one who executed it least'));
$("#assignment_config").attr("required", ""); $scope("#assignment_config").attr("required", "");
$("#assignment_config").removeAttr("disabled"); $scope("#assignment_config").removeAttr("disabled");
} }
else if (assignmentType === 'random') else if (assignmentType === 'random')
{ {
$('#chore-assignment-type-info').attr("data-original-title", __t('This means the next execution of this chore will be assigned randomly')); $scope('#chore-assignment-type-info').attr("data-original-title", __t('This means the next execution of this chore will be assigned randomly'));
$("#assignment_config").attr("required", ""); $scope("#assignment_config").attr("required", "");
$("#assignment_config").removeAttr("disabled"); $scope("#assignment_config").removeAttr("disabled");
} }
else if (assignmentType === 'in-alphabetical-order') else if (assignmentType === 'in-alphabetical-order')
{ {
$('#chore-assignment-type-info').attr("data-original-title", __t('This means the next execution of this chore will be assigned to the next one in alphabetical order')); $scope('#chore-assignment-type-info').attr("data-original-title", __t('This means the next execution of this chore will be assigned to the next one in alphabetical order'));
$("#assignment_config").attr("required", ""); $scope("#assignment_config").attr("required", "");
$("#assignment_config").removeAttr("disabled"); $scope("#assignment_config").removeAttr("disabled");
} }
Grocy.FrontendHelpers.ValidateForm('chore-form'); Grocy.FrontendHelpers.ValidateForm('chore-form', $scope);
}); });
$("#consume_product_on_execution").on("click", function() $scope("#consume_product_on_execution").on("click", function()
{ {
if (this.checked) if (this.checked)
{ {
Grocy.Components.ProductPicker.Enable(); Grocy.Components.ProductPicker.Enable();
$("#product_amount").removeAttr("disabled"); $scope("#product_amount").removeAttr("disabled");
} }
else else
{ {
Grocy.Components.ProductPicker.Disable(); Grocy.Components.ProductPicker.Disable();
$("#product_amount").attr("disabled", ""); $scope("#product_amount").attr("disabled", "");
} }
Grocy.FrontendHelpers.ValidateForm("chore-form"); Grocy.FrontendHelpers.ValidateForm("chore-form");
@ -232,14 +232,14 @@
Grocy.Components.ProductPicker.GetPicker().on('change', function(e) Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{ {
var productId = $(e.target).val(); var productId = $scope(e.target).val();
if (productId) if (productId)
{ {
Grocy.Api.Get('stock/products/' + productId, Grocy.Api.Get('stock/products/' + productId,
function(productDetails) function(productDetails)
{ {
$('#amount_qu_unit').text(productDetails.quantity_unit_stock.name); $scope('#amount_qu_unit').text(productDetails.quantity_unit_stock.name);
}, },
function(xhr) function(xhr)
{ {

View File

@ -6,19 +6,19 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var choresTable = $('#chores-table').DataTable({ var choresTable = $scope('#chores-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#chores-table tbody').removeClass("d-none"); $scope('#chores-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(choresTable, null, function() Grocy.FrontendHelpers.InitDataTable(choresTable, null, function()
{ {
$("#search").val(""); $scope("#search").val("");
choresTable.search("").draw(); choresTable.search("").draw();
$("#show-disabled").prop('checked', false); $scope("#show-disabled").prop('checked', false);
}); });
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
@ -44,7 +44,7 @@
if (GetUriParam('include_disabled')) if (GetUriParam('include_disabled'))
{ {
$("#show-disabled").prop('checked', true); $scope("#show-disabled").prop('checked', true);
} }
} }

View File

@ -6,7 +6,7 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var choresJournalTable = $('#chores-journal-table').DataTable({ var choresJournalTable = $scope('#chores-journal-table').DataTable({
'paginate': true, 'paginate': true,
'order': [[2, 'desc']], 'order': [[2, 'desc']],
'columnDefs': [ 'columnDefs': [
@ -14,21 +14,23 @@
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#chores-journal-table tbody').removeClass("d-none"); $scope('#chores-journal-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(choresJournalTable); Grocy.FrontendHelpers.InitDataTable(choresJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#chore-filter", 1, choresJournalTable); Grocy.FrontendHelpers.MakeFilterForColumn("#chore-filter", 1, choresJournalTable);
if (typeof GetUriParam("chore") !== "undefined") if (typeof GetUriParam("chore") !== "undefined")
{ {
$("#chore-filter").val(GetUriParam("chore")); $scope("#chore-filter").val(GetUriParam("chore"));
$("#chore-filter").trigger("change"); $scope("#chore-filter").trigger("change");
} }
$(document).on('click', '.undo-chore-execution-button', function(e) var top = scope != null ? $(scope) : $(document);
top.on('click', '.undo-chore-execution-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
var element = $(e.currentTarget); var element = $scope(e.currentTarget);
var executionId = element.attr('data-execution-id'); var executionId = element.attr('data-execution-id');
Grocy.Api.Post('chores/executions/' + executionId.toString() + '/undo', {}, Grocy.Api.Post('chores/executions/' + executionId.toString() + '/undo', {},

View File

@ -1,6 +1,8 @@
function choresoverviewView(Grocy, scope = null) function choresoverviewView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
var top = scope != null ? $(scope) : $(document);
if (scope != null) if (scope != null)
{ {
$scope = $(scope).find; $scope = $(scope).find;
@ -8,7 +10,7 @@
Grocy.Use("chorecard"); Grocy.Use("chorecard");
var choresOverviewTable = $('#chores-overview-table').DataTable({ var choresOverviewTable = $scope('#chores-overview-table').DataTable({
'order': [[2, 'asc']], 'order': [[2, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
@ -18,17 +20,17 @@
{ "type": "html", "targets": 3 } { "type": "html", "targets": 3 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#chores-overview-table tbody').removeClass("d-none"); $scope('#chores-overview-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(choresOverviewTable); Grocy.FrontendHelpers.InitDataTable(choresOverviewTable);
Grocy.FrontendHelpers.MakeValueFilter("status", 5, choresOverviewTable); Grocy.FrontendHelpers.MakeValueFilter("status", 5, choresOverviewTable);
Grocy.FrontendHelpers.MakeValueFilter("user", 6, choresOverviewTable, ""); Grocy.FrontendHelpers.MakeValueFilter("user", 6, choresOverviewTable, "");
$("#user-filter").on("change", function() $scope("#user-filter").on("change", function()
{ {
var user = $(this).val(); var user = $(this).val();
if (user !== null && !user.isEmpty()) if (user !== null && !user.isEmpty())
{ {
UpdateUriParam("user", $("#user-filter option:selected").data("user-id")); UpdateUriParam("user", $scope("#user-filter option:selected").data("user-id"));
} }
else else
{ {
@ -36,7 +38,7 @@
} }
}); });
$(document).on('click', '.track-chore-button', function(e) top.on('click', '.track-chore-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -46,8 +48,8 @@
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
var choreId = $(e.currentTarget).attr('data-chore-id'); var choreId = $scope(e.currentTarget).attr('data-chore-id');
var choreName = $(e.currentTarget).attr('data-chore-name'); var choreName = $scope(e.currentTarget).attr('data-chore-name');
Grocy.Api.Get('objects/chores/' + choreId, Grocy.Api.Get('objects/chores/' + choreId,
function(chore) function(chore)
@ -64,39 +66,39 @@
Grocy.Api.Get('chores/' + choreId, Grocy.Api.Get('chores/' + choreId,
function(result) function(result)
{ {
var choreRow = $('#chore-' + choreId + '-row'); var choreRow = $scope('#chore-' + choreId + '-row');
var nextXDaysThreshold = moment().add($("#info-due-chores").data("next-x-days"), "days"); var nextXDaysThreshold = moment().add($scope("#info-due-chores").data("next-x-days"), "days");
var now = moment(); var now = moment();
var nextExecutionTime = moment(result.next_estimated_execution_time); var nextExecutionTime = moment(result.next_estimated_execution_time);
choreRow.removeClass("table-warning"); choreRow.removeClass("table-warning");
choreRow.removeClass("table-danger"); choreRow.removeClass("table-danger");
$('#chore-' + choreId + '-due-filter-column').html(""); $scope('#chore-' + choreId + '-due-filter-column').html("");
if (nextExecutionTime.isBefore(now)) if (nextExecutionTime.isBefore(now))
{ {
choreRow.addClass("table-danger"); choreRow.addClass("table-danger");
$('#chore-' + choreId + '-due-filter-column').html("overdue"); $scope('#chore-' + choreId + '-due-filter-column').html("overdue");
} }
else if (nextExecutionTime.isBefore(nextXDaysThreshold)) else if (nextExecutionTime.isBefore(nextXDaysThreshold))
{ {
choreRow.addClass("table-warning"); choreRow.addClass("table-warning");
$('#chore-' + choreId + '-due-filter-column').html("duesoon"); $scope('#chore-' + choreId + '-due-filter-column').html("duesoon");
} }
animateCSS("#chore-" + choreId + "-row td:not(:first)", "shake"); animateCSS("#chore-" + choreId + "-row td:not(:first)", "shake");
$('#chore-' + choreId + '-last-tracked-time').text(trackedTime); $scope('#chore-' + choreId + '-last-tracked-time').text(trackedTime);
$('#chore-' + choreId + '-last-tracked-time-timeago').attr('datetime', trackedTime); $scope('#chore-' + choreId + '-last-tracked-time-timeago').attr('datetime', trackedTime);
if (result.chore.period_type == "dynamic-regular") if (result.chore.period_type == "dynamic-regular")
{ {
$('#chore-' + choreId + '-next-execution-time').text(result.next_estimated_execution_time); $scope('#chore-' + choreId + '-next-execution-time').text(result.next_estimated_execution_time);
$('#chore-' + choreId + '-next-execution-time-timeago').attr('datetime', result.next_estimated_execution_time); $scope('#chore-' + choreId + '-next-execution-time-timeago').attr('datetime', result.next_estimated_execution_time);
} }
if (result.chore.next_execution_assigned_to_user_id != null) if (result.chore.next_execution_assigned_to_user_id != null)
{ {
$('#chore-' + choreId + '-next-execution-assigned-user').text(result.next_execution_assigned_user.display_name); $scope('#chore-' + choreId + '-next-execution-assigned-user').text(result.next_execution_assigned_user.display_name);
} }
Grocy.FrontendHelpers.EndUiBusy(); Grocy.FrontendHelpers.EndUiBusy();
@ -110,7 +112,7 @@
// Refresh the DataTable to re-apply filters // Refresh the DataTable to re-apply filters
choresOverviewTable.rows().invalidate().draw(false); choresOverviewTable.rows().invalidate().draw(false);
$(".input-group-filter").trigger("change"); $scope(".input-group-filter").trigger("change");
}, 550); }, 550);
}, },
function(xhr) function(xhr)
@ -135,15 +137,15 @@
); );
}); });
$(document).on("click", ".chore-name-cell", function(e) top.on("click", ".chore-name-cell", function(e)
{ {
Grocy.Components.ChoreCard.Refresh($(e.currentTarget).attr("data-chore-id")); Grocy.Components.ChoreCard.Refresh($scope(e.currentTarget).attr("data-chore-id"));
$("#choresoverview-chorecard-modal").modal("show"); $scope("#choresoverview-chorecard-modal").modal("show");
}); });
function RefreshStatistics() function RefreshStatistics()
{ {
var nextXDays = $("#info-due-chores").data("next-x-days"); var nextXDays = $scope("#info-due-chores").data("next-x-days");
Grocy.Api.Get('chores', Grocy.Api.Get('chores',
function(result) function(result)
{ {
@ -170,9 +172,9 @@
} }
}); });
$("#info-due-chores").html('<span class="d-block d-md-none">' + dueCount + ' <i class="fas fa-clock"></i></span><span class="d-none d-md-block">' + __n(dueCount, '%s chore is due to be done', '%s chores are due to be done') + ' ' + __n(nextXDays, 'within the next day', 'within the next %s days')); $scope("#info-due-chores").html('<span class="d-block d-md-none">' + dueCount + ' <i class="fas fa-clock"></i></span><span class="d-none d-md-block">' + __n(dueCount, '%s chore is due to be done', '%s chores are due to be done') + ' ' + __n(nextXDays, 'within the next day', 'within the next %s days'));
$("#info-overdue-chores").html('<span class="d-block d-md-none">' + overdueCount + ' <i class="fas fa-times-circle"></i></span><span class="d-none d-md-block">' + __n(overdueCount, '%s chore is overdue to be done', '%s chores are overdue to be done')); $scope("#info-overdue-chores").html('<span class="d-block d-md-none">' + overdueCount + ' <i class="fas fa-times-circle"></i></span><span class="d-none d-md-block">' + __n(overdueCount, '%s chore is overdue to be done', '%s chores are overdue to be done'));
$("#info-assigned-to-me-chores").html('<span class="d-block d-md-none">' + assignedToMeCount + ' <i class="fas fa-exclamation-circle"></i></span><span class="d-none d-md-block">' + __n(assignedToMeCount, '%s chore is assigned to me', '%s chores are assigned to me')); $scope("#info-assigned-to-me-chores").html('<span class="d-block d-md-none">' + assignedToMeCount + ' <i class="fas fa-exclamation-circle"></i></span><span class="d-none d-md-block">' + __n(assignedToMeCount, '%s chore is assigned to me', '%s chores are assigned to me'));
}, },
function(xhr) function(xhr)
{ {
@ -183,8 +185,8 @@
if (GetUriParam("user") !== undefined) if (GetUriParam("user") !== undefined)
{ {
$("#user-filter").val("xx" + GetUriParam("user") + "xx"); $scope("#user-filter").val("xx" + GetUriParam("user") + "xx");
$("#user-filter").trigger("change"); $scope("#user-filter").trigger("change");
} }
RefreshStatistics(); RefreshStatistics();

View File

@ -8,7 +8,7 @@
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
$("#chores_due_soon_days").val(Grocy.UserSettings.chores_due_soon_days); $scope("#chores_due_soon_days").val(Grocy.UserSettings.chores_due_soon_days);
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();

View File

@ -10,33 +10,33 @@
Grocy.Use("datetimepicker"); Grocy.Use("datetimepicker");
Grocy.Use("userpicker"); Grocy.Use("userpicker");
$('#save-choretracking-button').on('click', function(e) $scope('#save-choretracking-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonForm = $('#choretracking-form').serializeJSON(); var jsonForm = $scope('#choretracking-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("choretracking-form"); Grocy.FrontendHelpers.BeginUiBusy("choretracking-form");
Grocy.Api.Get('chores/' + jsonForm.chore_id, Grocy.Api.Get('chores/' + jsonForm.chore_id,
function(choreDetails) function(choreDetails)
{ {
Grocy.Api.Post('chores/' + jsonForm.chore_id + '/execute', { 'tracked_time': Grocy.Components.DateTimePicker.GetValue(), 'done_by': $("#user_id").val() }, Grocy.Api.Post('chores/' + jsonForm.chore_id + '/execute', { 'tracked_time': Grocy.Components.DateTimePicker.GetValue(), 'done_by': $scope("#user_id").val() },
function(result) function(result)
{ {
Grocy.FrontendHelpers.EndUiBusy("choretracking-form"); Grocy.FrontendHelpers.EndUiBusy("choretracking-form");
toastr.success(__t('Tracked execution of chore %1$s on %2$s', choreDetails.chore.name, Grocy.Components.DateTimePicker.GetValue()) + '<br><a class="btn btn-secondary btn-sm mt-2" href="#" onclick="Grocy.UndoChoreExecution(' + result.id + ')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>'); toastr.success(__t('Tracked execution of chore %1$s on %2$s', choreDetails.chore.name, Grocy.Components.DateTimePicker.GetValue()) + '<br><a class="btn btn-secondary btn-sm mt-2" href="#" onclick="Grocy.UndoChoreExecution(' + result.id + ')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>');
Grocy.Components.ChoreCard.Refresh($('#chore_id').val()); Grocy.Components.ChoreCard.Refresh($scope('#chore_id').val());
$('#chore_id').val(''); $scope('#chore_id').val('');
$('#chore_id_text_input').focus(); $scope('#chore_id_text_input').focus();
$('#chore_id_text_input').val(''); $scope('#chore_id_text_input').val('');
Grocy.Components.DateTimePicker.SetValue(moment().format('YYYY-MM-DD HH:mm:ss')); Grocy.Components.DateTimePicker.SetValue(moment().format('YYYY-MM-DD HH:mm:ss'));
$('#chore_id_text_input').trigger('change'); $scope('#chore_id_text_input').trigger('change');
Grocy.FrontendHelpers.ValidateForm('choretracking-form'); Grocy.FrontendHelpers.ValidateForm('choretracking-form');
}, },
function(xhr) function(xhr)
@ -54,13 +54,13 @@
); );
}); });
$('#chore_id').on('change', function(e) $scope('#chore_id').on('change', function(e)
{ {
var input = $('#chore_id_text_input').val().toString(); var input = $scope('#chore_id_text_input').val().toString();
$('#chore_id_text_input').val(input); $scope('#chore_id_text_input').val(input);
$('#chore_id').data('combobox').refresh(); $scope('#chore_id').data('combobox').refresh();
var choreId = $(e.target).val(); var choreId = $scope(e.target).val();
if (choreId) if (choreId)
{ {
Grocy.Api.Get('objects/chores/' + choreId, Grocy.Api.Get('objects/chores/' + choreId,
@ -89,22 +89,22 @@
} }
}); });
$('.combobox').combobox({ $scope('.combobox').combobox({
appendId: '_text_input', appendId: '_text_input',
bsVersion: '4' bsVersion: '4'
}); });
$('#chore_id_text_input').focus(); $scope('#chore_id_text_input').focus();
$('#chore_id_text_input').trigger('change'); $scope('#chore_id_text_input').trigger('change');
Grocy.Components.DateTimePicker.GetInputElement().trigger('input'); Grocy.Components.DateTimePicker.GetInputElement().trigger('input');
Grocy.FrontendHelpers.ValidateForm('choretracking-form'); Grocy.FrontendHelpers.ValidateForm('choretracking-form');
$('#choretracking-form input').keyup(function(event) $scope('#choretracking-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('choretracking-form'); Grocy.FrontendHelpers.ValidateForm('choretracking-form');
}); });
$('#choretracking-form input').keydown(function(event) $scope('#choretracking-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -116,7 +116,7 @@
} }
else else
{ {
$('#save-choretracking-button').click(); $scope('#save-choretracking-button').click();
} }
} }
}); });

View File

@ -1,47 +1,49 @@
function consumeView(Grocy, scope = null) import { BoolVal } from '../helpers/extensions';
import { WindowMessageBag } from '../helpers/messagebag';
function consumeView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
var top = scope != null ? $(scope) : $(document);
if (scope != null) if (scope != null)
{ {
$scope = $(scope).find; $scope = $(scope).find;
} }
import { BoolVal } from '../helpers/extensions';
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("productamountpicker"); Grocy.Use("productamountpicker");
Grocy.Use("productcard"); Grocy.Use("productcard");
Grocy.Use("productpicker"); Grocy.Use("productpicker");
Grocy.Use("recipepicker"); Grocy.Use("recipepicker");
$('#save-consume-button').on('click', function(e) $scope('#save-consume-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonForm = $('#consume-form').serializeJSON(); var jsonForm = $scope('#consume-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("consume-form"); Grocy.FrontendHelpers.BeginUiBusy("consume-form");
var apiUrl = 'stock/products/' + jsonForm.product_id + '/consume'; var apiUrl = 'stock/products/' + jsonForm.product_id + '/consume';
var jsonData = {}; var jsonData = {};
jsonData.amount = jsonForm.amount; jsonData.amount = jsonForm.amount;
jsonData.exact_amount = $('#consume-exact-amount').is(':checked'); jsonData.exact_amount = $scope('#consume-exact-amount').is(':checked');
jsonData.spoiled = $('#spoiled').is(':checked'); jsonData.spoiled = $scope('#spoiled').is(':checked');
jsonData.allow_subproduct_substitution = true; jsonData.allow_subproduct_substitution = true;
if ($("#use_specific_stock_entry").is(":checked")) if ($scope("#use_specific_stock_entry").is(":checked"))
{ {
jsonData.stock_entry_id = jsonForm.specific_stock_entry; jsonData.stock_entry_id = jsonForm.specific_stock_entry;
} }
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{ {
jsonData.location_id = $("#location_id").val(); jsonData.location_id = $scope("#location_id").val();
} }
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_RECIPES && Grocy.Components.RecipePicker.GetValue().toString().length > 0) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_RECIPES && Grocy.Components.RecipePicker.GetValue().toString().length > 0)
@ -72,9 +74,9 @@
Grocy.Api.Post('objects/product_barcodes', jsonDataBarcode, Grocy.Api.Post('objects/product_barcodes', jsonDataBarcode,
function(result) function(result)
{ {
$("#flow-info-InplaceAddBarcodeToExistingProduct").addClass("d-none"); $scope("#flow-info-InplaceAddBarcodeToExistingProduct").addClass("d-none");
$('#barcode-lookup-disabled-hint').addClass('d-none'); $scope('#barcode-lookup-disabled-hint').addClass('d-none');
$('#barcode-lookup-hint').removeClass('d-none'); $scope('#barcode-lookup-hint').removeClass('d-none');
window.history.replaceState({}, document.title, U("/consume")); window.history.replaceState({}, document.title, U("/consume"));
}, },
function(xhr) function(xhr)
@ -85,10 +87,10 @@
); );
} }
$("#specific_stock_entry").find("option").remove().end().append("<option></option>"); $scope("#specific_stock_entry").find("option").remove().end().append("<option></option>");
if ($("#use_specific_stock_entry").is(":checked")) if ($scope("#use_specific_stock_entry").is(":checked"))
{ {
$("#use_specific_stock_entry").click(); $scope("#use_specific_stock_entry").click();
} }
var successMessage = null; var successMessage = null;
@ -114,19 +116,19 @@
Grocy.Components.ProductPicker.FinishFlow(); Grocy.Components.ProductPicker.FinishFlow();
Grocy.Components.ProductAmountPicker.Reset(); Grocy.Components.ProductAmountPicker.Reset();
$("#display_amount").attr("min", Grocy.DefaultMinAmount); $scope("#display_amount").attr("min", Grocy.DefaultMinAmount);
$("#display_amount").removeAttr("max"); $scope("#display_amount").removeAttr("max");
if (BoolVal(Grocy.UserSettings.stock_default_consume_amount_use_quick_consume_amount)) if (BoolVal(Grocy.UserSettings.stock_default_consume_amount_use_quick_consume_amount))
{ {
$('#display_amount').val(productDetails.product.quick_consume_amount); $scope('#display_amount').val(productDetails.product.quick_consume_amount);
} }
else else
{ {
$('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_consume_amount)); $scope('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_consume_amount));
} }
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
$("#tare-weight-handling-info").addClass("d-none"); $scope("#tare-weight-handling-info").addClass("d-none");
Grocy.Components.ProductPicker.Clear(); Grocy.Components.ProductPicker.Clear();
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_RECIPES) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_RECIPES)
{ {
@ -134,12 +136,12 @@
} }
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{ {
$("#location_id").find("option").remove().end().append("<option></option>"); $scope("#location_id").find("option").remove().end().append("<option></option>");
} }
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
Grocy.Components.ProductCard.Refresh(jsonForm.product_id); Grocy.Components.ProductCard.Refresh(jsonForm.product_id);
Grocy.FrontendHelpers.ValidateForm('consume-form'); Grocy.FrontendHelpers.ValidateForm('consume-form');
$("#consume-exact-amount-group").addClass("d-none"); $scope("#consume-exact-amount-group").addClass("d-none");
} }
}, },
function(xhr) function(xhr)
@ -157,16 +159,16 @@
); );
}); });
$('#save-mark-as-open-button').on('click', function(e) $scope('#save-mark-as-open-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonForm = $('#consume-form').serializeJSON(); var jsonForm = $scope('#consume-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("consume-form"); Grocy.FrontendHelpers.BeginUiBusy("consume-form");
var apiUrl = 'stock/products/' + jsonForm.product_id + '/open'; var apiUrl = 'stock/products/' + jsonForm.product_id + '/open';
@ -175,7 +177,7 @@
jsonData.amount = jsonForm.amount; jsonData.amount = jsonForm.amount;
jsonData.allow_subproduct_substitution = true; jsonData.allow_subproduct_substitution = true;
if ($("#use_specific_stock_entry").is(":checked")) if ($scope("#use_specific_stock_entry").is(":checked"))
{ {
jsonData.stock_entry_id = jsonForm.specific_stock_entry; jsonData.stock_entry_id = jsonForm.specific_stock_entry;
} }
@ -186,10 +188,10 @@
Grocy.Api.Post(apiUrl, jsonData, Grocy.Api.Post(apiUrl, jsonData,
function(result) function(result)
{ {
$("#specific_stock_entry").find("option").remove().end().append("<option></option>"); $scope("#specific_stock_entry").find("option").remove().end().append("<option></option>");
if ($("#use_specific_stock_entry").is(":checked")) if ($scope("#use_specific_stock_entry").is(":checked"))
{ {
$("#use_specific_stock_entry").click(); $scope("#use_specific_stock_entry").click();
} }
Grocy.FrontendHelpers.EndUiBusy("consume-form"); Grocy.FrontendHelpers.EndUiBusy("consume-form");
@ -197,14 +199,14 @@
if (BoolVal(Grocy.UserSettings.stock_default_consume_amount_use_quick_consume_amount)) if (BoolVal(Grocy.UserSettings.stock_default_consume_amount_use_quick_consume_amount))
{ {
$('#display_amount').val(productDetails.product.quick_consume_amount); $scope('#display_amount').val(productDetails.product.quick_consume_amount);
} }
else else
{ {
$('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_consume_amount)); $scope('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_consume_amount));
} }
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
Grocy.Components.ProductPicker.Clear(); Grocy.Components.ProductPicker.Clear();
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
Grocy.FrontendHelpers.ValidateForm('consume-form'); Grocy.FrontendHelpers.ValidateForm('consume-form');
@ -224,16 +226,16 @@
); );
}); });
var sumValue = 0; var sumValue = 0;
$("#location_id").on('change', function(e) $scope("#location_id").on('change', function(e)
{ {
var locationId = $(e.target).val(); var locationId = $scope(e.target).val();
sumValue = 0; sumValue = 0;
var stockId = null; var stockId = null;
$("#specific_stock_entry").find("option").remove().end().append("<option></option>"); $scope("#specific_stock_entry").find("option").remove().end().append("<option></option>");
if ($("#use_specific_stock_entry").is(":checked")) if ($scope("#use_specific_stock_entry").is(":checked"))
{ {
$("#use_specific_stock_entry").click(); $scope("#use_specific_stock_entry").click();
} }
if (GetUriParam("embedded") !== undefined) if (GetUriParam("embedded") !== undefined)
@ -243,9 +245,9 @@
else else
{ {
// try to get stock id from grocycode // try to get stock id from grocycode
if ($("#product_id").data("grocycode")) if ($scope("#product_id").data("grocycode"))
{ {
var gc = $("#product_id").attr("barcode").split(":"); var gc = $scope("#product_id").attr("barcode").split(":");
if (gc.length == 4) if (gc.length == 4)
{ {
stockId = gc[3]; stockId = gc[3];
@ -268,7 +270,7 @@
if (stockEntry.location_id == locationId) if (stockEntry.location_id == locationId)
{ {
$("#specific_stock_entry").append($("<option>", { $scope("#specific_stock_entry").append($("<option>", {
value: stockEntry.stock_id, value: stockEntry.stock_id,
amount: stockEntry.amount, amount: stockEntry.amount,
text: __t("Amount: %1$s; Due on %2$s; Bought on %3$s", stockEntry.amount, moment(stockEntry.best_before_date).format("YYYY-MM-DD"), moment(stockEntry.purchased_date).format("YYYY-MM-DD")) + "; " + openTxt text: __t("Amount: %1$s; Due on %2$s; Bought on %3$s", stockEntry.amount, moment(stockEntry.best_before_date).format("YYYY-MM-DD"), moment(stockEntry.purchased_date).format("YYYY-MM-DD")) + "; " + openTxt
@ -278,8 +280,8 @@
if (stockEntry.stock_id == stockId) if (stockEntry.stock_id == stockId)
{ {
$("#use_specific_stock_entry").click(); $scope("#use_specific_stock_entry").click();
$("#specific_stock_entry").val(stockId); $scope("#specific_stock_entry").val(stockId);
} }
} }
}); });
@ -316,14 +318,14 @@
Grocy.UISound.BarcodeScannerBeep(); Grocy.UISound.BarcodeScannerBeep();
} }
$("#specific_stock_entry").find("option").remove().end().append("<option></option>"); $scope("#specific_stock_entry").find("option").remove().end().append("<option></option>");
if ($("#use_specific_stock_entry").is(":checked")) if ($scope("#use_specific_stock_entry").is(":checked"))
{ {
$("#use_specific_stock_entry").click(); $scope("#use_specific_stock_entry").click();
} }
$("#location_id").val(""); $scope("#location_id").val("");
var productId = $(e.target).val(); var productId = $scope(e.target).val();
if (productId) if (productId)
{ {
@ -338,16 +340,16 @@
Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.quantity_unit_stock.id); Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.quantity_unit_stock.id);
if (BoolVal(Grocy.UserSettings.stock_default_consume_amount_use_quick_consume_amount)) if (BoolVal(Grocy.UserSettings.stock_default_consume_amount_use_quick_consume_amount))
{ {
$('#display_amount').val(productDetails.product.quick_consume_amount); $scope('#display_amount').val(productDetails.product.quick_consume_amount);
} }
else else
{ {
$('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_consume_amount)); $scope('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_consume_amount));
} }
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
$("#location_id").find("option").remove().end().append("<option></option>"); $scope("#location_id").find("option").remove().end().append("<option></option>");
Grocy.Api.Get("stock/products/" + productId + '/locations?include_sub_products=true', Grocy.Api.Get("stock/products/" + productId + '/locations?include_sub_products=true',
function(stockLocations) function(stockLocations)
{ {
@ -356,17 +358,17 @@
{ {
if (productDetails.location.id == stockLocation.location_id) if (productDetails.location.id == stockLocation.location_id)
{ {
$("#location_id").append($("<option>", { $scope("#location_id").append($("<option>", {
value: stockLocation.location_id, value: stockLocation.location_id,
text: stockLocation.location_name + " (" + __t("Default location") + ")" text: stockLocation.location_name + " (" + __t("Default location") + ")"
})); }));
$("#location_id").val(productDetails.location.id); $scope("#location_id").val(productDetails.location.id);
$("#location_id").trigger('change'); $scope("#location_id").trigger('change');
setDefault = 1; setDefault = 1;
} }
else else
{ {
$("#location_id").append($("<option>", { $scope("#location_id").append($("<option>", {
value: stockLocation.location_id, value: stockLocation.location_id,
text: stockLocation.location_name text: stockLocation.location_name
})); }));
@ -374,8 +376,8 @@
if (setDefault == 0) if (setDefault == 0)
{ {
$("#location_id").val(stockLocation.location_id); $scope("#location_id").val(stockLocation.location_id);
$("#location_id").trigger('change'); $scope("#location_id").trigger('change');
} }
}); });
@ -392,8 +394,8 @@
{ {
if (barcode.amount != null && !barcode.amount.isEmpty()) if (barcode.amount != null && !barcode.amount.isEmpty())
{ {
$("#display_amount").val(barcode.amount); $scope("#display_amount").val(barcode.amount);
$("#display_amount").select(); $scope("#display_amount").select();
} }
if (barcode.qu_id != null) if (barcode.qu_id != null)
@ -401,7 +403,7 @@
Grocy.Components.ProductAmountPicker.SetQuantityUnit(barcode.qu_id); Grocy.Components.ProductAmountPicker.SetQuantityUnit(barcode.qu_id);
} }
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('consume-form'); Grocy.FrontendHelpers.ValidateForm('consume-form');
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
Grocy.ScanModeSubmit(false); Grocy.ScanModeSubmit(false);
@ -423,14 +425,14 @@
if (productDetails.product.enable_tare_weight_handling == 1) if (productDetails.product.enable_tare_weight_handling == 1)
{ {
$("#display_amount").attr("min", productDetails.product.tare_weight); $scope("#display_amount").attr("min", productDetails.product.tare_weight);
$('#display_amount').attr('max', parseFloat(productDetails.stock_amount) + parseFloat(productDetails.product.tare_weight)); $scope('#display_amount').attr('max', parseFloat(productDetails.stock_amount) + parseFloat(productDetails.product.tare_weight));
$("#tare-weight-handling-info").removeClass("d-none"); $scope("#tare-weight-handling-info").removeClass("d-none");
} }
else else
{ {
$("#display_amount").attr("min", Grocy.DefaultMinAmount); $scope("#display_amount").attr("min", Grocy.DefaultMinAmount);
$("#tare-weight-handling-info").addClass("d-none"); $scope("#tare-weight-handling-info").addClass("d-none");
} }
if ((parseFloat(productDetails.stock_amount_aggregated) || 0) === 0) if ((parseFloat(productDetails.stock_amount_aggregated) || 0) === 0)
@ -445,16 +447,16 @@
{ {
Grocy.Components.ProductPicker.HideCustomError(); Grocy.Components.ProductPicker.HideCustomError();
Grocy.FrontendHelpers.ValidateForm('consume-form'); Grocy.FrontendHelpers.ValidateForm('consume-form');
$('#display_amount').focus(); $scope('#display_amount').focus();
} }
if (productDetails.stock_amount == productDetails.stock_amount_opened || productDetails.product.enable_tare_weight_handling == 1) if (productDetails.stock_amount == productDetails.stock_amount_opened || productDetails.product.enable_tare_weight_handling == 1)
{ {
$("#save-mark-as-open-button").addClass("disabled"); $scope("#save-mark-as-open-button").addClass("disabled");
} }
else else
{ {
$("#save-mark-as-open-button").removeClass("disabled"); $scope("#save-mark-as-open-button").removeClass("disabled");
} }
}, },
function(xhr) function(xhr)
@ -465,32 +467,32 @@
} }
}); });
$('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_consume_amount)); $scope('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_consume_amount));
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('consume-form'); Grocy.FrontendHelpers.ValidateForm('consume-form');
$('#display_amount').on('focus', function(e) $scope('#display_amount').on('focus', function(e)
{ {
$(this).select(); $(this).select();
}); });
$('#price').on('focus', function(e) $scope('#price').on('focus', function(e)
{ {
$(this).select(); $(this).select();
}); });
$('#consume-form input').keyup(function(event) $scope('#consume-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('consume-form'); Grocy.FrontendHelpers.ValidateForm('consume-form');
}); });
$('#consume-form select').change(function(event) $scope('#consume-form select').change(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('consume-form'); Grocy.FrontendHelpers.ValidateForm('consume-form');
}); });
$('#consume-form input').keydown(function(event) $scope('#consume-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -502,12 +504,12 @@
} }
else else
{ {
$('#save-consume-button').click(); $scope('#save-consume-button').click();
} }
} }
}); });
$("#specific_stock_entry").on("change", function(e) $scope("#specific_stock_entry").on("change", function(e)
{ {
if ($(e.target).val() == "") if ($(e.target).val() == "")
{ {
@ -517,15 +519,15 @@
{ {
stockEntries.forEach(stockEntry => stockEntries.forEach(stockEntry =>
{ {
if (stockEntry.location_id == $("#location_id").val() || stockEntry.location_id == "") if (stockEntry.location_id == $scope("#location_id").val() || stockEntry.location_id == "")
{ {
sumValue = sumValue + parseFloat(stockEntry.amount_aggregated); sumValue = sumValue + parseFloat(stockEntry.amount_aggregated);
} }
}); });
$("#display_amount").attr("max", sumValue); $scope("#display_amount").attr("max", sumValue);
if (sumValue == 0) if (sumValue == 0)
{ {
$("#display_amount").parent().find(".invalid-feedback").text(__t('There are no units available at this location')); $scope("#display_amount").parent().find(".invalid-feedback").text(__t('There are no units available at this location'));
} }
}, },
function(xhr) function(xhr)
@ -536,31 +538,32 @@
} }
else else
{ {
$("#display_amount").attr("max", $('option:selected', this).attr('amount')); // vvv might break
$scope("#display_amount").attr("max", $('option:selected', this).attr('amount'));
} }
}); });
$("#use_specific_stock_entry").on("change", function() $scope("#use_specific_stock_entry").on("change", function()
{ {
var value = $(this).is(":checked"); var value = $(this).is(":checked");
if (value) if (value)
{ {
$("#specific_stock_entry").removeAttr("disabled"); $scope("#specific_stock_entry").removeAttr("disabled");
$("#specific_stock_entry").attr("required", ""); $scope("#specific_stock_entry").attr("required", "");
} }
else else
{ {
$("#specific_stock_entry").attr("disabled", ""); $scope("#specific_stock_entry").attr("disabled", "");
$("#specific_stock_entry").removeAttr("required"); $scope("#specific_stock_entry").removeAttr("required");
$("#specific_stock_entry").val(""); $scope("#specific_stock_entry").val("");
$("#location_id").trigger('change'); $scope("#location_id").trigger('change');
} }
Grocy.FrontendHelpers.ValidateForm("consume-form"); Grocy.FrontendHelpers.ValidateForm("consume-form");
}); });
$("#qu_id").on("change", function() $scope("#qu_id").on("change", function()
{ {
RefreshForm(); RefreshForm();
}); });
@ -576,17 +579,17 @@
} }
else else
{ {
$("#location_id").val(locationId); $scope("#location_id").val(locationId);
$("#location_id").trigger('change'); $scope("#location_id").trigger('change');
$("#use_specific_stock_entry").click(); $scope("#use_specific_stock_entry").click();
$("#use_specific_stock_entry").trigger('change'); $scope("#use_specific_stock_entry").trigger('change');
} }
} }
// Default input field // Default input field
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
$(document).on("change", "#scan-mode", function(e) top.on("change", "#scan-mode", function(e)
{ {
if ($(this).prop("checked")) if ($(this).prop("checked"))
{ {
@ -594,22 +597,22 @@
} }
}); });
$("#scan-mode-button").on("click", function(e) $scope("#scan-mode-button").on("click", function(e)
{ {
document.activeElement.blur(); document.activeElement.blur();
$("#scan-mode").click(); $scope("#scan-mode").click();
$("#scan-mode-button").toggleClass("btn-success").toggleClass("btn-danger"); $scope("#scan-mode-button").toggleClass("btn-success").toggleClass("btn-danger");
if ($("#scan-mode").prop("checked")) if ($scope("#scan-mode").prop("checked"))
{ {
$("#scan-mode-status").text(__t("on")); $scope("#scan-mode-status").text(__t("on"));
} }
else else
{ {
$("#scan-mode-status").text(__t("off")); $scope("#scan-mode-status").text(__t("off"));
} }
}); });
$('#consume-exact-amount').on('change', RefreshForm); $scope('#consume-exact-amount').on('change', RefreshForm);
var current_productDetails; var current_productDetails;
function RefreshForm() function RefreshForm()
{ {
@ -621,32 +624,34 @@
if (productDetails.product.enable_tare_weight_handling == 1) if (productDetails.product.enable_tare_weight_handling == 1)
{ {
$("#consume-exact-amount-group").removeClass("d-none"); $scope("#consume-exact-amount-group").removeClass("d-none");
} }
else else
{ {
$("#consume-exact-amount-group").addClass("d-none"); $scope("#consume-exact-amount-group").addClass("d-none");
} }
if (productDetails.product.enable_tare_weight_handling == 1 && !$('#consume-exact-amount').is(':checked')) if (productDetails.product.enable_tare_weight_handling == 1 && !$scope('#consume-exact-amount').is(':checked'))
{ {
$("#display_amount").attr("min", productDetails.product.tare_weight); $scope("#display_amount").attr("min", productDetails.product.tare_weight);
$('#display_amount').attr('max', sumValue + parseFloat(productDetails.product.tare_weight)); $scope('#display_amount').attr('max', sumValue + parseFloat(productDetails.product.tare_weight));
$("#tare-weight-handling-info").removeClass("d-none"); $scope("#tare-weight-handling-info").removeClass("d-none");
} }
else else
{ {
$("#tare-weight-handling-info").addClass("d-none"); $scope("#tare-weight-handling-info").addClass("d-none");
$("#display_amount").attr("min", Grocy.DefaultMinAmount); $scope("#display_amount").attr("min", Grocy.DefaultMinAmount);
$('#display_amount').attr('max', sumValue * $("#qu_id option:selected").attr("data-qu-factor")); $scope('#display_amount').attr('max', sumValue * $scope("#qu_id option:selected").attr("data-qu-factor"));
if (sumValue == 0) if (sumValue == 0)
{ {
$("#display_amount").parent().find(".invalid-feedback").text(__t('There are no units available at this location')); $scope("#display_amount").parent().find(".invalid-feedback").text(__t('There are no units available at this location'));
} }
} }
Grocy.FrontendHelpers.ValidateForm("consume-form"); Grocy.FrontendHelpers.ValidateForm("consume-form");
} }
} }
window.consumeViw = consumeView;

View File

@ -1,4 +1,6 @@
function equipmentView(Grocy, scope = null) import { ResizeResponsiveEmbeds } from "../helpers/embeds";
function equipmentView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,9 +8,7 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { ResizeResponsiveEmbeds } from "../helpers/embeds"; var equipmentTable = $scope('#equipment-table').DataTable({
var equipmentTable = $('#equipment-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
@ -21,17 +21,17 @@
'initComplete': function() 'initComplete': function()
{ {
this.api().row({ order: 'current' }, 0).select(); this.api().row({ order: 'current' }, 0).select();
DisplayEquipment($('#equipment-table tbody tr:eq(0)').data("equipment-id")); DisplayEquipment($scope('#equipment-table tbody tr:eq(0)').data("equipment-id"));
} }
}); });
$('#equipment-table tbody').removeClass("d-none"); $scope('#equipment-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(equipmentTable); Grocy.FrontendHelpers.InitDataTable(equipmentTable);
equipmentTable.on('select', function(e, dt, type, indexes) equipmentTable.on('select', function(e, dt, type, indexes)
{ {
if (type === 'row') if (type === 'row')
{ {
var selectedEquipmentId = $(equipmentTable.row(indexes[0]).node()).data("equipment-id"); var selectedEquipmentId = $scope(equipmentTable.row(indexes[0]).node()).data("equipment-id");
DisplayEquipment(selectedEquipmentId) DisplayEquipment(selectedEquipmentId)
} }
}); });
@ -41,29 +41,29 @@
Grocy.Api.Get('objects/equipment/' + id, Grocy.Api.Get('objects/equipment/' + id,
function(equipmentItem) function(equipmentItem)
{ {
$(".selected-equipment-name").text(equipmentItem.name); $scope(".selected-equipment-name").text(equipmentItem.name);
$("#description-tab-content").html(equipmentItem.description); $scope("#description-tab-content").html(equipmentItem.description);
$(".equipment-edit-button").attr("href", U("/equipment/" + equipmentItem.id.toString())); $scope(".equipment-edit-button").attr("href", U("/equipment/" + equipmentItem.id.toString()));
if (equipmentItem.instruction_manual_file_name !== null && !equipmentItem.instruction_manual_file_name.isEmpty()) if (equipmentItem.instruction_manual_file_name !== null && !equipmentItem.instruction_manual_file_name.isEmpty())
{ {
var pdfUrl = U('/api/files/equipmentmanuals/' + btoa(equipmentItem.instruction_manual_file_name)); var pdfUrl = U('/api/files/equipmentmanuals/' + btoa(equipmentItem.instruction_manual_file_name));
$("#selected-equipment-instruction-manual").attr("src", pdfUrl); $scope("#selected-equipment-instruction-manual").attr("src", pdfUrl);
$("#selectedEquipmentInstructionManualDownloadButton").attr("href", pdfUrl); $scope("#selectedEquipmentInstructionManualDownloadButton").attr("href", pdfUrl);
$("#selected-equipment-instruction-manual").removeClass("d-none"); $scope("#selected-equipment-instruction-manual").removeClass("d-none");
$("#selectedEquipmentInstructionManualDownloadButton").removeClass("d-none"); $scope("#selectedEquipmentInstructionManualDownloadButton").removeClass("d-none");
$("#selected-equipment-has-no-instruction-manual-hint").addClass("d-none"); $scope("#selected-equipment-has-no-instruction-manual-hint").addClass("d-none");
$("a[href='#instruction-manual-tab']").tab("show"); $scope("a[href='#instruction-manual-tab']").tab("show");
ResizeResponsiveEmbeds(); ResizeResponsiveEmbeds();
} }
else else
{ {
$("#selected-equipment-instruction-manual").addClass("d-none"); $scope("#selected-equipment-instruction-manual").addClass("d-none");
$("#selectedEquipmentInstructionManualDownloadButton").addClass("d-none"); $scope("#selectedEquipmentInstructionManualDownloadButton").addClass("d-none");
$("#selected-equipment-has-no-instruction-manual-hint").removeClass("d-none"); $scope("#selected-equipment-has-no-instruction-manual-hint").removeClass("d-none");
$("a[href='#description-tab']").tab("show"); $scope("a[href='#description-tab']").tab("show");
} }
}, },
function(xhr) function(xhr)
@ -82,21 +82,23 @@
'/equipment' '/equipment'
); );
$("#selectedEquipmentInstructionManualToggleFullscreenButton").on('click', function(e) $scope("#selectedEquipmentInstructionManualToggleFullscreenButton").on('click', function(e)
{ {
$("#selectedEquipmentInstructionManualCard").toggleClass("fullscreen"); $scope("#selectedEquipmentInstructionManualCard").toggleClass("fullscreen");
$("#selectedEquipmentInstructionManualCard .card-header").toggleClass("fixed-top"); $scope("#selectedEquipmentInstructionManualCard .card-header").toggleClass("fixed-top");
$("#selectedEquipmentInstructionManualCard .card-body").toggleClass("mt-5"); $scope("#selectedEquipmentInstructionManualCard .card-body").toggleClass("mt-5");
$("body").toggleClass("fullscreen-card"); $scope("body").toggleClass("fullscreen-card");
ResizeResponsiveEmbeds(true); ResizeResponsiveEmbeds(true);
}); });
$("#selectedEquipmentDescriptionToggleFullscreenButton").on('click', function(e) $scope("#selectedEquipmentDescriptionToggleFullscreenButton").on('click', function(e)
{ {
$("#selectedEquipmentDescriptionCard").toggleClass("fullscreen"); $scope("#selectedEquipmentDescriptionCard").toggleClass("fullscreen");
$("#selectedEquipmentDescriptionCard .card-header").toggleClass("fixed-top"); $scope("#selectedEquipmentDescriptionCard .card-header").toggleClass("fixed-top");
$("#selectedEquipmentDescriptionCard .card-body").toggleClass("mt-5"); $scope("#selectedEquipmentDescriptionCard .card-body").toggleClass("mt-5");
$("body").toggleClass("fullscreen-card"); $scope("body").toggleClass("fullscreen-card");
}); });
} }
window.equipmentView = equipmentView

View File

@ -1,4 +1,7 @@
function equipmentformView(Grocy, scope = null) import { RandomString } from '../helpers/extensions';
import { ResizeResponsiveEmbeds } from '../helpers/embeds';
function equipmentformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,27 +9,24 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { RandomString } from '../helpers/extensions';
import { ResizeResponsiveEmbeds } from '../helpers/embeds';
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
$('#save-equipment-button').on('click', function(e) $scope('#save-equipment-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#equipment-form').serializeJSON(); var jsonData = $scope('#equipment-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("equipment-form"); Grocy.FrontendHelpers.BeginUiBusy("equipment-form");
if ($("#instruction-manual")[0].files.length > 0) if ($scope("#instruction-manual")[0].files.length > 0)
{ {
var someRandomStuff = RandomString(); var someRandomStuff = RandomString();
jsonData.instruction_manual_file_name = someRandomStuff + $("#instruction-manual")[0].files[0].name; jsonData.instruction_manual_file_name = someRandomStuff + $scope("#instruction-manual")[0].files[0].name;
} }
if (Grocy.DeleteInstructionManualOnSave) if (Grocy.DeleteInstructionManualOnSave)
@ -45,7 +45,7 @@
// https://eslint.org/docs/rules/no-prototype-builtins // https://eslint.org/docs/rules/no-prototype-builtins
if (Object.prototype.hasOwnProperty.call(jsonData, "instruction_manual_file_name") && !Grocy.DeleteInstructionManualOnSave) if (Object.prototype.hasOwnProperty.call(jsonData, "instruction_manual_file_name") && !Grocy.DeleteInstructionManualOnSave)
{ {
Grocy.Api.UploadFile($("#instruction-manual")[0].files[0], 'equipmentmanuals', jsonData.instruction_manual_file_name, Grocy.Api.UploadFile($scope("#instruction-manual")[0].files[0], 'equipmentmanuals', jsonData.instruction_manual_file_name,
function(result) function(result)
{ {
window.location.href = U('/equipment'); window.location.href = U('/equipment');
@ -94,7 +94,7 @@
{ {
if (Object.prototype.hasOwnProperty.call(jsonData, "instruction_manual_file_name") && !Grocy.DeleteInstructionManualOnSave) if (Object.prototype.hasOwnProperty.call(jsonData, "instruction_manual_file_name") && !Grocy.DeleteInstructionManualOnSave)
{ {
Grocy.Api.UploadFile($("#instruction-manual")[0].files[0], 'equipmentmanuals', jsonData.instruction_manual_file_name, Grocy.Api.UploadFile($scope("#instruction-manual")[0].files[0], 'equipmentmanuals', jsonData.instruction_manual_file_name,
function(result) function(result)
{ {
window.location.href = U('/equipment'); window.location.href = U('/equipment');
@ -121,12 +121,12 @@
} }
}); });
$('#equipment-form input').keyup(function(event) $scope('#equipment-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('equipment-form'); Grocy.FrontendHelpers.ValidateForm('equipment-form');
}); });
$('#equipment-form input').keydown(function(event) $scope('#equipment-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -138,33 +138,33 @@
} }
else else
{ {
$('#save-equipment-button').click(); $scope('#save-equipment-button').click();
} }
} }
}); });
Grocy.DeleteInstructionManualOnSave = false; Grocy.DeleteInstructionManualOnSave = false;
$('#delete-current-instruction-manual-button').on('click', function(e) $scope('#delete-current-instruction-manual-button').on('click', function(e)
{ {
Grocy.DeleteInstructionManualOnSave = true; Grocy.DeleteInstructionManualOnSave = true;
$("#current-equipment-instruction-manual").addClass("d-none"); $scope("#current-equipment-instruction-manual").addClass("d-none");
$("#delete-current-instruction-manual-on-save-hint").removeClass("d-none"); $scope("#delete-current-instruction-manual-on-save-hint").removeClass("d-none");
$("#delete-current-instruction-manual-button").addClass("disabled"); $scope("#delete-current-instruction-manual-button").addClass("disabled");
$("#instruction-manual-label").addClass("d-none"); $scope("#instruction-manual-label").addClass("d-none");
$("#instruction-manual-label-none").removeClass("d-none"); $scope("#instruction-manual-label-none").removeClass("d-none");
}); });
ResizeResponsiveEmbeds(); ResizeResponsiveEmbeds();
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
$('#name').focus(); $scope('#name').focus();
Grocy.FrontendHelpers.ValidateForm('equipment-form'); Grocy.FrontendHelpers.ValidateForm('equipment-form');
$("#instruction-manual").on("change", function(e) $scope("#instruction-manual").on("change", function(e)
{ {
$("#instruction-manual-label").removeClass("d-none"); $scope("#instruction-manual-label").removeClass("d-none");
$("#instruction-manual-label-none").addClass("d-none"); $scope("#instruction-manual-label-none").addClass("d-none");
$("#delete-current-instruction-manual-on-save-hint").addClass("d-none"); $scope("#delete-current-instruction-manual-on-save-hint").addClass("d-none");
$("#current-instruction-manuale").addClass("d-none"); $scope("#current-instruction-manuale").addClass("d-none");
Grocy.DeleteProductPictureOnSave = false; Grocy.DeleteProductPictureOnSave = false;
}); });

View File

@ -1,4 +1,6 @@
function inventoryView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function inventoryView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,8 +8,6 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("datetimepicker"); Grocy.Use("datetimepicker");
if (Grocy.UserSettings.show_purchased_date_on_purchase) if (Grocy.UserSettings.show_purchased_date_on_purchase)
{ {
@ -20,16 +20,16 @@
Grocy.Use("productcard"); Grocy.Use("productcard");
Grocy.Use("shoppinglocationpicker"); Grocy.Use("shoppinglocationpicker");
$('#save-inventory-button').on('click', function(e) $scope('#save-inventory-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonForm = $('#inventory-form').serializeJSON(); var jsonForm = $scope('#inventory-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("inventory-form"); Grocy.FrontendHelpers.BeginUiBusy("inventory-form");
Grocy.Api.Get('stock/products/' + jsonForm.product_id, Grocy.Api.Get('stock/products/' + jsonForm.product_id,
@ -76,9 +76,9 @@
Grocy.Api.Post('objects/product_barcodes', jsonDataBarcode, Grocy.Api.Post('objects/product_barcodes', jsonDataBarcode,
function(result) function(result)
{ {
$("#flow-info-InplaceAddBarcodeToExistingProduct").addClass("d-none"); $scope("#flow-info-InplaceAddBarcodeToExistingProduct").addClass("d-none");
$('#barcode-lookup-disabled-hint').addClass('d-none'); $scope('#barcode-lookup-disabled-hint').addClass('d-none');
$('#barcode-lookup-hint').removeClass('d-none'); $scope('#barcode-lookup-hint').removeClass('d-none');
window.history.replaceState({}, document.title, U("/inventory")); window.history.replaceState({}, document.title, U("/inventory"));
}, },
function(xhr) function(xhr)
@ -107,13 +107,13 @@
Grocy.Components.ProductPicker.FinishFlow(); Grocy.Components.ProductPicker.FinishFlow();
Grocy.Components.ProductAmountPicker.Reset(); Grocy.Components.ProductAmountPicker.Reset();
$('#inventory-change-info').addClass('d-none'); $scope('#inventory-change-info').addClass('d-none');
$("#tare-weight-handling-info").addClass("d-none"); $scope("#tare-weight-handling-info").addClass("d-none");
$("#display_amount").attr("min", "0"); $scope("#display_amount").attr("min", "0");
$('#display_amount').val(''); $scope('#display_amount').val('');
$('#display_amount').removeAttr("data-not-equal"); $scope('#display_amount').removeAttr("data-not-equal");
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
$('#price').val(''); $scope('#price').val('');
Grocy.Components.DateTimePicker.Clear(); Grocy.Components.DateTimePicker.Clear();
Grocy.Components.ProductPicker.SetValue(''); Grocy.Components.ProductPicker.SetValue('');
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
@ -149,7 +149,7 @@
Grocy.Components.ProductPicker.GetPicker().on('change', function(e) Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{ {
var productId = $(e.target).val(); var productId = $scope(e.target).val();
if (productId) if (productId)
{ {
@ -161,21 +161,21 @@
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id); Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.quantity_unit_stock.id); Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.quantity_unit_stock.id);
$('#display_amount').attr("data-stock-amount", productDetails.stock_amount) $scope('#display_amount').attr("data-stock-amount", productDetails.stock_amount)
$('#display_amount').attr('data-not-equal', productDetails.stock_amount * $("#qu_id option:selected").attr("data-qu-factor")); $scope('#display_amount').attr('data-not-equal', productDetails.stock_amount * $scope("#qu_id option:selected").attr("data-qu-factor"));
if (productDetails.product.enable_tare_weight_handling == 1) if (productDetails.product.enable_tare_weight_handling == 1)
{ {
$("#display_amount").attr("min", productDetails.product.tare_weight); $scope("#display_amount").attr("min", productDetails.product.tare_weight);
$("#tare-weight-handling-info").removeClass("d-none"); $scope("#tare-weight-handling-info").removeClass("d-none");
} }
else else
{ {
$("#display_amount").attr("min", "0"); $scope("#display_amount").attr("min", "0");
$("#tare-weight-handling-info").addClass("d-none"); $scope("#tare-weight-handling-info").addClass("d-none");
} }
$('#price').val(parseFloat(productDetails.last_price)); $scope('#price').val(parseFloat(productDetails.last_price));
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{ {
@ -192,9 +192,9 @@
{ {
if (productDetails.product.default_best_before_days == -1) if (productDetails.product.default_best_before_days == -1)
{ {
if (!$("#datetimepicker-shortcut").is(":checked")) if (!$scope("#datetimepicker-shortcut").is(":checked"))
{ {
$("#datetimepicker-shortcut").click(); $scope("#datetimepicker-shortcut").click();
} }
} }
else else
@ -217,8 +217,8 @@
{ {
if (barcode.amount != null && !barcode.amount.isEmpty()) if (barcode.amount != null && !barcode.amount.isEmpty())
{ {
$("#display_amount").val(barcode.amount); $scope("#display_amount").val(barcode.amount);
$("#display_amount").select(); $scope("#display_amount").select();
} }
if (barcode.qu_id != null) if (barcode.qu_id != null)
@ -226,7 +226,7 @@
Grocy.Components.ProductAmountPicker.SetQuantityUnit(barcode.qu_id); Grocy.Components.ProductAmountPicker.SetQuantityUnit(barcode.qu_id);
} }
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('inventory-form'); Grocy.FrontendHelpers.ValidateForm('inventory-form');
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
} }
@ -239,11 +239,11 @@
); );
} }
$('#display_amount').val(productDetails.stock_amount); $scope('#display_amount').val(productDetails.stock_amount);
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
$('#display_amount').focus(); $scope('#display_amount').focus();
$('#display_amount').trigger('keyup'); $scope('#display_amount').trigger('keyup');
}, },
function(xhr) function(xhr)
{ {
@ -253,8 +253,8 @@
} }
}); });
$('#display_amount').val(''); $scope('#display_amount').val('');
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('inventory-form'); Grocy.FrontendHelpers.ValidateForm('inventory-form');
if (Grocy.Components.ProductPicker.InAnyFlow() === false && GetUriParam("embedded") === undefined) if (Grocy.Components.ProductPicker.InAnyFlow() === false && GetUriParam("embedded") === undefined)
@ -271,7 +271,7 @@
} }
} }
$('#display_amount').on('focus', function(e) $scope('#display_amount').on('focus', function(e)
{ {
if (Grocy.Components.ProductPicker.GetValue().length === 0) if (Grocy.Components.ProductPicker.GetValue().length === 0)
{ {
@ -283,12 +283,12 @@
} }
}); });
$('#inventory-form input').keyup(function(event) $scope('#inventory-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('inventory-form'); Grocy.FrontendHelpers.ValidateForm('inventory-form');
}); });
$('#inventory-form input').keydown(function(event) $scope('#inventory-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -300,15 +300,15 @@
} }
else else
{ {
$('#save-inventory-button').click(); $scope('#save-inventory-button').click();
} }
} }
}); });
$('#qu_id').on('change', function(e) $scope('#qu_id').on('change', function(e)
{ {
$('#display_amount').attr('data-not-equal', parseFloat($('#display_amount').attr('data-stock-amount')) * parseFloat($("#qu_id option:selected").attr("data-qu-factor"))); $scope('#display_amount').attr('data-not-equal', parseFloat($scope('#display_amount').attr('data-stock-amount')) * parseFloat($scope("#qu_id option:selected").attr("data-qu-factor")));
Grocy.FrontendHelpers.ValidateForm('inventory-form'); Grocy.FrontendHelpers.ValidateForm('inventory-form');
}); });
@ -322,10 +322,10 @@
Grocy.FrontendHelpers.ValidateForm('inventory-form'); Grocy.FrontendHelpers.ValidateForm('inventory-form');
}); });
$('#display_amount').on('keyup', function(e) $scope('#display_amount').on('keyup', function(e)
{ {
var productId = Grocy.Components.ProductPicker.GetValue(); var productId = Grocy.Components.ProductPicker.GetValue();
var newAmount = parseInt($('#amount').val()); var newAmount = parseInt($scope('#amount').val());
if (productId) if (productId)
{ {
@ -341,15 +341,15 @@
} }
var estimatedBookingAmount = Math.abs(newAmount - productStockAmount - containerWeight); var estimatedBookingAmount = Math.abs(newAmount - productStockAmount - containerWeight);
$('#inventory-change-info').removeClass('d-none'); $scope('#inventory-change-info').removeClass('d-none');
if (productDetails.product.enable_tare_weight_handling == 1 && newAmount < containerWeight) if (productDetails.product.enable_tare_weight_handling == 1 && newAmount < containerWeight)
{ {
$('#inventory-change-info').addClass('d-none'); $scope('#inventory-change-info').addClass('d-none');
} }
else if (newAmount > productStockAmount + containerWeight) else if (newAmount > productStockAmount + containerWeight)
{ {
$('#inventory-change-info').text(__t('This means %s will be added to stock', estimatedBookingAmount.toLocaleString() + ' ' + __n(estimatedBookingAmount, productDetails.quantity_unit_stock.name, productDetails.quantity_unit_stock.name_plural))); $scope('#inventory-change-info').text(__t('This means %s will be added to stock', estimatedBookingAmount.toLocaleString() + ' ' + __n(estimatedBookingAmount, productDetails.quantity_unit_stock.name, productDetails.quantity_unit_stock.name_plural)));
Grocy.Components.DateTimePicker.GetInputElement().attr('required', ''); Grocy.Components.DateTimePicker.GetInputElement().attr('required', '');
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{ {
@ -358,7 +358,7 @@
} }
else if (newAmount < productStockAmount + containerWeight) else if (newAmount < productStockAmount + containerWeight)
{ {
$('#inventory-change-info').text(__t('This means %s will be removed from stock', estimatedBookingAmount.toLocaleString() + ' ' + __n(estimatedBookingAmount, productDetails.quantity_unit_stock.name, productDetails.quantity_unit_stock.name_plural))); $scope('#inventory-change-info').text(__t('This means %s will be removed from stock', estimatedBookingAmount.toLocaleString() + ' ' + __n(estimatedBookingAmount, productDetails.quantity_unit_stock.name, productDetails.quantity_unit_stock.name_plural)));
Grocy.Components.DateTimePicker.GetInputElement().removeAttr('required'); Grocy.Components.DateTimePicker.GetInputElement().removeAttr('required');
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{ {
@ -381,6 +381,8 @@
} }
}); });
$("#display_amount").attr("min", "0"); $scope("#display_amount").attr("min", "0");
} }
window.inventoryView = inventoryView

View File

@ -1,23 +1,24 @@
function locationcontentsheetView(Grocy, scope = null) function locationcontentsheetView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
var top = scope != null ? $(scope) : $(document);
if (scope != null) if (scope != null)
{ {
$scope = $(scope).find; $scope = $(scope).find;
} }
$(document).on("click", ".print-all-locations-button", function(e) top.on("click", ".print-all-locations-button", function(e)
{ {
$(".page").removeClass("d-print-none").removeClass("no-page-break"); $scope(".page").removeClass("d-print-none").removeClass("no-page-break");
$(".print-timestamp").text(moment().format("l LT")); $scope(".print-timestamp").text(moment().format("l LT"));
window.print(); window.print();
}); });
$(document).on("click", ".print-single-location-button", function(e) top.on("click", ".print-single-location-button", function(e)
{ {
$(".page").addClass("d-print-none"); $scope(".page").addClass("d-print-none");
$(e.currentTarget).closest(".page").removeClass("d-print-none").addClass("no-page-break"); $scope(e.currentTarget).closest(".page").removeClass("d-print-none").addClass("no-page-break");
$(".print-timestamp").text(moment().format("l LT")); $scope(".print-timestamp").text(moment().format("l LT"));
window.print(); window.print();
}); });

View File

@ -1,4 +1,6 @@
function locationformView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function locationformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,20 +8,18 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
$('#save-location-button').on('click', function(e) $scope('#save-location-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#location-form').serializeJSON(); var jsonData = $scope('#location-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("location-form"); Grocy.FrontendHelpers.BeginUiBusy("location-form");
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
@ -73,12 +73,12 @@
} }
}); });
$('#location-form input').keyup(function(event) $scope('#location-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('location-form'); Grocy.FrontendHelpers.ValidateForm('location-form');
}); });
$('#location-form input').keydown(function(event) $scope('#location-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -90,13 +90,15 @@
} }
else else
{ {
$('#save-location-button').click(); $scope('#save-location-button').click();
} }
} }
}); });
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
Grocy.FrontendHelpers.ValidateForm('location-form'); Grocy.FrontendHelpers.ValidateForm('location-form');
$('#name').focus(); $scope('#name').focus();
} }
window.locationformView = locationformView

View File

@ -6,15 +6,15 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var locationsTable = $('#locations-table').DataTable({ var locationsTable = $scope('#locations-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#locations-table tbody').removeClass("d-none"); $scope('#locations-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(locationsTable); Grocy.FrontendHelpers.InitDataTable(locationsTable,);
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete location "%s"?', 'Are you sure to delete location "%s"?',

View File

@ -6,12 +6,12 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
$('#username').focus(); $scope('#username').focus();
if (GetUriParam('invalid') === 'true') if (GetUriParam('invalid') === 'true')
{ {
$('#login-error').text(__t('Invalid credentials, please try again')); $scope('#login-error').text(__t('Invalid credentials, please try again'));
$('#login-error').removeClass('d-none'); $scope('#login-error').removeClass('d-none');
} }
} }

View File

@ -1,4 +1,6 @@
function manageapikeysView(Grocy, scope = null) import { QrCodeImgHtml } from "../helpers/qrcode";
function manageapikeysView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,16 +8,14 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { QrCodeImgHtml } from "../helpers/qrcode"; var apiKeysTable = $scope('#apikeys-table').DataTable({
var apiKeysTable = $('#apikeys-table').DataTable({
'order': [[4, 'desc']], 'order': [[4, 'desc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#apikeys-table tbody').removeClass("d-none"); $scope('#apikeys-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(apiKeysTable); Grocy.FrontendHelpers.InitDataTable(apiKeysTable);
var createdApiKeyId = GetUriParam('CreatedApiKeyId'); var createdApiKeyId = GetUriParam('CreatedApiKeyId');
@ -44,7 +44,7 @@
return QrCodeImgHtml(content); return QrCodeImgHtml(content);
} }
$('.apikey-show-qr-button').on('click', function() $scope('.apikey-show-qr-button').on('click', function()
{ {
var qrcodeHtml = QrCodeForApiKey($(this).data('apikey-type'), $(this).data('apikey-key')); var qrcodeHtml = QrCodeForApiKey($(this).data('apikey-type'), $(this).data('apikey-key'));
bootbox.alert({ bootbox.alert({
@ -55,3 +55,5 @@
}) })
} }
window.manageapikeysView = manageapikeysView;

View File

@ -1,12 +1,4 @@
function mealplanView(Grocy, scope = null) /* global fullcalendarEventSources, internalRecipes, recipesResolved */
{
var $scope = $;
if (scope != null)
{
$scope = $(scope).find;
}
/* global fullcalendarEventSources, internalRecipes, recipesResolved */
import { Calendar } from '@fullcalendar/core'; import { Calendar } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid'; import dayGridPlugin from '@fullcalendar/daygrid';
@ -18,6 +10,17 @@
import '@fullcalendar/daygrid/main.css'; import '@fullcalendar/daygrid/main.css';
import '@fullcalendar/bootstrap/main.css'; import '@fullcalendar/bootstrap/main.css';
function mealplanView(Grocy, scope = null)
{
var $scope = $;
var top = scope != null ? $(scope) : $(document);
var viewport = scope != null ? $(scope) : $(window);
if (scope != null)
{
$scope = $(scope).find;
}
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
Grocy.Use("productamountpicker"); Grocy.Use("productamountpicker");
Grocy.Use("recipepicker"); Grocy.Use("recipepicker");
@ -54,7 +57,7 @@
weekNumbers: false, weekNumbers: false,
eventLimit: false, eventLimit: false,
events: fullcalendarEventSources, events: fullcalendarEventSources,
defaultView: ($(window).width() < 768) ? "dayGridDay" : "dayGridWeek", defaultView: (viewport.width() < 768) ? "dayGridDay" : "dayGridWeek",
firstDay: firstDay, firstDay: firstDay,
height: "auto", height: "auto",
datesRender: function(info) datesRender: function(info)
@ -70,7 +73,7 @@
UpdateUriParam("week", start.format("YYYY-MM-DD")); UpdateUriParam("week", start.format("YYYY-MM-DD"));
} }
$(".fc-day-header").prepend('\ $scope(".fc-day-header").prepend('\
<div class="btn-group mr-2 my-1"> \ <div class="btn-group mr-2 my-1"> \
<button type="button" class="btn btn-outline-dark btn-xs add-recipe-button""><i class="fas fa-plus"></i></a></button> \ <button type="button" class="btn btn-outline-dark btn-xs add-recipe-button""><i class="fas fa-plus"></i></a></button> \
<button type="button" class="btn btn-outline-dark btn-xs dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"></button> \ <button type="button" class="btn btn-outline-dark btn-xs dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"></button> \
@ -110,7 +113,7 @@
weekRecipeOrderMissingButtonHtml = '<a class="ml-1 btn btn-outline-primary btn-xs recipe-order-missing-button ' + weekRecipeOrderMissingButtonDisabledClasses + '" href="#" data-toggle="tooltip" title="' + __t("Put missing products on shopping list") + '" data-recipe-id="' + weekRecipe.id.toString() + '" data-recipe-name="' + weekRecipe.name + '" data-recipe-type="' + weekRecipe.type + '"><i class="fas fa-cart-plus"></i></a>' weekRecipeOrderMissingButtonHtml = '<a class="ml-1 btn btn-outline-primary btn-xs recipe-order-missing-button ' + weekRecipeOrderMissingButtonDisabledClasses + '" href="#" data-toggle="tooltip" title="' + __t("Put missing products on shopping list") + '" data-recipe-id="' + weekRecipe.id.toString() + '" data-recipe-name="' + weekRecipe.name + '" data-recipe-type="' + weekRecipe.type + '"><i class="fas fa-cart-plus"></i></a>'
weekRecipeConsumeButtonHtml = '<a class="ml-1 btn btn-outline-success btn-xs recipe-consume-button ' + weekRecipeConsumeButtonDisabledClasses + '" href="#" data-toggle="tooltip" title="' + __t("Consume all ingredients needed by this weeks recipes or products") + '" data-recipe-id="' + weekRecipe.id.toString() + '" data-recipe-name="' + weekRecipe.name + '" data-recipe-type="' + weekRecipe.type + '"><i class="fas fa-utensils"></i></a>' weekRecipeConsumeButtonHtml = '<a class="ml-1 btn btn-outline-success btn-xs recipe-consume-button ' + weekRecipeConsumeButtonDisabledClasses + '" href="#" data-toggle="tooltip" title="' + __t("Consume all ingredients needed by this weeks recipes or products") + '" data-recipe-id="' + weekRecipe.id.toString() + '" data-recipe-name="' + weekRecipe.name + '" data-recipe-type="' + weekRecipe.type + '"><i class="fas fa-utensils"></i></a>'
} }
$(".fc-header-toolbar .fc-center").html("<h4>" + weekCostsHtml + weekRecipeOrderMissingButtonHtml + weekRecipeConsumeButtonHtml + "</h4>"); $scope(".fc-header-toolbar .fc-center").html("<h4>" + weekCostsHtml + weekRecipeOrderMissingButtonHtml + weekRecipeConsumeButtonHtml + "</h4>");
}, },
eventRender: function(info) eventRender: function(info)
{ {
@ -129,7 +132,7 @@
var dayRecipe = internalRecipes.find(elem => elem.name == dayRecipeName); var dayRecipe = internalRecipes.find(elem => elem.name == dayRecipeName);
var dayRecipeResolved = recipesResolved.find(elem => elem.recipe_id == dayRecipe.id); var dayRecipeResolved = recipesResolved.find(elem => elem.recipe_id == dayRecipe.id);
if (!$("#day-summary-" + dayRecipeName).length) // This runs for every event/recipe, so maybe multiple times per day, so only add the day summary once if (!$scope("#day-summary-" + dayRecipeName).length) // This runs for every event/recipe, so maybe multiple times per day, so only add the day summary once
{ {
if (dayRecipe != null) if (dayRecipe != null)
{ {
@ -141,7 +144,7 @@
{ {
costsAndCaloriesPerDay = '<h5 class="small text-truncate"><span class="locale-number locale-number-generic">' + dayRecipeResolved.calories + '</span> kcal ' + __t('per day') + '<h5>'; costsAndCaloriesPerDay = '<h5 class="small text-truncate"><span class="locale-number locale-number-generic">' + dayRecipeResolved.calories + '</span> kcal ' + __t('per day') + '<h5>';
} }
$(".fc-day-header[data-date='" + dayRecipeName + "']").append('<h5 id="day-summary-' + dayRecipeName + '" class="small text-truncate border-top pt-1 pb-0">' + costsAndCaloriesPerDay + '</h5>'); $scope(".fc-day-header[data-date='" + dayRecipeName + "']").append('<h5 id="day-summary-' + dayRecipeName + '" class="small text-truncate border-top pt-1 pb-0">' + costsAndCaloriesPerDay + '</h5>');
} }
} }
} }
@ -320,92 +323,92 @@
calendar.gotoDate(GetUriParam("week")); calendar.gotoDate(GetUriParam("week"));
} }
$(document).on("click", ".add-recipe-button", function(e) top.on("click", ".add-recipe-button", function(e)
{ {
var day = $(this).parent().parent().data("date"); var day = $(this).parent().parent().data("date");
$("#add-recipe-modal-title").text(__t("Add recipe on %s", day.toString())); $scope("#add-recipe-modal-title").text(__t("Add recipe on %s", day.toString()));
$("#day").val(day.toString()); $scope("#day").val(day.toString());
Grocy.Components.RecipePicker.Clear(); Grocy.Components.RecipePicker.Clear();
$("#add-recipe-modal").modal("show"); $scope("#add-recipe-modal").modal("show");
Grocy.FrontendHelpers.ValidateForm("add-recipe-form"); Grocy.FrontendHelpers.ValidateForm("add-recipe-form");
Grocy.IsMealPlanEntryEditAction = false; Grocy.IsMealPlanEntryEditAction = false;
}); });
$(document).on("click", ".add-note-button", function(e) top.on("click", ".add-note-button", function(e)
{ {
var day = $(this).parent().parent().parent().data("date"); var day = $(this).parent().parent().parent().data("date");
$("#add-note-modal-title").text(__t("Add note on %s", day.toString())); $scope("#add-note-modal-title").text(__t("Add note on %s", day.toString()));
$("#day").val(day.toString()); $scope("#day").val(day.toString());
$("#note").val(""); $scope("#note").val("");
$("#add-note-modal").modal("show"); $scope("#add-note-modal").modal("show");
Grocy.FrontendHelpers.ValidateForm("add-note-form"); Grocy.FrontendHelpers.ValidateForm("add-note-form");
Grocy.IsMealPlanEntryEditAction = false; Grocy.IsMealPlanEntryEditAction = false;
}); });
$(document).on("click", ".add-product-button", function(e) top.on("click", ".add-product-button", function(e)
{ {
var day = $(this).parent().parent().parent().data("date"); var day = $(this).parent().parent().parent().data("date");
$("#add-product-modal-title").text(__t("Add product on %s", day.toString())); $scope("#add-product-modal-title").text(__t("Add product on %s", day.toString()));
$("#day").val(day.toString()); $scope("#day").val(day.toString());
Grocy.Components.ProductPicker.Clear(); Grocy.Components.ProductPicker.Clear();
$("#add-product-modal").modal("show"); $scope("#add-product-modal").modal("show");
Grocy.FrontendHelpers.ValidateForm("add-product-form"); Grocy.FrontendHelpers.ValidateForm("add-product-form");
Grocy.IsMealPlanEntryEditAction = false; Grocy.IsMealPlanEntryEditAction = false;
}); });
$(document).on("click", ".edit-meal-plan-entry-button", function(e) top.on("click", ".edit-meal-plan-entry-button", function(e)
{ {
var mealPlanEntry = JSON.parse($(this).parents(".fc-h-event:first").attr("data-meal-plan-entry")); var mealPlanEntry = JSON.parse($(this).parents(".fc-h-event:first").attr("data-meal-plan-entry"));
if (mealPlanEntry.type == "recipe") if (mealPlanEntry.type == "recipe")
{ {
$("#add-recipe-modal-title").text(__t("Edit recipe on %s", mealPlanEntry.day.toString())); $scope("#add-recipe-modal-title").text(__t("Edit recipe on %s", mealPlanEntry.day.toString()));
$("#day").val(mealPlanEntry.day.toString()); $scope("#day").val(mealPlanEntry.day.toString());
$("#recipe_servings").val(mealPlanEntry.recipe_servings); $scope("#recipe_servings").val(mealPlanEntry.recipe_servings);
Grocy.Components.RecipePicker.SetId(mealPlanEntry.recipe_id); Grocy.Components.RecipePicker.SetId(mealPlanEntry.recipe_id);
$("#add-recipe-modal").modal("show"); $scope("#add-recipe-modal").modal("show");
Grocy.FrontendHelpers.ValidateForm("add-recipe-form"); Grocy.FrontendHelpers.ValidateForm("add-recipe-form");
} }
else if (mealPlanEntry.type == "product") else if (mealPlanEntry.type == "product")
{ {
$("#add-product-modal-title").text(__t("Edit product on %s", mealPlanEntry.day.toString())); $scope("#add-product-modal-title").text(__t("Edit product on %s", mealPlanEntry.day.toString()));
$("#day").val(mealPlanEntry.day.toString()); $scope("#day").val(mealPlanEntry.day.toString());
Grocy.Components.ProductPicker.SetId(mealPlanEntry.product_id); Grocy.Components.ProductPicker.SetId(mealPlanEntry.product_id);
$("#add-product-modal").modal("show"); $scope("#add-product-modal").modal("show");
Grocy.FrontendHelpers.ValidateForm("add-product-form"); Grocy.FrontendHelpers.ValidateForm("add-product-form");
Grocy.Components.ProductPicker.GetPicker().trigger("change"); Grocy.Components.ProductPicker.GetPicker().trigger("change");
} }
else if (mealPlanEntry.type == "note") else if (mealPlanEntry.type == "note")
{ {
$("#add-note-modal-title").text(__t("Edit note on %s", mealPlanEntry.day.toString())); $scope("#add-note-modal-title").text(__t("Edit note on %s", mealPlanEntry.day.toString()));
$("#day").val(mealPlanEntry.day.toString()); $scope("#day").val(mealPlanEntry.day.toString());
$("#note").val(mealPlanEntry.note); $scope("#note").val(mealPlanEntry.note);
$("#add-note-modal").modal("show"); $scope("#add-note-modal").modal("show");
Grocy.FrontendHelpers.ValidateForm("add-note-form"); Grocy.FrontendHelpers.ValidateForm("add-note-form");
} }
Grocy.IsMealPlanEntryEditAction = true; Grocy.IsMealPlanEntryEditAction = true;
Grocy.MealPlanEntryEditObjectId = mealPlanEntry.id; Grocy.MealPlanEntryEditObjectId = mealPlanEntry.id;
}); });
$("#add-recipe-modal").on("shown.bs.modal", function(e) $scope("#add-recipe-modal").on("shown.bs.modal", function(e)
{ {
Grocy.Components.RecipePicker.GetInputElement().focus(); Grocy.Components.RecipePicker.GetInputElement().focus();
}) })
$("#add-note-modal").on("shown.bs.modal", function(e) $scope("#add-note-modal").on("shown.bs.modal", function(e)
{ {
$("#note").focus(); $scope("#note").focus();
}) })
$("#add-product-modal").on("shown.bs.modal", function(e) $scope("#add-product-modal").on("shown.bs.modal", function(e)
{ {
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
}) })
$(document).on("click", ".remove-recipe-button, .remove-note-button, .remove-product-button", function(e) top.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")); var mealPlanEntry = JSON.parse($(this).parents(".fc-h-event:first").attr("data-meal-plan-entry"));
@ -421,11 +424,11 @@
); );
}); });
$('#save-add-recipe-button').on('click', function(e) $scope('#save-add-recipe-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
@ -437,7 +440,7 @@
if (Grocy.IsMealPlanEntryEditAction) if (Grocy.IsMealPlanEntryEditAction)
{ {
Grocy.Api.Put('objects/meal_plan/' + Grocy.MealPlanEntryEditObjectId.toString(), $('#add-recipe-form').serializeJSON(), Grocy.Api.Put('objects/meal_plan/' + Grocy.MealPlanEntryEditObjectId.toString(), $scope('#add-recipe-form').serializeJSON(),
function(result) function(result)
{ {
window.location.reload(); window.location.reload();
@ -450,7 +453,7 @@
} }
else else
{ {
Grocy.Api.Post('objects/meal_plan', $('#add-recipe-form').serializeJSON(), Grocy.Api.Post('objects/meal_plan', $scope('#add-recipe-form').serializeJSON(),
function(result) function(result)
{ {
window.location.reload(); window.location.reload();
@ -463,11 +466,11 @@
} }
}); });
$('#save-add-note-button').on('click', function(e) $scope('#save-add-note-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
@ -477,8 +480,8 @@
return false; return false;
} }
var jsonData = $('#add-note-form').serializeJSON(); var jsonData = $scope('#add-note-form').serializeJSON();
jsonData.day = $("#day").val(); jsonData.day = $scope("#day").val();
if (Grocy.IsMealPlanEntryEditAction) if (Grocy.IsMealPlanEntryEditAction)
{ {
@ -509,11 +512,11 @@
}); });
$('#save-add-product-button').on('click', function(e) $scope('#save-add-product-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
@ -523,8 +526,8 @@
return false; return false;
} }
var jsonData = $('#add-product-form').serializeJSON(); var jsonData = $scope('#add-product-form').serializeJSON();
jsonData.day = $("#day").val(); jsonData.day = $scope("#day").val();
delete jsonData.display_amount; delete jsonData.display_amount;
jsonData.product_amount = jsonData.amount; jsonData.product_amount = jsonData.amount;
delete jsonData.amount; delete jsonData.amount;
@ -559,7 +562,7 @@
} }
}); });
$('#add-recipe-form input').keydown(function(event) $scope('#add-recipe-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -571,12 +574,12 @@
} }
else else
{ {
$("#save-add-recipe-button").click(); $scope("#save-add-recipe-button").click();
} }
} }
}); });
$('#add-product-form input').keydown(function(event) $scope('#add-product-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -588,12 +591,12 @@
} }
else else
{ {
$("#save-add-product-button").click(); $scope("#save-add-product-button").click();
} }
} }
}); });
$(document).on("keydown", "#servings", function(event) top.on("keydown", "#servings", function(event)
{ {
if (event.key === 13) //Enter if (event.key === 13) //Enter
{ {
@ -605,21 +608,21 @@
} }
else else
{ {
$("#save-add-recipe-button").click(); $scope("#save-add-recipe-button").click();
} }
} }
}); });
$(document).on('click', '.recipe-order-missing-button', function(e) top.on('click', '.recipe-order-missing-button', function(e)
{ {
// Remove the focus from the current button // Remove the focus from the current button
// to prevent that the tooltip stays until clicked anywhere else // to prevent that the tooltip stays until clicked anywhere else
document.activeElement.blur(); document.activeElement.blur();
var objectName = $(e.currentTarget).attr('data-recipe-name'); var objectName = $scope(e.currentTarget).attr('data-recipe-name');
var objectId = $(e.currentTarget).attr('data-recipe-id'); var objectId = $scope(e.currentTarget).attr('data-recipe-id');
var button = $(this); var button = $(this);
var servings = $(e.currentTarget).attr('data-mealplan-servings'); var servings = $scope(e.currentTarget).attr('data-mealplan-servings');
bootbox.confirm({ bootbox.confirm({
message: __t('Are you sure to put all missing ingredients for recipe "%s" on the shopping list?', objectName), message: __t('Are you sure to put all missing ingredients for recipe "%s" on the shopping list?', objectName),
@ -674,7 +677,7 @@
}); });
}); });
$(document).on('click', '.product-consume-button', function(e) top.on('click', '.product-consume-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -684,8 +687,8 @@
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
var productId = $(e.currentTarget).attr('data-product-id'); var productId = $scope(e.currentTarget).attr('data-product-id');
var consumeAmount = parseFloat($(e.currentTarget).attr('data-product-amount')); var consumeAmount = parseFloat($scope(e.currentTarget).attr('data-product-amount'));
Grocy.Api.Post('stock/products/' + productId + '/consume', { 'amount': consumeAmount, 'spoiled': false }, Grocy.Api.Post('stock/products/' + productId + '/consume', { 'amount': consumeAmount, 'spoiled': false },
function(bookingResponse) function(bookingResponse)
@ -714,15 +717,15 @@
); );
}); });
$(document).on('click', '.recipe-consume-button', function(e) top.on('click', '.recipe-consume-button', function(e)
{ {
// Remove the focus from the current button // Remove the focus from the current button
// to prevent that the tooltip stays until clicked anywhere else // to prevent that the tooltip stays until clicked anywhere else
document.activeElement.blur(); document.activeElement.blur();
var objectName = $(e.currentTarget).attr('data-recipe-name'); var objectName = $scope(e.currentTarget).attr('data-recipe-name');
var objectId = $(e.currentTarget).attr('data-recipe-id'); var objectId = $scope(e.currentTarget).attr('data-recipe-id');
var servings = $(e.currentTarget).attr('data-mealplan-servings'); var servings = $scope(e.currentTarget).attr('data-mealplan-servings');
bootbox.confirm({ 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), 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),
@ -772,14 +775,14 @@
}); });
}); });
$(document).on("click", ".recipe-popup-button", function(e) top.on("click", ".recipe-popup-button", function(e)
{ {
// Remove the focus from the current button // Remove the focus from the current button
// to prevent that the tooltip stays until clicked anywhere else // to prevent that the tooltip stays until clicked anywhere else
document.activeElement.blur(); document.activeElement.blur();
var objectId = $(e.currentTarget).attr('data-recipe-id'); var objectId = $scope(e.currentTarget).attr('data-recipe-id');
var servings = $(e.currentTarget).attr('data-mealplan-servings'); var servings = $scope(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 // 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 }, Grocy.Api.Put('objects/recipes/' + objectId, { "desired_servings": servings },
@ -813,7 +816,7 @@
{ {
// Automatically switch the calendar to "basicDay" view on small screens // Automatically switch the calendar to "basicDay" view on small screens
// and to "basicWeek" otherwise // and to "basicWeek" otherwise
if ($(window).width() < 768) if (viewport.width() < 768)
{ {
calendar.changeView("dayGridDay"); calendar.changeView("dayGridDay");
} }
@ -825,7 +828,7 @@
Grocy.Components.ProductPicker.GetPicker().on('change', function(e) Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{ {
var productId = $(e.target).val(); var productId = $scope(e.target).val();
if (productId) if (productId)
{ {
@ -834,12 +837,12 @@
{ {
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id); Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
$('#display_amount').val(1); $scope('#display_amount').val(1);
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
$('#display_amount').focus(); $scope('#display_amount').focus();
$('#display_amount').select(); $scope('#display_amount').select();
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('add-product-form'); Grocy.FrontendHelpers.ValidateForm('add-product-form');
}, },
function(xhr) function(xhr)
@ -852,16 +855,16 @@
Grocy.Components.RecipePicker.GetPicker().on('change', function(e) Grocy.Components.RecipePicker.GetPicker().on('change', function(e)
{ {
var recipeId = $(e.target).val(); var recipeId = $scope(e.target).val();
if (recipeId) if (recipeId)
{ {
Grocy.Api.Get('objects/recipes/' + recipeId, Grocy.Api.Get('objects/recipes/' + recipeId,
function(recipe) function(recipe)
{ {
$("#recipe_servings").val(recipe.base_servings); $scope("#recipe_servings").val(recipe.base_servings);
$("#recipe_servings").focus(); $scope("#recipe_servings").focus();
$("#recipe_servings").select(); $scope("#recipe_servings").select();
}, },
function(xhr) function(xhr)
{ {

View File

@ -1,27 +1,29 @@
function productbarcodeformView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function productbarcodeformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
var top = scope != null ? $(scope) : $(document);
if (scope != null) if (scope != null)
{ {
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use('barcodescanner'); Grocy.Use('barcodescanner');
Grocy.Use("productamountpicker"); Grocy.Use("productamountpicker");
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
$('#save-barcode-button').on('click', function(e) $scope('#save-barcode-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#barcode-form').serializeJSON(); var jsonData = $scope('#barcode-form').serializeJSON();
jsonData.amount = jsonData.display_amount; jsonData.amount = jsonData.display_amount;
delete jsonData.display_amount; delete jsonData.display_amount;
@ -63,22 +65,22 @@
} }
}); });
$('#barcode').on('keyup', function(e) $scope('#barcode').on('keyup', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('barcode-form'); Grocy.FrontendHelpers.ValidateForm('barcode-form');
}); });
$('#qu_id').on('change', function(e) $scope('#qu_id').on('change', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('barcode-form'); Grocy.FrontendHelpers.ValidateForm('barcode-form');
}); });
$('#display_amount').on('keyup', function(e) $scope('#display_amount').on('keyup', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('barcode-form'); Grocy.FrontendHelpers.ValidateForm('barcode-form');
}); });
$('#barcode-form input').keydown(function(event) $scope('#barcode-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -90,7 +92,7 @@
} }
else else
{ {
$('#save-barcode-button').click(); $scope('#save-barcode-button').click();
} }
} }
}); });
@ -98,24 +100,26 @@
Grocy.Components.ProductAmountPicker.Reload(Grocy.EditObjectProduct.id, Grocy.EditObjectProduct.qu_id_purchase); Grocy.Components.ProductAmountPicker.Reload(Grocy.EditObjectProduct.id, Grocy.EditObjectProduct.qu_id_purchase);
if (Grocy.EditMode == "edit") if (Grocy.EditMode == "edit")
{ {
$("#display_amount").val(Grocy.EditObject.amount); $scope("#display_amount").val(Grocy.EditObject.amount);
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
Grocy.Components.ProductAmountPicker.SetQuantityUnit(Grocy.EditObject.qu_id); Grocy.Components.ProductAmountPicker.SetQuantityUnit(Grocy.EditObject.qu_id);
} }
Grocy.FrontendHelpers.ValidateForm('barcode-form'); Grocy.FrontendHelpers.ValidateForm('barcode-form');
$('#barcode').focus(); $scope('#barcode').focus();
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
Grocy.Components.UserfieldsForm.Load() Grocy.Components.UserfieldsForm.Load()
$(document).on("Grocy.BarcodeScanned", function(e, barcode, target) top.on("Grocy.BarcodeScanned", function(e, barcode, target)
{ {
if (target !== "#barcode") if (target !== "#barcode")
{ {
return; return;
} }
$("#barcode").val(barcode); $scope("#barcode").val(barcode);
}); });
} }
window.productbarcodeformView = productbarcodeformView

View File

@ -1,13 +1,15 @@
function productformView(Grocy, scope = null) import { BoolVal } from '../helpers/extensions';
function productformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
var top = scope != null ? $(scope) : $(document);
if (scope != null) if (scope != null)
{ {
$scope = $(scope).find; $scope = $(scope).find;
} }
import { BoolVal } from '../helpers/extensions';
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
Grocy.Use("shoppinglocationpicker"); Grocy.Use("shoppinglocationpicker");
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
@ -20,7 +22,7 @@
{ {
if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteProductPictureOnSave) if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteProductPictureOnSave)
{ {
Grocy.Api.UploadFile($("#product-picture")[0].files[0], 'productpictures', jsonData.picture_file_name, Grocy.Api.UploadFile($scope("#product-picture")[0].files[0], 'productpictures', jsonData.picture_file_name,
(result) => (result) =>
{ {
if (Grocy.ProductEditFormRedirectUri == "reload") if (Grocy.ProductEditFormRedirectUri == "reload")
@ -38,7 +40,7 @@
{ {
if (GetUriParam("flow") !== undefined) if (GetUriParam("flow") !== undefined)
{ {
window.location.href = U(returnTo) + '&product-name=' + encodeURIComponent($('#name').val()); window.location.href = U(returnTo) + '&product-name=' + encodeURIComponent($scope('#name').val());
} }
else else
{ {
@ -76,7 +78,7 @@
{ {
if (GetUriParam("flow") !== undefined) if (GetUriParam("flow") !== undefined)
{ {
window.location.href = U(returnTo) + '&product-name=' + encodeURIComponent($('#name').val()); window.location.href = U(returnTo) + '&product-name=' + encodeURIComponent($scope('#name').val());
} }
else else
{ {
@ -91,11 +93,11 @@
}); });
} }
$('.save-product-button').on('click', function(e) $scope('.save-product-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
var jsonData = $('#product-form').serializeJSON(); var jsonData = $scope('#product-form').serializeJSON();
var parentProductId = jsonData.product_id; var parentProductId = jsonData.product_id;
delete jsonData.product_id; delete jsonData.product_id;
jsonData.parent_product_id = parentProductId; jsonData.parent_product_id = parentProductId;
@ -106,13 +108,13 @@
jsonData.parent_product_id = null; jsonData.parent_product_id = null;
} }
if ($("#product-picture")[0].files.length > 0) if ($scope("#product-picture")[0].files.length > 0)
{ {
var someRandomStuff = Math.random().toString(36).substring(2, 100) + Math.random().toString(36).substring(2, 100); 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; jsonData.picture_file_name = someRandomStuff + $scope("#product-picture")[0].files[0].name;
} }
const location = $(e.currentTarget).attr('data-location') == 'return' ? '/products?product=' : '/product/'; const location = $scope(e.currentTarget).attr('data-location') == 'return' ? '/products?product=' : '/product/';
if (Grocy.EditMode == 'create') if (Grocy.EditMode == 'create')
{ {
@ -160,7 +162,7 @@
{ {
if (productDetails.last_purchased == null) if (productDetails.last_purchased == null)
{ {
$('#qu_id_stock').removeAttr("disabled"); $scope('#qu_id_stock').removeAttr("disabled");
} }
}, },
function(xhr) function(xhr)
@ -172,65 +174,65 @@
if (GetUriParam("flow") == "InplaceNewProductWithName") if (GetUriParam("flow") == "InplaceNewProductWithName")
{ {
$('#name').val(GetUriParam("name")); $scope('#name').val(GetUriParam("name"));
$('#name').focus(); $scope('#name').focus();
} }
if (GetUriParam("flow") !== undefined || GetUriParam("returnto") !== undefined) if (GetUriParam("flow") !== undefined || GetUriParam("returnto") !== undefined)
{ {
$("#save-hint").addClass("d-none"); $scope("#save-hint").addClass("d-none");
$(".save-product-button[data-location='return']").addClass("d-none"); $scope(".save-product-button[data-location='return']").addClass("d-none");
} }
$('.input-group-qu').on('change', function(e) $scope('.input-group-qu').on('change', function(e)
{ {
var quIdPurchase = $("#qu_id_purchase").val(); var quIdPurchase = $scope("#qu_id_purchase").val();
var quIdStock = $("#qu_id_stock").val(); var quIdStock = $scope("#qu_id_stock").val();
var factor = $('#qu_factor_purchase_to_stock').val(); var factor = $scope('#qu_factor_purchase_to_stock').val();
if (factor > 1 || quIdPurchase != quIdStock) 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")))); $scope('#qu-conversion-info').text(__t('This means 1 %1$s purchased will be converted into %2$s %3$s in stock', $scope("#qu_id_purchase option:selected").text(), (1 * factor).toString(), __n((1 * factor).toString(), $scope("#qu_id_stock option:selected").text(), $scope("#qu_id_stock option:selected").data("plural-form"))));
$('#qu-conversion-info').removeClass('d-none'); $scope('#qu-conversion-info').removeClass('d-none');
} }
else else
{ {
$('#qu-conversion-info').addClass('d-none'); $scope('#qu-conversion-info').addClass('d-none');
} }
$("#tare_weight_qu_info").text($("#qu_id_stock option:selected").text()); $scope("#tare_weight_qu_info").text($scope("#qu_id_stock option:selected").text());
$("#quick_consume_qu_info").text($("#qu_id_stock option:selected").text()); $scope("#quick_consume_qu_info").text($scope("#qu_id_stock option:selected").text());
Grocy.FrontendHelpers.ValidateForm('product-form'); Grocy.FrontendHelpers.ValidateForm('product-form');
}); });
$('#product-form input').keyup(function(event) $scope('#product-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('product-form'); Grocy.FrontendHelpers.ValidateForm('product-form');
$(".input-group-qu").trigger("change"); $scope(".input-group-qu").trigger("change");
$("#product-form select").trigger("select"); $scope("#product-form select").trigger("select");
if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error
{ {
$("#qu-conversion-add-button").addClass("disabled"); $scope("#qu-conversion-add-button").addClass("disabled");
} }
else else
{ {
$("#qu-conversion-add-button").removeClass("disabled"); $scope("#qu-conversion-add-button").removeClass("disabled");
} }
if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error
{ {
$("#barcode-add-button").addClass("disabled"); $scope("#barcode-add-button").addClass("disabled");
} }
}); });
$('#location_id').change(function(event) $scope('#location_id').change(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('product-form'); Grocy.FrontendHelpers.ValidateForm('product-form');
}); });
$('#product-form input').keydown(function(event) $scope('#product-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -242,45 +244,45 @@
} }
else else
{ {
$('#save-product-button').click(); $scope('#save-product-button').click();
} }
} }
}); });
$("#enable_tare_weight_handling").on("click", function() $scope("#enable_tare_weight_handling").on("click", function()
{ {
if (this.checked) if (this.checked)
{ {
$("#tare_weight").removeAttr("disabled"); $scope("#tare_weight").removeAttr("disabled");
} }
else else
{ {
$("#tare_weight").attr("disabled", ""); $scope("#tare_weight").attr("disabled", "");
} }
Grocy.FrontendHelpers.ValidateForm("product-form"); Grocy.FrontendHelpers.ValidateForm("product-form");
}); });
$("#product-picture").on("change", function(e) $scope("#product-picture").on("change", function(e)
{ {
$("#product-picture-label").removeClass("d-none"); $scope("#product-picture-label").removeClass("d-none");
$("#product-picture-label-none").addClass("d-none"); $scope("#product-picture-label-none").addClass("d-none");
$("#delete-current-product-picture-on-save-hint").addClass("d-none"); $scope("#delete-current-product-picture-on-save-hint").addClass("d-none");
$("#current-product-picture").addClass("d-none"); $scope("#current-product-picture").addClass("d-none");
Grocy.DeleteProductPictureOnSave = false; Grocy.DeleteProductPictureOnSave = false;
}); });
Grocy.DeleteProductPictureOnSave = false; Grocy.DeleteProductPictureOnSave = false;
$("#delete-current-product-picture-button").on("click", function(e) $scope("#delete-current-product-picture-button").on("click", function(e)
{ {
Grocy.DeleteProductPictureOnSave = true; Grocy.DeleteProductPictureOnSave = true;
$("#current-product-picture").addClass("d-none"); $scope("#current-product-picture").addClass("d-none");
$("#delete-current-product-picture-on-save-hint").removeClass("d-none"); $scope("#delete-current-product-picture-on-save-hint").removeClass("d-none");
$("#product-picture-label").addClass("d-none"); $scope("#product-picture-label").addClass("d-none");
$("#product-picture-label-none").removeClass("d-none"); $scope("#product-picture-label-none").removeClass("d-none");
}); });
var quConversionsTable = $('#qu-conversions-table-products').DataTable({ var quConversionsTable = $scope('#qu-conversions-table-products').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
"orderFixed": [[4, 'asc']], "orderFixed": [[4, 'asc']],
'columnDefs': [ 'columnDefs': [
@ -293,10 +295,10 @@
dataSrc: 4 dataSrc: 4
} }
}); });
$('#qu-conversions-table-products tbody').removeClass("d-none"); $scope('#qu-conversions-table-products tbody').removeClass("d-none");
quConversionsTable.columns.adjust().draw(); quConversionsTable.columns.adjust().draw();
var barcodeTable = $('#barcode-table').DataTable({ var barcodeTable = $scope('#barcode-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
"orderFixed": [[1, 'asc']], "orderFixed": [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
@ -306,16 +308,16 @@
{ 'visible': false, 'targets': 6 } { 'visible': false, 'targets': 6 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#barcode-table tbody').removeClass("d-none"); $scope('#barcode-table tbody').removeClass("d-none");
barcodeTable.columns.adjust().draw(); barcodeTable.columns.adjust().draw();
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
$("#name").trigger("keyup"); $scope("#name").trigger("keyup");
$('#name').focus(); $scope('#name').focus();
$('.input-group-qu').trigger('change'); $scope('.input-group-qu').trigger('change');
Grocy.FrontendHelpers.ValidateForm('product-form'); Grocy.FrontendHelpers.ValidateForm('product-form');
$(document).on('click', '.stockentry-grocycode-product-label-print', function(e) top.on('click', '.stockentry-grocycode-product-label-print', function(e)
{ {
e.preventDefault(); e.preventDefault();
document.activeElement.blur(); document.activeElement.blur();
@ -330,85 +332,37 @@
}); });
}); });
$(document).on('click', '.qu-conversion-delete-button', function(e) Grocy.FrontendHelpers.MakeDeleteConfirmBox(
{ 'Are you sure to remove this conversion?',
var objectId = $(e.currentTarget).attr('data-qu-conversion-id'); '.qu-conversion-delete-button',
'data-qu-conversion-id',
bootbox.confirm({ 'data-qu-conversion-id',
message: __t('Are you sure to remove this conversion?'), 'objects/quantity_unit_conversions/',
closeButton: false, (result, id, name) =>
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"; Grocy.ProductEditFormRedirectUri = "reload";
$('#save-product-button').click(); $scope('#save-product-button').click();
},
function(xhr)
{
console.error(xhr);
} }
); );
}
}
});
});
$(document).on('click', '.barcode-delete-button', function(e) Grocy.FrontendHelpers.MakeDeleteConfirmBox(
{ 'Are you sure to remove this barcode?',
var objectId = $(e.currentTarget).attr('data-barcode-id'); '.barcode-delete-button',
'data-barcode-id',
bootbox.confirm({ 'data-barcode-id',
message: __t('Are you sure to remove this barcode?'), 'objects/product_barcodes/',
closeButton: false, (result, id, name) =>
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"; Grocy.ProductEditFormRedirectUri = "reload";
$('#save-product-button').click(); $scope('#save-product-button').click();
},
function(xhr)
{
console.error(xhr);
} }
); )
}
}
});
});
$('#qu_id_stock').change(function(e) $scope('#qu_id_stock').change(function(e)
{ {
// Preset QU purchase with stock QU if unset // Preset QU purchase with stock QU if unset
var quIdStock = $('#qu_id_stock'); var quIdStock = $scope('#qu_id_stock');
var quIdPurchase = $('#qu_id_purchase'); var quIdPurchase = $scope('#qu_id_purchase');
if (quIdPurchase[0].selectedIndex === 0 && quIdStock[0].selectedIndex !== 0) if (quIdPurchase[0].selectedIndex === 0 && quIdStock[0].selectedIndex !== 0)
{ {
@ -417,19 +371,19 @@
} }
}); });
$('#allow_label_per_unit').on('change', function() $scope('#allow_label_per_unit').on('change', function()
{ {
if (this.checked) if (this.checked)
{ {
$('#label-option-per-unit').prop("disabled", false); $scope('#label-option-per-unit').prop("disabled", false);
} }
else else
{ {
if ($('#default_print_stock_label').val() == "2") if ($scope('#default_print_stock_label').val() == "2")
{ {
$("#default_print_stock_label").val("0"); $scope("#default_print_stock_label").val("0");
} }
$('#label-option-per-unit').prop("disabled", true); $scope('#label-option-per-unit').prop("disabled", true);
} }
}); });
@ -454,43 +408,43 @@
} }
if (sourceProduct.description != null) if (sourceProduct.description != null)
{ {
$("#description").summernote("pasteHTML", sourceProduct.description); $scope("#description").summernote("pasteHTML", sourceProduct.description);
} }
$("#location_id").val(sourceProduct.location_id); $scope("#location_id").val(sourceProduct.location_id);
if (sourceProduct.shopping_location_id != null) if (sourceProduct.shopping_location_id != null)
{ {
Grocy.Components.ShoppingLocationPicker.SetId(sourceProduct.shopping_location_id); Grocy.Components.ShoppingLocationPicker.SetId(sourceProduct.shopping_location_id);
} }
$("#min_stock_amount").val(sourceProduct.min_stock_amount); $scope("#min_stock_amount").val(sourceProduct.min_stock_amount);
if (BoolVal(sourceProduct.cumulate_min_stock_amount_of_sub_products)) if (BoolVal(sourceProduct.cumulate_min_stock_amount_of_sub_products))
{ {
$("#cumulate_min_stock_amount_of_sub_products").prop("checked", true); $scope("#cumulate_min_stock_amount_of_sub_products").prop("checked", true);
} }
$("#default_best_before_days").val(sourceProduct.default_best_before_days); $scope("#default_best_before_days").val(sourceProduct.default_best_before_days);
$("#default_best_before_days_after_open").val(sourceProduct.default_best_before_days_after_open); $scope("#default_best_before_days_after_open").val(sourceProduct.default_best_before_days_after_open);
if (sourceProduct.product_group_id != null) if (sourceProduct.product_group_id != null)
{ {
$("#product_group_id").val(sourceProduct.product_group_id); $scope("#product_group_id").val(sourceProduct.product_group_id);
} }
$("#qu_id_stock").val(sourceProduct.qu_id_stock); $scope("#qu_id_stock").val(sourceProduct.qu_id_stock);
$("#qu_id_purchase").val(sourceProduct.qu_id_purchase); $scope("#qu_id_purchase").val(sourceProduct.qu_id_purchase);
$("#qu_factor_purchase_to_stock").val(sourceProduct.qu_factor_purchase_to_stock); $scope("#qu_factor_purchase_to_stock").val(sourceProduct.qu_factor_purchase_to_stock);
if (BoolVal(sourceProduct.enable_tare_weight_handling)) if (BoolVal(sourceProduct.enable_tare_weight_handling))
{ {
$("#enable_tare_weight_handling").prop("checked", true); $scope("#enable_tare_weight_handling").prop("checked", true);
} }
$("#tare_weight").val(sourceProduct.tare_weight); $scope("#tare_weight").val(sourceProduct.tare_weight);
if (BoolVal(sourceProduct.not_check_stock_fulfillment_for_recipes)) if (BoolVal(sourceProduct.not_check_stock_fulfillment_for_recipes))
{ {
$("#not_check_stock_fulfillment_for_recipes").prop("checked", true); $scope("#not_check_stock_fulfillment_for_recipes").prop("checked", true);
} }
if (sourceProduct.calories != null) if (sourceProduct.calories != null)
{ {
$("#calories").val(sourceProduct.calories); $scope("#calories").val(sourceProduct.calories);
} }
$("#default_best_before_days_after_freezing").val(sourceProduct.default_best_before_days_after_freezing); $scope("#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); $scope("#default_best_before_days_after_thawing").val(sourceProduct.default_best_before_days_after_thawing);
$("#quick_consume_amount").val(sourceProduct.quick_consume_amount); $scope("#quick_consume_amount").val(sourceProduct.quick_consume_amount);
Grocy.FrontendHelpers.ValidateForm('product-form'); Grocy.FrontendHelpers.ValidateForm('product-form');
}, },
@ -504,20 +458,22 @@
{ {
if (Grocy.UserSettings.product_presets_location_id.toString() !== '-1') if (Grocy.UserSettings.product_presets_location_id.toString() !== '-1')
{ {
$("#location_id").val(Grocy.UserSettings.product_presets_location_id); $scope("#location_id").val(Grocy.UserSettings.product_presets_location_id);
} }
if (Grocy.UserSettings.product_presets_product_group_id.toString() !== '-1') if (Grocy.UserSettings.product_presets_product_group_id.toString() !== '-1')
{ {
$("#product_group_id").val(Grocy.UserSettings.product_presets_product_group_id); $scope("#product_group_id").val(Grocy.UserSettings.product_presets_product_group_id);
} }
if (Grocy.UserSettings.product_presets_qu_id.toString() !== '-1') if (Grocy.UserSettings.product_presets_qu_id.toString() !== '-1')
{ {
$("select.input-group-qu").val(Grocy.UserSettings.product_presets_qu_id); $scope("select.input-group-qu").val(Grocy.UserSettings.product_presets_qu_id);
} }
} }
Grocy.FrontendHelpers.ValidateForm("product-form"); Grocy.FrontendHelpers.ValidateForm("product-form");
} }
window.productformView = productformView

View File

@ -1,4 +1,6 @@
function productgroupformView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function productgroupformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,20 +8,18 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
$('#save-product-group-button').on('click', function(e) $scope('#save-product-group-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#product-group-form').serializeJSON(); var jsonData = $scope('#product-group-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("product-group-form"); Grocy.FrontendHelpers.BeginUiBusy("product-group-form");
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
@ -59,12 +59,12 @@
} }
}); });
$('#product-group-form input').keyup(function(event) $scope('#product-group-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('product-group-form'); Grocy.FrontendHelpers.ValidateForm('product-group-form');
}); });
$('#product-group-form input').keydown(function(event) $scope('#product-group-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -76,13 +76,15 @@
} }
else else
{ {
$('#save-product-group-button').click(); $scope('#save-product-group-button').click();
} }
} }
}); });
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
$('#name').focus(); $scope('#name').focus();
Grocy.FrontendHelpers.ValidateForm('product-group-form'); Grocy.FrontendHelpers.ValidateForm('product-group-form');
} }
window.productgroupformView = productgroupformView

View File

@ -6,14 +6,14 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var groupsTable = $('#productgroups-table').DataTable({ var groupsTable = $scope('#productgroups-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#productgroups-table tbody').removeClass("d-none"); $scope('#productgroups-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(groupsTable); Grocy.FrontendHelpers.InitDataTable(groupsTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete product group "%s"?', 'Are you sure to delete product group "%s"?',
@ -33,5 +33,4 @@
window.location.reload(); window.location.reload();
} }
}); });
} }

View File

@ -6,7 +6,7 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var productsTable = $('#products-table').DataTable({ var productsTable = $scope('#products-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
@ -15,20 +15,20 @@
{ "type": "html-num-fmt", "targets": 3 } { "type": "html-num-fmt", "targets": 3 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#products-table tbody').removeClass("d-none"); $scope('#products-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(productsTable, null, function() Grocy.FrontendHelpers.InitDataTable(productsTable, null, function()
{ {
$("#search").val(""); $scope("#search").val("");
productsTable.search("").draw(); productsTable.search("").draw();
$("#show-disabled").prop('checked', false); $scope("#show-disabled").prop('checked', false);
}) })
Grocy.FrontendHelpers.MakeFilterForColumn("#product-group-filter", 6, productsTable); Grocy.FrontendHelpers.MakeFilterForColumn("#product-group-filter", 6, productsTable);
if (typeof GetUriParam("product-group") !== "undefined") if (typeof GetUriParam("product-group") !== "undefined")
{ {
$("#product-group-filter").val(GetUriParam("product-group")); $scope("#product-group-filter").val(GetUriParam("product-group"));
$("#product-group-filter").trigger("change"); $scope("#product-group-filter").trigger("change");
} }
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
@ -45,7 +45,7 @@
'/products' '/products'
); );
$("#show-disabled").change(function() $scope("#show-disabled").change(function()
{ {
if (this.checked) if (this.checked)
{ {
@ -59,22 +59,22 @@
if (GetUriParam('include_disabled')) if (GetUriParam('include_disabled'))
{ {
$("#show-disabled").prop('checked', true); $scope("#show-disabled").prop('checked', true);
} }
$(".merge-products-button").on("click", function(e) $scope(".merge-products-button").on("click", function(e)
{ {
var productId = $(e.currentTarget).attr("data-product-id"); var productId = $scope(e.currentTarget).attr("data-product-id");
$("#merge-products-keep").val(productId); $scope("#merge-products-keep").val(productId);
$("#merge-products-remove").val(""); $scope("#merge-products-remove").val("");
$("#merge-products-modal").modal("show"); $scope("#merge-products-modal").modal("show");
}); });
$("#merge-products-save-button").on("click", function() $scope("#merge-products-save-button").on("click", function()
{ {
var productIdToKeep = $("#merge-products-keep").val(); var productIdToKeep = $scope("#merge-products-keep").val();
var productIdToRemove = $("#merge-products-remove").val(); var productIdToRemove = $scope("#merge-products-remove").val();
Grocy.Api.Post("stock/products/" + productIdToKeep.toString() + "/merge/" + productIdToRemove.toString(), {}, Grocy.Api.Post("stock/products/" + productIdToKeep.toString() + "/merge/" + productIdToRemove.toString(), {},
function(result) function(result)

View File

@ -1,4 +1,7 @@
function purchaseView(Grocy, scope = null) import { BoolVal } from '../helpers/extensions';
import { WindowMessageBag } from '../helpers/messagebag';
function purchaseView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,9 +9,6 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { BoolVal } from '../helpers/extensions';
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("datetimepicker"); Grocy.Use("datetimepicker");
if (Grocy.UserSettings.show_purchased_date_on_purchase) if (Grocy.UserSettings.show_purchased_date_on_purchase)
{ {
@ -22,21 +22,21 @@
var CurrentProductDetails; var CurrentProductDetails;
$('#save-purchase-button').on('click', function(e) $scope('#save-purchase-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonForm = $('#purchase-form').serializeJSON(); var jsonForm = $scope('#purchase-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("purchase-form"); Grocy.FrontendHelpers.BeginUiBusy("purchase-form");
@ -59,8 +59,8 @@
amount -= parseFloat(productDetails.product.tare_weight); amount -= parseFloat(productDetails.product.tare_weight);
} }
var price = parseFloat(jsonForm.price * $("#qu_id option:selected").attr("data-qu-factor")).toFixed(Grocy.UserSettings.stock_decimal_places_prices); var price = parseFloat(jsonForm.price * $scope("#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 ($scope("input[name='price-type']:checked").val() == "total-price")
{ {
price = parseFloat(price / amount).toFixed(Grocy.UserSettings.stock_decimal_places_prices); price = parseFloat(price / amount).toFixed(Grocy.UserSettings.stock_decimal_places_prices);
} }
@ -94,9 +94,9 @@
Grocy.Api.Post('stock/products/' + jsonForm.product_id + '/add', jsonData, Grocy.Api.Post('stock/products/' + jsonForm.product_id + '/add', jsonData,
function(result) function(result)
{ {
if ($("#purchase-form").hasAttr("data-used-barcode")) if ($scope("#purchase-form").hasAttr("data-used-barcode"))
{ {
Grocy.Api.Put('objects/product_barcodes/' + $("#purchase-form").attr("data-used-barcode"), { last_price: $("#price").val() }, Grocy.Api.Put('objects/product_barcodes/' + $scope("#purchase-form").attr("data-used-barcode"), { last_price: $scope("#price").val() },
function(result) function(result)
{ }, { },
function(xhr) function(xhr)
@ -119,9 +119,9 @@
Grocy.Api.Post('objects/product_barcodes', jsonDataBarcode, Grocy.Api.Post('objects/product_barcodes', jsonDataBarcode,
function(result) function(result)
{ {
$("#flow-info-InplaceAddBarcodeToExistingProduct").addClass("d-none"); $scope("#flow-info-InplaceAddBarcodeToExistingProduct").addClass("d-none");
$('#barcode-lookup-disabled-hint').addClass('d-none'); $scope('#barcode-lookup-disabled-hint').addClass('d-none');
$('#barcode-lookup-hint').removeClass('d-none'); $scope('#barcode-lookup-hint').removeClass('d-none');
window.history.replaceState({}, document.title, U("/purchase")); window.history.replaceState({}, document.title, U("/purchase"));
}, },
function(xhr) function(xhr)
@ -186,12 +186,12 @@
} }
Grocy.Components.ProductAmountPicker.Reset(); Grocy.Components.ProductAmountPicker.Reset();
$("#purchase-form").removeAttr("data-used-barcode"); $scope("#purchase-form").removeAttr("data-used-barcode");
$("#display_amount").attr("min", Grocy.DefaultMinAmount); $scope("#display_amount").attr("min", Grocy.DefaultMinAmount);
$('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_purchase_amount)); $scope('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_purchase_amount));
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
$('#price').val(''); $scope('#price').val('');
$("#tare-weight-handling-info").addClass("d-none"); $scope("#tare-weight-handling-info").addClass("d-none");
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{ {
Grocy.Components.LocationPicker.Clear(); Grocy.Components.LocationPicker.Clear();
@ -208,9 +208,9 @@
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
Grocy.Components.ProductCard.Refresh(jsonForm.product_id); Grocy.Components.ProductCard.Refresh(jsonForm.product_id);
$('#price-hint').text(""); $scope('#price-hint').text("");
var priceTypeUnitPrice = $("#price-type-unit-price"); var priceTypeUnitPrice = $scope("#price-type-unit-price");
var priceTypeUnitPriceLabel = $("[for=" + priceTypeUnitPrice.attr("id") + "]"); var priceTypeUnitPriceLabel = $scope("[for=" + priceTypeUnitPrice.attr("id") + "]");
priceTypeUnitPriceLabel.text(__t("Unit price")); priceTypeUnitPriceLabel.text(__t("Unit price"));
Grocy.FrontendHelpers.ValidateForm('purchase-form'); Grocy.FrontendHelpers.ValidateForm('purchase-form');
@ -240,7 +240,7 @@
Grocy.UISound.BarcodeScannerBeep(); Grocy.UISound.BarcodeScannerBeep();
} }
var productId = $(e.target).val(); var productId = $scope(e.target).val();
if (productId) if (productId)
{ {
@ -253,16 +253,16 @@
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id); Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.default_quantity_unit_purchase.id); Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.default_quantity_unit_purchase.id);
$('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_purchase_amount)); $scope('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_purchase_amount));
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
if (GetUriParam("flow") === "shoppinglistitemtostock") if (GetUriParam("flow") === "shoppinglistitemtostock")
{ {
Grocy.Components.ProductAmountPicker.SetQuantityUnit(GetUriParam("quId")); Grocy.Components.ProductAmountPicker.SetQuantityUnit(GetUriParam("quId"));
$('#display_amount').val(parseFloat(GetUriParam("amount") * $("#qu_id option:selected").attr("data-qu-factor"))); $scope('#display_amount').val(parseFloat(GetUriParam("amount") * $scope("#qu_id option:selected").attr("data-qu-factor")));
} }
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{ {
@ -283,29 +283,29 @@
if (productDetails.last_price == null || productDetails.last_price == 0) if (productDetails.last_price == null || productDetails.last_price == 0)
{ {
$("#price").val("") $scope("#price").val("")
} }
else else
{ {
$('#price').val(parseFloat(productDetails.last_price / $("#qu_id option:selected").attr("data-qu-factor"))); $scope('#price').val(parseFloat(productDetails.last_price / $scope("#qu_id option:selected").attr("data-qu-factor")));
} }
var priceTypeUnitPrice = $("#price-type-unit-price"); var priceTypeUnitPrice = $scope("#price-type-unit-price");
var priceTypeUnitPriceLabel = $("[for=" + priceTypeUnitPrice.attr("id") + "]"); var priceTypeUnitPriceLabel = $scope("[for=" + priceTypeUnitPrice.attr("id") + "]");
priceTypeUnitPriceLabel.text($("#qu_id option:selected").text() + " " + __t("price")); priceTypeUnitPriceLabel.text($scope("#qu_id option:selected").text() + " " + __t("price"));
refreshPriceHint(); refreshPriceHint();
if (productDetails.product.enable_tare_weight_handling == 1) 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); var minAmount = parseFloat(productDetails.product.tare_weight) / $scope("#qu_id option:selected").attr("data-qu-factor") + parseFloat(productDetails.stock_amount);
$("#display_amount").attr("min", minAmount); $scope("#display_amount").attr("min", minAmount);
$("#tare-weight-handling-info").removeClass("d-none"); $scope("#tare-weight-handling-info").removeClass("d-none");
} }
else else
{ {
$("#display_amount").attr("min", Grocy.DefaultMinAmount); $scope("#display_amount").attr("min", Grocy.DefaultMinAmount);
$("#tare-weight-handling-info").addClass("d-none"); $scope("#tare-weight-handling-info").addClass("d-none");
} }
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
@ -314,9 +314,9 @@
{ {
if (productDetails.product.default_best_before_days == -1) if (productDetails.product.default_best_before_days == -1)
{ {
if (!$("#datetimepicker-shortcut").is(":checked")) if (!$scope("#datetimepicker-shortcut").is(":checked"))
{ {
$("#datetimepicker-shortcut").click(); $scope("#datetimepicker-shortcut").click();
} }
} }
else else
@ -328,27 +328,27 @@
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_LABELPRINTER) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_LABELPRINTER)
{ {
$("#print_stock_label").val(productDetails.product.default_print_stock_label); $scope("#print_stock_label").val(productDetails.product.default_print_stock_label);
if (productDetails.product.allow_label_per_unit) if (productDetails.product.allow_label_per_unit)
{ {
if ($('#default_print_stock_label').val() == "2") if ($scope('#default_print_stock_label').val() == "2")
{ {
$("#default_print_stock_label").val("0"); $scope("#default_print_stock_label").val("0");
} }
$('#label-option-per-unit').prop("disabled", true); $scope('#label-option-per-unit').prop("disabled", true);
} }
else else
{ {
$('#label-option-per-unit').prop("disabled", false); $scope('#label-option-per-unit').prop("disabled", false);
} }
} }
$("#display_amount").focus(); $scope("#display_amount").focus();
Grocy.FrontendHelpers.ValidateForm('purchase-form'); 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) 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(); $scope("#save-purchase-button").click();
} }
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
@ -361,14 +361,14 @@
if (barcodeResult != null) if (barcodeResult != null)
{ {
var barcode = barcodeResult[0]; var barcode = barcodeResult[0];
$("#purchase-form").attr("data-used-barcode", barcode.id); $scope("#purchase-form").attr("data-used-barcode", barcode.id);
if (barcode != null) if (barcode != null)
{ {
if (barcode.amount != null && !barcode.amount.isEmpty()) if (barcode.amount != null && !barcode.amount.isEmpty())
{ {
$("#display_amount").val(barcode.amount); $scope("#display_amount").val(barcode.amount);
$("#display_amount").select(); $scope("#display_amount").select();
} }
if (barcode.qu_id != null) if (barcode.qu_id != null)
@ -383,11 +383,11 @@
if (barcode.last_price != null && !barcode.last_price.isEmpty()) if (barcode.last_price != null && !barcode.last_price.isEmpty())
{ {
$("#price").val(barcode.last_price); $scope("#price").val(barcode.last_price);
$("#price-type-total-price").click(); $scope("#price-type-total-price").click();
} }
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('purchase-form'); Grocy.FrontendHelpers.ValidateForm('purchase-form');
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
} }
@ -403,11 +403,11 @@
} }
else else
{ {
$("#purchase-form").removeAttr("data-used-barcode"); $scope("#purchase-form").removeAttr("data-used-barcode");
Grocy.ScanModeSubmit(); Grocy.ScanModeSubmit();
} }
$('#display_amount').trigger("keyup"); $scope('#display_amount').trigger("keyup");
}, },
function(xhr) function(xhr)
{ {
@ -418,9 +418,9 @@
}); });
} }
$('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_purchase_amount)); $scope('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_purchase_amount));
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('purchase-form'); Grocy.FrontendHelpers.ValidateForm('purchase-form');
if (Grocy.Components.ProductPicker) if (Grocy.Components.ProductPicker)
@ -440,7 +440,7 @@
} }
} }
$('#display_amount').on('focus', function(e) $scope('#display_amount').on('focus', function(e)
{ {
if (Grocy.Components.ProductPicker.GetValue().length === 0) if (Grocy.Components.ProductPicker.GetValue().length === 0)
{ {
@ -448,21 +448,21 @@
} }
else else
{ {
$(this).select(); $scope(this).select();
} }
}); });
$('#price').on('focus', function(e) $scope('#price').on('focus', function(e)
{ {
$(this).select(); $scope(this).select();
}); });
$('#purchase-form input').keyup(function(event) $scope('#purchase-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('purchase-form'); Grocy.FrontendHelpers.ValidateForm('purchase-form');
}); });
$('#purchase-form input').keydown(function(event) $scope('#purchase-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -474,7 +474,7 @@
} }
else else
{ {
$('#save-purchase-button').click(); $scope('#save-purchase-button').click();
} }
} }
}); });
@ -507,22 +507,22 @@
Grocy.Components.DateTimePicker2.GetInputElement().trigger("input"); Grocy.Components.DateTimePicker2.GetInputElement().trigger("input");
} }
$('#price').on('keyup', function(e) $scope('#price').on('keyup', function(e)
{ {
refreshPriceHint(); refreshPriceHint();
}); });
$('#price-type-unit-price').on('change', function(e) $scope('#price-type-unit-price').on('change', function(e)
{ {
refreshPriceHint(); refreshPriceHint();
}); });
$('#price-type-total-price').on('change', function(e) $scope('#price-type-total-price').on('change', function(e)
{ {
refreshPriceHint(); refreshPriceHint();
}); });
$('#display_amount').on('change', function(e) $scope('#display_amount').on('change', function(e)
{ {
refreshPriceHint(); refreshPriceHint();
Grocy.FrontendHelpers.ValidateForm('purchase-form'); Grocy.FrontendHelpers.ValidateForm('purchase-form');
@ -530,35 +530,35 @@
function refreshPriceHint() function refreshPriceHint()
{ {
if ($('#amount').val() == 0 || $('#price').val() == 0) if ($scope('#amount').val() == 0 || $scope('#price').val() == 0)
{ {
$('#price-hint').text(""); $scope('#price-hint').text("");
return; return;
} }
if ($("input[name='price-type']:checked").val() == "total-price" || $("#qu_id").attr("data-destination-qu-name") != $("#qu_id option:selected").text()) if ($scope("input[name='price-type']:checked").val() == "total-price" || $scope("#qu_id").attr("data-destination-qu-name") != $scope("#qu_id option:selected").text())
{ {
var amount = $('#display_amount').val(); var amount = $scope('#display_amount').val();
if (BoolVal(CurrentProductDetails.product.enable_tare_weight_handling)) if (BoolVal(CurrentProductDetails.product.enable_tare_weight_handling))
{ {
amount -= parseFloat(CurrentProductDetails.product.tare_weight); 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); var price = parseFloat($scope('#price').val() * $scope("#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 ($scope("input[name='price-type']:checked").val() == "total-price")
{ {
price = parseFloat(price / amount).toFixed(Grocy.UserSettings.stock_decimal_places_prices); 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"))); $scope('#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 }), $scope("#qu_id").attr("data-destination-qu-name")));
} }
else else
{ {
$('#price-hint').text(""); $scope('#price-hint').text("");
} }
} }
$("#scan-mode").on("change", function(e) $scope("#scan-mode").on("change", function(e)
{ {
if ($(this).prop("checked")) if ($(this).prop("checked"))
{ {
@ -566,27 +566,29 @@
} }
}); });
$("#scan-mode-button").on("click", function(e) $scope("#scan-mode-button").on("click", function(e)
{ {
document.activeElement.blur(); document.activeElement.blur();
$("#scan-mode").click(); $scope("#scan-mode").click();
$("#scan-mode-button").toggleClass("btn-success").toggleClass("btn-danger"); $scope("#scan-mode-button").toggleClass("btn-success").toggleClass("btn-danger");
if ($("#scan-mode").prop("checked")) if ($scope("#scan-mode").prop("checked"))
{ {
$("#scan-mode-status").text(__t("on")); $scope("#scan-mode-status").text(__t("on"));
} }
else else
{ {
$("#scan-mode-status").text(__t("off")); $scope("#scan-mode-status").text(__t("off"));
} }
}); });
$('#qu_id').on('change', function(e) $scope('#qu_id').on('change', function(e)
{ {
var priceTypeUnitPrice = $("#price-type-unit-price"); var priceTypeUnitPrice = $scope("#price-type-unit-price");
var priceTypeUnitPriceLabel = $("[for=" + priceTypeUnitPrice.attr("id") + "]"); var priceTypeUnitPriceLabel = $scope("[for=" + priceTypeUnitPrice.attr("id") + "]");
priceTypeUnitPriceLabel.text($("#qu_id option:selected").text() + " " + __t("price")); priceTypeUnitPriceLabel.text($scope("#qu_id option:selected").text() + " " + __t("price"));
refreshPriceHint(); refreshPriceHint();
}); });
} }
window.purchaseView = purchaseView

View File

@ -1,4 +1,6 @@
function quantityunitconversionformView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function quantityunitconversionformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,27 +8,25 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
$('#save-quconversion-button').on('click', function(e) $scope('#save-quconversion-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#quconversion-form').serializeJSON(); var jsonData = $scope('#quconversion-form').serializeJSON();
jsonData.from_qu_id = $("#from_qu_id").val(); jsonData.from_qu_id = $scope("#from_qu_id").val();
Grocy.FrontendHelpers.BeginUiBusy("quconversion-form"); Grocy.FrontendHelpers.BeginUiBusy("quconversion-form");
if ($("#create_inverse").is(":checked")) if ($scope("#create_inverse").is(":checked"))
{ {
var inverse_to_qu_id = $("#from_qu_id").val(); var inverse_to_qu_id = $scope("#from_qu_id").val();
var inverse_from_qu_id = $("#to_qu_id").val(); var inverse_from_qu_id = $scope("#to_qu_id").val();
} }
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
@ -37,7 +37,7 @@
Grocy.EditObjectId = result.created_object_id; Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function() Grocy.Components.UserfieldsForm.Save(function()
{ {
if ($("#create_inverse").is(":checked")) if ($scope("#create_inverse").is(":checked"))
{ {
jsonData.to_qu_id = inverse_to_qu_id; jsonData.to_qu_id = inverse_to_qu_id;
jsonData.from_qu_id = inverse_from_qu_id; jsonData.from_qu_id = inverse_from_qu_id;
@ -137,13 +137,13 @@
} }
}); });
$('#quconversion-form input').keyup(function(event) $scope('#quconversion-form input').keyup(function(event)
{ {
$('.input-group-qu').trigger('change'); $scope('.input-group-qu').trigger('change');
Grocy.FrontendHelpers.ValidateForm('quconversion-form'); Grocy.FrontendHelpers.ValidateForm('quconversion-form');
}); });
$('#quconversion-form input').keydown(function(event) $scope('#quconversion-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -155,69 +155,71 @@
} }
else else
{ {
$('#save-quconversion-button').click(); $scope('#save-quconversion-button').click();
} }
} }
}); });
$("#create_inverse").on("change", function() $scope("#create_inverse").on("change", function()
{ {
var value = $(this).is(":checked"); var value = $(this).is(":checked");
if (value) if (value)
{ {
$('#qu-conversion-inverse-info').removeClass('d-none'); $scope('#qu-conversion-inverse-info').removeClass('d-none');
} }
else else
{ {
$('#qu-conversion-inverse-info').addClass('d-none'); $scope('#qu-conversion-inverse-info').addClass('d-none');
} }
}); });
$('.input-group-qu').on('change', function(e) $scope('.input-group-qu').on('change', function(e)
{ {
var fromQuId = $("#from_qu_id").val(); var fromQuId = $scope("#from_qu_id").val();
var toQuId = $("#to_qu_id").val(); var toQuId = $scope("#to_qu_id").val();
var factor = $('#factor').val(); var factor = $scope('#factor').val();
if (fromQuId == toQuId) if (fromQuId == toQuId)
{ {
$("#to_qu_id").parent().find(".invalid-feedback").text(__t('This cannot be equal to %s', $("#from_qu_id option:selected").text())); $scope("#to_qu_id").parent().find(".invalid-feedback").text(__t('This cannot be equal to %s', $scope("#from_qu_id option:selected").text()));
$("#to_qu_id")[0].setCustomValidity("error"); $scope("#to_qu_id")[0].setCustomValidity("error");
} }
else else
{ {
$("#to_qu_id")[0].setCustomValidity(""); $scope("#to_qu_id")[0].setCustomValidity("");
} }
if (fromQuId && toQuId) 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")))); $scope('#qu-conversion-info').text(__t('This means 1 %1$s is the same as %2$s %3$s', $scope("#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 }), $scope("#to_qu_id option:selected").text(), $scope("#to_qu_id option:selected").data("plural-form"))));
$('#qu-conversion-info').removeClass('d-none'); $scope('#qu-conversion-info').removeClass('d-none');
if (Grocy.EditMode === 'create') 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")))); $scope('#qu-conversion-inverse-info').text(__t('This means 1 %1$s is the same as %2$s %3$s', $scope("#to_qu_id option:selected").text(), parseFloat((1 / factor)).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }), __n((1 / factor).toString(), $scope("#from_qu_id option:selected").text(), $scope("#from_qu_id option:selected").data("plural-form"))));
$('#qu-conversion-inverse-info').removeClass('d-none'); $scope('#qu-conversion-inverse-info').removeClass('d-none');
} }
} }
else else
{ {
$('#qu-conversion-info').addClass('d-none'); $scope('#qu-conversion-info').addClass('d-none');
$('#qu-conversion-inverse-info').addClass('d-none'); $scope('#qu-conversion-inverse-info').addClass('d-none');
} }
Grocy.FrontendHelpers.ValidateForm('quconversion-form'); Grocy.FrontendHelpers.ValidateForm('quconversion-form');
}); });
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
$('.input-group-qu').trigger('change'); $scope('.input-group-qu').trigger('change');
$('#from_qu_id').focus(); $scope('#from_qu_id').focus();
Grocy.FrontendHelpers.ValidateForm('quconversion-form'); Grocy.FrontendHelpers.ValidateForm('quconversion-form');
if (GetUriParam("qu-unit") !== undefined) if (GetUriParam("qu-unit") !== undefined)
{ {
$("#from_qu_id").attr("disabled", ""); $scope("#from_qu_id").attr("disabled", "");
} }
} }
window.quantityunitconversionformView = quantityunitconversionformView

View File

@ -10,11 +10,11 @@
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
$('.save-quantityunit-button').on('click', function(e) $scope('.save-quantityunit-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
var jsonData = $('#quantityunit-form').serializeJSON(); var jsonData = $scope('#quantityunit-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("quantityunit-form"); Grocy.FrontendHelpers.BeginUiBusy("quantityunit-form");
var redirectDestination = U('/quantityunits'); var redirectDestination = U('/quantityunits');
@ -23,7 +23,7 @@
redirectDestination = Grocy.QuantityUnitEditFormRedirectUri; redirectDestination = Grocy.QuantityUnitEditFormRedirectUri;
} }
if ($(e.currentTarget).attr('data-location') == "continue") if ($scope(e.currentTarget).attr('data-location') == "continue")
{ {
redirectDestination = "reload"; redirectDestination = "reload";
} }
@ -103,59 +103,59 @@
} }
}); });
$('#quantityunit-form input').keyup(function(event) $scope('#quantityunit-form input').keyup(function(event)
{ {
if (!$("#name").val().isEmpty()) if (!$scope("#name").val().isEmpty())
{ {
$("#qu-conversion-headline-info").text(__t('1 %s is the same as...', $("#name").val())); $scope("#qu-conversion-headline-info").text(__t('1 %s is the same as...', $scope("#name").val()));
} }
else else
{ {
$("#qu-conversion-headline-info").text(""); $scope("#qu-conversion-headline-info").text("");
} }
if (document.getElementById('quantityunit-form').checkValidity() === false) //There is at least one validation error if ($scope('quantityunit-form')[0].checkValidity() === false) //There is at least one validation error
{ {
$("#qu-conversion-add-button").addClass("disabled"); $scope("#qu-conversion-add-button").addClass("disabled");
} }
else else
{ {
$("#qu-conversion-add-button").removeClass("disabled"); $scope("#qu-conversion-add-button").removeClass("disabled");
} }
Grocy.FrontendHelpers.ValidateForm('quantityunit-form'); Grocy.FrontendHelpers.ValidateForm('quantityunit-form');
}); });
$('#quantityunit-form input').keydown(function(event) $scope('#quantityunit-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('quantityunit-form').checkValidity() === false) //There is at least one validation error if ($scope('quantityunit-form')[0].checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
else else
{ {
$('#save-quantityunit-button').click(); $scope('#save-quantityunit-button').click();
} }
} }
}); });
var quConversionsTable = $('#qu-conversions-table').DataTable({ var quConversionsTable = $scope('#qu-conversions-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#qu-conversions-table tbody').removeClass("d-none"); $scope('#qu-conversions-table tbody').removeClass("d-none");
quConversionsTable.columns.adjust().draw(); quConversionsTable.columns.adjust().draw();
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
$("#name").trigger("keyup"); $scope("#name").trigger("keyup");
$('#name').focus(); $scope('#name').focus();
Grocy.FrontendHelpers.ValidateForm('quantityunit-form'); Grocy.FrontendHelpers.ValidateForm('quantityunit-form');
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
@ -167,12 +167,13 @@
() => window.location.reload(), () => window.location.reload(),
); );
$("#test-quantityunit-plural-forms-button").on("click", function(e) // TODO: LoadSubView
$scope("#test-quantityunit-plural-forms-button").on("click", function(e)
{ {
e.preventDefault(); e.preventDefault();
Grocy.QuantityUnitEditFormRedirectUri = "stay"; Grocy.QuantityUnitEditFormRedirectUri = "stay";
$("#save-quantityunit-button").click(); $scope("#save-quantityunit-button").click();
bootbox.alert({ bootbox.alert({
message: '<iframe height="400px" class="embed-responsive" src="' + U("/quantityunitpluraltesting?embedded&qu=") + Grocy.EditObjectId.toString() + '"></iframe>', message: '<iframe height="400px" class="embed-responsive" src="' + U("/quantityunitpluraltesting?embedded&qu=") + Grocy.EditObjectId.toString() + '"></iframe>',

View File

@ -8,26 +8,26 @@
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
$("#qu_id").change(function(event) $scope("#qu_id").change(function(event)
{ {
RefreshQuPluralTestingResult(); RefreshQuPluralTestingResult();
}); });
$("#amount").keyup(function(event) $scope("#amount").keyup(function(event)
{ {
RefreshQuPluralTestingResult(); RefreshQuPluralTestingResult();
}); });
$("#amount").change(function(event) $scope("#amount").change(function(event)
{ {
RefreshQuPluralTestingResult(); RefreshQuPluralTestingResult();
}); });
function RefreshQuPluralTestingResult() function RefreshQuPluralTestingResult()
{ {
var singularForm = $("#qu_id option:selected").data("singular-form"); var singularForm = $scope("#qu_id option:selected").data("singular-form");
var pluralForm = $("#qu_id option:selected").data("plural-form"); var pluralForm = $scope("#qu_id option:selected").data("plural-form");
var amount = $("#amount").val(); var amount = $scope("#amount").val();
if (singularForm.toString().isEmpty() || amount.toString().isEmpty()) if (singularForm.toString().isEmpty() || amount.toString().isEmpty())
{ {
@ -35,15 +35,15 @@
} }
animateCSS("h2", "shake"); animateCSS("h2", "shake");
$("#result").text(__n(amount, singularForm, pluralForm)); $scope("#result").text(__n(amount, singularForm, pluralForm));
} }
if (GetUriParam("qu") !== undefined) if (GetUriParam("qu") !== undefined)
{ {
$("#qu_id").val(GetUriParam("qu")); $scope("#qu_id").val(GetUriParam("qu"));
$("#qu_id").trigger("change"); $scope("#qu_id").trigger("change");
} }
$("#amount").focus(); $scope("#amount").focus();
} }

View File

@ -6,14 +6,14 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var quantityUnitsTable = $('#quantityunits-table').DataTable({ var quantityUnitsTable = $scope('#quantityunits-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#quantityunits-table tbody').removeClass("d-none"); $scope('#quantityunits-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(quantityUnitsTable); Grocy.FrontendHelpers.InitDataTable(quantityUnitsTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete quantity unit "%s"?', 'Are you sure to delete quantity unit "%s"?',

View File

@ -1,13 +1,14 @@
function recipeformView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function recipeformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
var top = scope != null ? $(scope) : $(document);
if (scope != null) if (scope != null)
{ {
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
Grocy.Use("recipepicker"); Grocy.Use("recipepicker");
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
@ -19,7 +20,7 @@
{ {
if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteRecipePictureOnSave) if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteRecipePictureOnSave)
{ {
Grocy.Api.UploadFile($("#recipe-picture")[0].files[0], 'recipepictures', jsonData.picture_file_name, Grocy.Api.UploadFile($scope("#recipe-picture")[0].files[0], 'recipepictures', jsonData.picture_file_name,
(result) => (result) =>
{ {
window.location.href = U(location + recipeId); window.location.href = U(location + recipeId);
@ -38,20 +39,20 @@
}); });
} }
$('.save-recipe').on('click', function(e) $scope('.save-recipe').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
var jsonData = $('#recipe-form').serializeJSON(); var jsonData = $scope('#recipe-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("recipe-form"); Grocy.FrontendHelpers.BeginUiBusy("recipe-form");
if ($("#recipe-picture")[0].files.length > 0) if ($scope("#recipe-picture")[0].files.length > 0)
{ {
var someRandomStuff = Math.random().toString(36).substring(2, 100) + Math.random().toString(36).substring(2, 100); 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; jsonData.picture_file_name = someRandomStuff + $scope("#recipe-picture")[0].files[0].name;
} }
const location = $(e.currentTarget).attr('data-location') == 'return' ? '/recipes?recipe=' : '/recipe/'; const location = $scope(e.currentTarget).attr('data-location') == 'return' ? '/recipes?recipe=' : '/recipe/';
if (Grocy.EditMode == 'create') if (Grocy.EditMode == 'create')
{ {
@ -87,7 +88,7 @@
); );
}); });
var recipesPosTables = $('#recipes-pos-table').DataTable({ var recipesPosTables = $scope('#recipes-pos-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
"orderFixed": [[4, 'asc']], "orderFixed": [[4, 'asc']],
'columnDefs': [ 'columnDefs': [
@ -100,28 +101,28 @@
dataSrc: 4 dataSrc: 4
} }
}); });
$('#recipes-pos-table tbody').removeClass("d-none"); $scope('#recipes-pos-table tbody').removeClass("d-none");
recipesPosTables.columns.adjust().draw(); recipesPosTables.columns.adjust().draw();
var recipesIncludesTables = $('#recipes-includes-table').DataTable({ var recipesIncludesTables = $scope('#recipes-includes-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#recipes-includes-table tbody').removeClass("d-none"); $scope('#recipes-includes-table tbody').removeClass("d-none");
recipesIncludesTables.columns.adjust().draw(); recipesIncludesTables.columns.adjust().draw();
Grocy.FrontendHelpers.ValidateForm('recipe-form'); Grocy.FrontendHelpers.ValidateForm('recipe-form');
$("#name").focus(); $scope("#name").focus();
$('#recipe-form input').keyup(function(event) $scope('#recipe-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('recipe-form'); Grocy.FrontendHelpers.ValidateForm('recipe-form');
}); });
$('#recipe-form input').keydown(function(event) $scope('#recipe-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -133,7 +134,7 @@
} }
else else
{ {
$('#save-recipe-button').click(); $scope('#save-recipe-button').click();
} }
} }
}); });
@ -156,14 +157,15 @@
() => window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl) () => window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl)
); );
$(document).on('click', '.recipe-pos-show-note-button', function(e) top.on('click', '.recipe-pos-show-note-button', function(e)
{ {
var note = $(e.currentTarget).attr('data-recipe-pos-note'); var note = $(e.currentTarget).attr('data-recipe-pos-note');
bootbox.alert(note); bootbox.alert(note);
}); });
$(document).on('click', '.recipe-pos-edit-button', function(e) // TODO: LoadSubView
top.on('click', '.recipe-pos-edit-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -188,21 +190,21 @@
}); });
}); });
$(document).on('click', '.recipe-include-edit-button', function(e) top.on('click', '.recipe-include-edit-button', function(e)
{ {
var id = $(e.currentTarget).attr('data-recipe-include-id'); var id = $(e.currentTarget).attr('data-recipe-include-id');
var recipeId = $(e.currentTarget).attr('data-recipe-included-recipe-id'); var recipeId = $(e.currentTarget).attr('data-recipe-included-recipe-id');
var recipeServings = $(e.currentTarget).attr('data-recipe-included-recipe-servings'); var recipeServings = $(e.currentTarget).attr('data-recipe-included-recipe-servings');
Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(), Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $scope('#recipe-form').serializeJSON(),
function(result) function(result)
{ {
$("#recipe-include-editform-title").text(__t("Edit included recipe")); $scope("#recipe-include-editform-title").text(__t("Edit included recipe"));
$("#recipe-include-form").data("edit-mode", "edit"); $scope("#recipe-include-form").data("edit-mode", "edit");
$("#recipe-include-form").data("recipe-nesting-id", id); $scope("#recipe-include-form").data("recipe-nesting-id", id);
Grocy.Components.RecipePicker.SetId(recipeId); Grocy.Components.RecipePicker.SetId(recipeId);
$("#includes_servings").val(recipeServings); $scope("#includes_servings").val(recipeServings);
$("#recipe-include-editform-modal").modal("show"); $scope("#recipe-include-editform-modal").modal("show");
Grocy.FrontendHelpers.ValidateForm("recipe-include-form"); Grocy.FrontendHelpers.ValidateForm("recipe-include-form");
}, },
function(xhr) function(xhr)
@ -212,7 +214,7 @@
); );
}); });
$("#recipe-pos-add-button").on("click", function(e) $scope("#recipe-pos-add-button").on("click", function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -234,16 +236,16 @@
}); });
}); });
$("#recipe-include-add-button").on("click", function(e) $scope("#recipe-include-add-button").on("click", function(e)
{ {
Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(), Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $scope('#recipe-form').serializeJSON(),
function(result) function(result)
{ {
$("#recipe-include-editform-title").text(__t("Add included recipe")); $scope("#recipe-include-editform-title").text(__t("Add included recipe"));
$("#recipe-include-form").data("edit-mode", "create"); $scope("#recipe-include-form").data("edit-mode", "create");
Grocy.Components.RecipePicker.Clear(); Grocy.Components.RecipePicker.Clear();
Grocy.Components.RecipePicker.GetInputElement().focus(); Grocy.Components.RecipePicker.GetInputElement().focus();
$("#recipe-include-editform-modal").modal("show"); $scope("#recipe-include-editform-modal").modal("show");
Grocy.FrontendHelpers.ValidateForm("recipe-include-form"); Grocy.FrontendHelpers.ValidateForm("recipe-include-form");
}, },
function(xhr) function(xhr)
@ -253,11 +255,11 @@
); );
}); });
$('#save-recipe-include-button').on('click', function(e) $scope('#save-recipe-include-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
@ -267,12 +269,12 @@
return false; return false;
} }
var nestingId = $("#recipe-include-form").data("recipe-nesting-id"); var nestingId = $scope("#recipe-include-form").data("recipe-nesting-id");
var editMode = $("#recipe-include-form").data("edit-mode"); var editMode = $scope("#recipe-include-form").data("edit-mode");
var jsonData = {}; var jsonData = {};
jsonData.includes_recipe_id = Grocy.Components.RecipePicker.GetValue(); jsonData.includes_recipe_id = Grocy.Components.RecipePicker.GetValue();
jsonData.servings = $("#includes_servings").val(); jsonData.servings = $scope("#includes_servings").val();
jsonData.recipe_id = Grocy.EditObjectId; jsonData.recipe_id = Grocy.EditObjectId;
if (editMode === 'create') if (editMode === 'create')
@ -303,23 +305,23 @@
} }
}); });
$("#recipe-picture").on("change", function(e) $scope("#recipe-picture").on("change", function(e)
{ {
$("#recipe-picture-label").removeClass("d-none"); $scope("#recipe-picture-label").removeClass("d-none");
$("#recipe-picture-label-none").addClass("d-none"); $scope("#recipe-picture-label-none").addClass("d-none");
$("#delete-current-recipe-picture-on-save-hint").addClass("d-none"); $scope("#delete-current-recipe-picture-on-save-hint").addClass("d-none");
$("#current-recipe-picture").addClass("d-none"); $scope("#current-recipe-picture").addClass("d-none");
Grocy.DeleteRecipePictureOnSave = false; Grocy.DeleteRecipePictureOnSave = false;
}); });
Grocy.DeleteRecipePictureOnSave = false; Grocy.DeleteRecipePictureOnSave = false;
$("#delete-current-recipe-picture-button").on("click", function(e) $scope("#delete-current-recipe-picture-button").on("click", function(e)
{ {
Grocy.DeleteRecipePictureOnSave = true; Grocy.DeleteRecipePictureOnSave = true;
$("#current-recipe-picture").addClass("d-none"); $scope("#current-recipe-picture").addClass("d-none");
$("#delete-current-recipe-picture-on-save-hint").removeClass("d-none"); $scope("#delete-current-recipe-picture-on-save-hint").removeClass("d-none");
$("#recipe-picture-label").addClass("d-none"); $scope("#recipe-picture-label").addClass("d-none");
$("#recipe-picture-label-none").removeClass("d-none"); $scope("#recipe-picture-label-none").removeClass("d-none");
}); });
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
@ -344,3 +346,5 @@
}); });
} }
window.recipeformView = recipeformView

View File

@ -1,4 +1,6 @@
function recipeposformView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function recipeposformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,24 +8,22 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
Grocy.Use("productamountpicker"); Grocy.Use("productamountpicker");
Grocy.Use("productcard"); Grocy.Use("productcard");
Grocy.RecipePosFormInitialLoadDone = false; Grocy.RecipePosFormInitialLoadDone = false;
$('#save-recipe-pos-button').on('click', function(e) $scope('#save-recipe-pos-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#recipe-pos-form').serializeJSON(); var jsonData = $scope('#recipe-pos-form').serializeJSON();
jsonData.recipe_id = Grocy.EditObjectParentId; jsonData.recipe_id = Grocy.EditObjectParentId;
delete jsonData.display_amount; delete jsonData.display_amount;
@ -63,7 +63,7 @@
Grocy.Components.ProductPicker.GetPicker().on('change', function(e) Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{ {
var productId = $(e.target).val(); var productId = $scope(e.target).val();
if (productId) if (productId)
{ {
@ -83,15 +83,15 @@
if (Grocy.Mode == "create") if (Grocy.Mode == "create")
{ {
$("#not_check_stock_fulfillment").prop("checked", productDetails.product.not_check_stock_fulfillment_for_recipes == 1); $scope("#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) if (!$scope("#only_check_single_unit_in_stock").prop("checked") && Grocy.RecipePosFormInitialLoadDone)
{ {
Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.quantity_unit_stock.id); Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.quantity_unit_stock.id);
} }
$('#display_amount').focus(); $scope('#display_amount').focus();
Grocy.FrontendHelpers.ValidateForm('recipe-pos-form'); Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
Grocy.RecipePosFormInitialLoadDone = true; Grocy.RecipePosFormInitialLoadDone = true;
}, },
@ -116,7 +116,7 @@
Grocy.RecipePosFormInitialLoadDone = true; Grocy.RecipePosFormInitialLoadDone = true;
} }
$('#display_amount').on('focus', function(e) $scope('#display_amount').on('focus', function(e)
{ {
if (Grocy.Components.ProductPicker.GetValue().length === 0) if (Grocy.Components.ProductPicker.GetValue().length === 0)
{ {
@ -128,17 +128,17 @@
} }
}); });
$('#recipe-pos-form input').keyup(function(event) $scope('#recipe-pos-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('recipe-pos-form'); Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
}); });
$('#qu_id').change(function(event) $scope('#qu_id').change(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('recipe-pos-form'); Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
}); });
$('#recipe-pos-form input').keydown(function(event) $scope('#recipe-pos-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -150,31 +150,33 @@
} }
else else
{ {
$('#save-recipe-pos-button').click(); $scope('#save-recipe-pos-button').click();
} }
} }
}); });
$("#only_check_single_unit_in_stock").on("change", function() $scope("#only_check_single_unit_in_stock").on("change", function()
{ {
if (this.checked) if (this.checked)
{ {
$("#display_amount").attr("min", Grocy.DefaultMinAmount); $scope("#display_amount").attr("min", Grocy.DefaultMinAmount);
Grocy.Components.ProductAmountPicker.AllowAnyQu(true); Grocy.Components.ProductAmountPicker.AllowAnyQu(true);
Grocy.FrontendHelpers.ValidateForm("recipe-pos-form"); Grocy.FrontendHelpers.ValidateForm("recipe-pos-form");
} }
else else
{ {
$("#display_amount").attr("min", "0"); $scope("#display_amount").attr("min", "0");
Grocy.Components.ProductPicker.GetPicker().trigger("change"); // Selects the default quantity unit of the selected product Grocy.Components.ProductPicker.GetPicker().trigger("change"); // Selects the default quantity unit of the selected product
Grocy.Components.ProductAmountPicker.AllowAnyQuEnabled = false; Grocy.Components.ProductAmountPicker.AllowAnyQuEnabled = false;
Grocy.FrontendHelpers.ValidateForm("recipe-pos-form"); Grocy.FrontendHelpers.ValidateForm("recipe-pos-form");
} }
}); });
if ($("#only_check_single_unit_in_stock").prop("checked")) if ($scope("#only_check_single_unit_in_stock").prop("checked"))
{ {
Grocy.Components.ProductAmountPicker.AllowAnyQu(true); Grocy.Components.ProductAmountPicker.AllowAnyQu(true);
} }
} }
window.recipeposformView = recipeposformView

View File

@ -1,6 +1,8 @@
function recipesView(Grocy, scope = null) function recipesView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
var viewport = scope != null ? $(scope) : $(window);
var top = scope != null ? $(scope) : $(document)
if (scope != null) if (scope != null)
{ {
$scope = $(scope).find; $scope = $(scope).find;
@ -8,7 +10,7 @@
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
var recipesTables = $('#recipes-table').DataTable({ var recipesTables = $scope('#recipes-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
@ -24,64 +26,64 @@
this.api().row({ order: 'current' }, 0).select(); this.api().row({ order: 'current' }, 0).select();
} }
}); });
$('#recipes-table tbody').removeClass("d-none"); $scope('#recipes-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(recipesTables, Grocy.FrontendHelpers.InitDataTable(recipesTables, $scope,
function() function()
{ {
var value = $(this).val(); var value = $(this).val();
recipesTables.search(value).draw(); recipesTables.search(value).draw();
$(".recipe-gallery-item").removeClass("d-none"); $scope(".recipe-gallery-item").removeClass("d-none");
$(".recipe-gallery-item .card-title:not(:contains_case_insensitive(" + value + "))").parent().parent().parent().addClass("d-none"); $scope(".recipe-gallery-item .card-title:not(:contains_case_insensitive(" + value + "))").parent().parent().parent().addClass("d-none");
}, },
function() // custom status filter below function() // custom status filter below
{ {
$("#search").val(""); $scope("#search").val("");
$("#status-filter").val("all"); $scope("#status-filter").val("all");
$("#search").trigger("keyup"); $scope("#search").trigger("keyup");
$("#status-filter").trigger("change"); $scope("#status-filter").trigger("change");
}) })
if ((typeof GetUriParam("tab") !== "undefined" && GetUriParam("tab") === "gallery") || window.localStorage.getItem("recipes_last_tab_id") == "gallery-tab") if ((typeof GetUriParam("tab") !== "undefined" && GetUriParam("tab") === "gallery") || window.localStorage.getItem("recipes_last_tab_id") == "gallery-tab")
{ {
$(".nav-tabs a[href='#gallery']").tab("show"); $scope(".nav-tabs a[href='#gallery']").tab("show");
} }
var recipe = GetUriParam("recipe"); var recipe = GetUriParam("recipe");
if (typeof recipe !== "undefined") if (typeof recipe !== "undefined")
{ {
$("#recipes-table tr").removeClass("selected"); $scope("#recipes-table tr").removeClass("selected");
var rowId = "#recipe-row-" + recipe; var rowId = "#recipe-row-" + recipe;
$(rowId).addClass("selected") $scope(rowId).addClass("selected")
var cardId = "#RecipeGalleryCard-" + recipe; var cardId = "#RecipeGalleryCard-" + recipe;
$(cardId).addClass("border-primary"); $scope(cardId).addClass("border-primary");
if ($(window).width() < 768) if (viewport.width() < 768)
{ {
// Scroll to recipe card on mobile // Scroll to recipe card on mobile
$("#selectedRecipeCard")[0].scrollIntoView(); $scope("#selectedRecipeCard")[0].scrollIntoView();
} }
} }
if (GetUriParam("search") !== undefined) if (GetUriParam("search") !== undefined)
{ {
$("#search").val(GetUriParam("search")); $scope("#search").val(GetUriParam("search"));
setTimeout(function() setTimeout(function()
{ {
$("#search").keyup(); $scope("#search").keyup();
}, 50); }, 50);
} }
$("a[data-toggle='tab']").on("shown.bs.tab", function(e) $scope("a[data-toggle='tab']").on("shown.bs.tab", function(e)
{ {
var tabId = $(e.target).attr("id"); var tabId = $(e.target).attr("id");
window.localStorage.setItem("recipes_last_tab_id", tabId); window.localStorage.setItem("recipes_last_tab_id", tabId);
}); });
$("#status-filter").on("change", function() $scope("#status-filter").on("change", function()
{ {
var value = $(this).val(); var value = $(this).val();
if (value === "all") if (value === "all")
@ -91,20 +93,20 @@
recipesTables.column(5).search(value).draw(); recipesTables.column(5).search(value).draw();
$('.recipe-gallery-item').removeClass('d-none'); $scope('.recipe-gallery-item').removeClass('d-none');
if (value !== "") if (value !== "")
{ {
if (value === 'Xenoughinstock') if (value === 'Xenoughinstock')
{ {
$('.recipe-gallery-item').not('.recipe-enoughinstock').addClass('d-none'); $scope('.recipe-gallery-item').not('.recipe-enoughinstock').addClass('d-none');
} }
else if (value === 'enoughinstockwithshoppinglist') else if (value === 'enoughinstockwithshoppinglist')
{ {
$('.recipe-gallery-item').not('.recipe-enoughinstockwithshoppinglist').addClass('d-none'); $scope('.recipe-gallery-item').not('.recipe-enoughinstockwithshoppinglist').addClass('d-none');
} }
if (value === 'notenoughinstock') if (value === 'notenoughinstock')
{ {
$('.recipe-gallery-item').not('.recipe-notenoughinstock').addClass('d-none'); $scope('.recipe-gallery-item').not('.recipe-notenoughinstock').addClass('d-none');
} }
} }
}); });
@ -126,7 +128,7 @@
"<br><br>" + "<br><br>" +
__t("Uncheck ingredients to not put them on the shopping list") + __t("Uncheck ingredients to not put them on the shopping list") +
":" + ":" +
$("#missing-recipe-pos-list")[0].outerHTML.replace("d-none", ""); $scope("#missing-recipe-pos-list")[0].outerHTML.replace("d-none", "");
}, },
'.recipe-shopping-list', '.recipe-shopping-list',
(result, e) => (result, e) =>
@ -137,7 +139,7 @@
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
var excludedProductIds = new Array(); var excludedProductIds = new Array();
$(".missing-recipe-pos-product-checkbox:checkbox:not(:checked)").each(function() $scope(".missing-recipe-pos-product-checkbox:checkbox:not(:checked)").each(function()
{ {
excludedProductIds.push($(this).data("product-id")); excludedProductIds.push($(this).data("product-id"));
}); });
@ -194,7 +196,7 @@
{ {
if (type === 'row') if (type === 'row')
{ {
var selectedRecipeId = $(recipesTables.row(indexes[0]).node()).data("recipe-id"); var selectedRecipeId = $scope(recipesTables.row(indexes[0]).node()).data("recipe-id");
var currentRecipeId = window.location.search.split('recipe=')[1]; var currentRecipeId = window.location.search.split('recipe=')[1];
if (selectedRecipeId.toString() !== currentRecipeId) if (selectedRecipeId.toString() !== currentRecipeId)
{ {
@ -203,23 +205,23 @@
} }
}); });
$(".recipe-gallery-item").on("click", function(e) $scope(".recipe-gallery-item").on("click", function(e)
{ {
e.preventDefault(); e.preventDefault();
window.location.href = U('/recipes?tab=gallery&recipe=' + $(this).data("recipe-id")); window.location.href = U('/recipes?tab=gallery&recipe=' + $(this).data("recipe-id"));
}); });
$(".recipe-fullscreen").on('click', function(e) $scope(".recipe-fullscreen").on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
$("#selectedRecipeCard").toggleClass("fullscreen"); $scope("#selectedRecipeCard").toggleClass("fullscreen");
$("body").toggleClass("fullscreen-card"); $scope("body").toggleClass("fullscreen-card");
$("#selectedRecipeCard .card-header").toggleClass("fixed-top"); $scope("#selectedRecipeCard .card-header").toggleClass("fixed-top");
$("#selectedRecipeCard .card-body").toggleClass("mt-5"); $scope("#selectedRecipeCard .card-body").toggleClass("mt-5");
if ($("body").hasClass("fullscreen-card")) if ($scope("body").hasClass("fullscreen-card"))
{ {
window.location.hash = "#fullscreen"; window.location.hash = "#fullscreen";
} }
@ -229,20 +231,20 @@
} }
}); });
$(".recipe-print").on('click', function(e) $scope(".recipe-print").on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
$("#selectedRecipeCard").removeClass("fullscreen"); $scope("#selectedRecipeCard").removeClass("fullscreen");
$("body").removeClass("fullscreen-card"); $scope("body").removeClass("fullscreen-card");
$("#selectedRecipeCard .card-header").removeClass("fixed-top"); $scope("#selectedRecipeCard .card-header").removeClass("fixed-top");
$("#selectedRecipeCard .card-body").removeClass("mt-5"); $scope("#selectedRecipeCard .card-body").removeClass("mt-5");
window.history.replaceState(null, null, " "); window.history.replaceState(null, null, " ");
window.print(); window.print();
}); });
$('#servings-scale').keyup(function(event) $scope('#servings-scale').keyup(function(event)
{ {
var data = {}; var data = {};
data.desired_servings = $(this).val(); data.desired_servings = $(this).val();
@ -259,7 +261,7 @@
); );
}); });
$(document).on("click", ".missing-recipe-pos-select-button", function(e) top.on("click", ".missing-recipe-pos-select-button", function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -271,7 +273,7 @@
if (window.location.hash === "#fullscreen") if (window.location.hash === "#fullscreen")
{ {
$("#selectedRecipeToggleFullscreenButton").click(); $scope("#selectedRecipeToggleFullscreenButton").click();
} }
} }

View File

@ -1,4 +1,6 @@
function recipessettingsView(Grocy, scope = null) import { BoolVal } from '../helpers/extensions';
function recipessettingsView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,13 +8,13 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { BoolVal } from '../helpers/extensions';
if (BoolVal(Grocy.UserSettings.recipe_ingredients_group_by_product_group)) if (BoolVal(Grocy.UserSettings.recipe_ingredients_group_by_product_group))
{ {
$("#recipe_ingredients_group_by_product_group").prop("checked", true); $scope("#recipe_ingredients_group_by_product_group").prop("checked", true);
} }
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
} }
window.recipessettingsView = recipessettingsView

View File

@ -1,20 +1,24 @@
function shoppinglistView(Grocy, scope = null) 
{
var $scope = $;
if (scope != null)
{
$scope = $(scope).find;
}
// this needs to be explicitly imported for some reason, // this needs to be explicitly imported for some reason,
// otherwise rollup complains. // otherwise rollup complains.
import bwipjs from '../../node_modules/bwip-js/dist/bwip-js.mjs'; import bwipjs from '../../node_modules/bwip-js/dist/bwip-js.mjs';
import { WindowMessageBag } from '../helpers/messagebag'; import { WindowMessageBag } from '../helpers/messagebag';
function shoppinglistView(Grocy, scope = null)
{
var $scope = $;
var top = scope != null ? $(scope) : top;
var viewport = scope != null ? $(scope) : $(window);
if (scope != null)
{
$scope = $(scope).find;
}
Grocy.Use("calendarcard"); Grocy.Use("calendarcard");
Grocy.Use("productcard"); Grocy.Use("productcard");
var shoppingListTable = $('#shoppinglist-table').DataTable({ var shoppingListTable = $scope('#shoppinglist-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
"orderFixed": [[3, 'asc']], "orderFixed": [[3, 'asc']],
'columnDefs': [ 'columnDefs': [
@ -34,11 +38,11 @@
dataSrc: 3 dataSrc: 3
} }
}); });
$('#shoppinglist-table tbody').removeClass("d-none"); $scope('#shoppinglist-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(shoppingListTable); Grocy.FrontendHelpers.InitDataTable(shoppingListTable);
Grocy.FrontendHelpers.MakeStatusFilter(shoppingListTable, 4); Grocy.FrontendHelpers.MakeStatusFilter(shoppingListTable, 4);
var shoppingListPrintShadowTable = $('#shopping-list-print-shadow-table').DataTable({ var shoppingListPrintShadowTable = $scope('#shopping-list-print-shadow-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
"orderFixed": [[2, 'asc']], "orderFixed": [[2, 'asc']],
'columnDefs': [ 'columnDefs': [
@ -53,7 +57,7 @@
Grocy.FrontendHelpers.InitDataTable(shoppingListPrintShadowTable); Grocy.FrontendHelpers.InitDataTable(shoppingListPrintShadowTable);
$("#selected-shopping-list").on("change", function() $scope("#selected-shopping-list").on("change", function()
{ {
var value = $(this).val(); var value = $(this).val();
window.location.href = U('/shoppinglist?list=' + value); window.location.href = U('/shoppinglist?list=' + value);
@ -62,13 +66,13 @@
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete shopping list "%s"?', 'Are you sure to delete shopping list "%s"?',
'#delete-selected-shopping-list', '#delete-selected-shopping-list',
() => $("#selected-shopping-list option:selected").text(), () => $scope("#selected-shopping-list option:selected").text(),
() => $("#selected-shopping-list").val(), () => $scope("#selected-shopping-list").val(),
'objects/shopping_lists/', 'objects/shopping_lists/',
'/shoppinglist' '/shoppinglist'
); );
$(document).on('click', '.shoppinglist-delete-button', function(e) top.on('click', '.shoppinglist-delete-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -85,7 +89,7 @@
animateCSS("#shoppinglistitem-" + shoppingListItemId + "-row", "fadeOut", function() animateCSS("#shoppinglistitem-" + shoppingListItemId + "-row", "fadeOut", function()
{ {
Grocy.FrontendHelpers.EndUiBusy(); Grocy.FrontendHelpers.EndUiBusy();
$("#shoppinglistitem-" + shoppingListItemId + "-row").remove(); $scope("#shoppinglistitem-" + shoppingListItemId + "-row").remove();
OnListItemRemoved(); OnListItemRemoved();
}); });
}, },
@ -97,21 +101,21 @@
); );
}); });
$(document).on("click", ".product-name-cell", function(e) top.on("click", ".product-name-cell", function(e)
{ {
if ($(e.currentTarget).attr("data-product-id") != "") if ($(e.currentTarget).attr("data-product-id") != "")
{ {
Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-product-id")); Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-product-id"));
$("#shoppinglist-productcard-modal").modal("show"); $scope("#shoppinglist-productcard-modal").modal("show");
} }
}); });
$(document).on('click', '#add-products-below-min-stock-amount', function(e) top.on('click', '#add-products-below-min-stock-amount', function(e)
{ {
Grocy.Api.Post('stock/shoppinglist/add-missing-products', { "list_id": $("#selected-shopping-list").val() }, Grocy.Api.Post('stock/shoppinglist/add-missing-products', { "list_id": $scope("#selected-shopping-list").val() },
function(result) function(result)
{ {
window.location.href = U('/shoppinglist?list=' + $("#selected-shopping-list").val()); window.location.href = U('/shoppinglist?list=' + $scope("#selected-shopping-list").val());
}, },
function(xhr) function(xhr)
{ {
@ -120,7 +124,7 @@
); );
}); });
$(document).on('click', '#add-overdue-expired-products', function(e) top.on('click', '#add-overdue-expired-products', function(e)
{ {
Grocy.Api.Post('stock/shoppinglist/add-overdue-products', { "list_id": $("#selected-shopping-list").val() }, Grocy.Api.Post('stock/shoppinglist/add-overdue-products', { "list_id": $("#selected-shopping-list").val() },
function(result) function(result)
@ -144,7 +148,7 @@
}); });
Grocy.FrontendHelpers.MakeYesNoBox( Grocy.FrontendHelpers.MakeYesNoBox(
() => __t('Are you sure to empty shopping list "%s"?', $("#selected-shopping-list option:selected").text()), () => __t('Are you sure to empty shopping list "%s"?', $scope("#selected-shopping-list option:selected").text()),
'#clear-shopping-list', '#clear-shopping-list',
(result) => (result) =>
{ {
@ -152,13 +156,13 @@
{ {
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
Grocy.Api.Post('stock/shoppinglist/clear', { "list_id": $("#selected-shopping-list").val() }, Grocy.Api.Post('stock/shoppinglist/clear', { "list_id": $scope("#selected-shopping-list").val() },
function(result) function(result)
{ {
animateCSS("#shoppinglist-table tbody tr", "fadeOut", function() animateCSS("#shoppinglist-table tbody tr", "fadeOut", function()
{ {
Grocy.FrontendHelpers.EndUiBusy(); Grocy.FrontendHelpers.EndUiBusy();
$("#shoppinglist-table tbody tr").remove(); $scope("#shoppinglist-table tbody tr").remove();
OnListItemRemoved(); OnListItemRemoved();
}); });
}, },
@ -172,7 +176,7 @@
} }
); );
$(document).on('click', '.shopping-list-stock-add-workflow-list-item-button', function(e) top.on('click', '.shopping-list-stock-add-workflow-list-item-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -180,35 +184,35 @@
// to prevent that the tooltip stays until clicked anywhere else // to prevent that the tooltip stays until clicked anywhere else
document.activeElement.blur(); document.activeElement.blur();
var href = $(e.currentTarget).attr('href'); var href = $scope(e.currentTarget).attr('href');
$("#shopping-list-stock-add-workflow-purchase-form-frame").attr("src", href); $scope("#shopping-list-stock-add-workflow-purchase-form-frame").attr("src", href);
$("#shopping-list-stock-add-workflow-modal").modal("show"); $scope("#shopping-list-stock-add-workflow-modal").modal("show");
if (Grocy.ShoppingListToStockWorkflowAll) if (Grocy.ShoppingListToStockWorkflowAll)
{ {
$("#shopping-list-stock-add-workflow-purchase-item-count").removeClass("d-none"); $scope("#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)); $scope("#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"); $scope("#shopping-list-stock-add-workflow-skip-button").removeClass("d-none");
} }
else else
{ {
$("#shopping-list-stock-add-workflow-skip-button").addClass("d-none"); $scope("#shopping-list-stock-add-workflow-skip-button").addClass("d-none");
} }
}); });
Grocy.ShoppingListToStockWorkflowAll = false; Grocy.ShoppingListToStockWorkflowAll = false;
Grocy.ShoppingListToStockWorkflowCount = 0; Grocy.ShoppingListToStockWorkflowCount = 0;
Grocy.ShoppingListToStockWorkflowCurrent = 0; Grocy.ShoppingListToStockWorkflowCurrent = 0;
$(document).on('click', '#add-all-items-to-stock-button', function(e) top.on('click', '#add-all-items-to-stock-button', function(e)
{ {
Grocy.ShoppingListToStockWorkflowAll = true; Grocy.ShoppingListToStockWorkflowAll = true;
Grocy.ShoppingListToStockWorkflowCount = $(".shopping-list-stock-add-workflow-list-item-button").length; Grocy.ShoppingListToStockWorkflowCount = $scope(".shopping-list-stock-add-workflow-list-item-button").length;
Grocy.ShoppingListToStockWorkflowCurrent++; Grocy.ShoppingListToStockWorkflowCurrent++;
$(".shopping-list-stock-add-workflow-list-item-button").first().click(); $scope(".shopping-list-stock-add-workflow-list-item-button").first().click();
}); });
$("#shopping-list-stock-add-workflow-modal").on("hidden.bs.modal", function(e) $scope("#shopping-list-stock-add-workflow-modal").on("hidden.bs.modal", function(e)
{ {
Grocy.ShoppingListToStockWorkflowAll = false; Grocy.ShoppingListToStockWorkflowAll = false;
Grocy.ShoppingListToStockWorkflowCount = 0; Grocy.ShoppingListToStockWorkflowCount = 0;
@ -221,37 +225,37 @@
if (data.Message === "AfterItemAdded") if (data.Message === "AfterItemAdded")
{ {
$(".shoppinglist-delete-button[data-shoppinglist-id='" + data.Payload + "']").click(); $scope(".shoppinglist-delete-button[data-shoppinglist-id='" + data.Payload + "']").click();
} }
else if (data.Message === "Ready") else if (data.Message === "Ready")
{ {
if (!Grocy.ShoppingListToStockWorkflowAll) if (!Grocy.ShoppingListToStockWorkflowAll)
{ {
$("#shopping-list-stock-add-workflow-modal").modal("hide"); $scope("#shopping-list-stock-add-workflow-modal").modal("hide");
} }
else else
{ {
Grocy.ShoppingListToStockWorkflowCurrent++; Grocy.ShoppingListToStockWorkflowCurrent++;
if (Grocy.ShoppingListToStockWorkflowCurrent <= Grocy.ShoppingListToStockWorkflowCount) if (Grocy.ShoppingListToStockWorkflowCurrent <= Grocy.ShoppingListToStockWorkflowCount)
{ {
$(".shopping-list-stock-add-workflow-list-item-button")[Grocy.ShoppingListToStockWorkflowCurrent - 1].click(); $scope(".shopping-list-stock-add-workflow-list-item-button")[Grocy.ShoppingListToStockWorkflowCurrent - 1].click();
} }
else else
{ {
$("#shopping-list-stock-add-workflow-modal").modal("hide"); $scope("#shopping-list-stock-add-workflow-modal").modal("hide");
} }
} }
} }
}); });
$(document).on('click', '#shopping-list-stock-add-workflow-skip-button', function(e) top.on('click', '#shopping-list-stock-add-workflow-skip-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
window.postMessage(WindowMessageBag("Ready"), Grocy.BaseUrl); window.postMessage(WindowMessageBag("Ready"), Grocy.BaseUrl);
}); });
$(document).on('click', '.order-listitem-button', function(e) top.on('click', '.order-listitem-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -276,13 +280,13 @@
{ {
if (done == 1) if (done == 1)
{ {
$('#shoppinglistitem-' + listItemId + '-row').addClass("text-muted"); $scope('#shoppinglistitem-' + listItemId + '-row').addClass("text-muted");
$('#shoppinglistitem-' + listItemId + '-row').addClass("text-strike-through"); $scope('#shoppinglistitem-' + listItemId + '-row').addClass("text-strike-through");
} }
else else
{ {
$('#shoppinglistitem-' + listItemId + '-row').removeClass("text-muted"); $scope('#shoppinglistitem-' + listItemId + '-row').removeClass("text-muted");
$('#shoppinglistitem-' + listItemId + '-row').removeClass("text-strike-through"); $scope('#shoppinglistitem-' + listItemId + '-row').removeClass("text-strike-through");
} }
Grocy.FrontendHelpers.EndUiBusy(); Grocy.FrontendHelpers.EndUiBusy();
@ -295,7 +299,7 @@
); );
var statusInfoCell = $("#shoppinglistitem-" + listItemId + "-status-info"); var statusInfoCell = $scope("#shoppinglistitem-" + listItemId + "-status-info");
if (done == 1) if (done == 1)
{ {
statusInfoCell.text(statusInfoCell.text().replace("xxUNDONExx", "")); statusInfoCell.text(statusInfoCell.text().replace("xxUNDONExx", ""));
@ -306,19 +310,19 @@
} }
shoppingListTable.rows().invalidate().draw(false); shoppingListTable.rows().invalidate().draw(false);
$("#status-filter").trigger("change"); $scope("#status-filter").trigger("change");
}); });
function OnListItemRemoved() function OnListItemRemoved()
{ {
if ($(".shopping-list-stock-add-workflow-list-item-button").length === 0) if ($scope(".shopping-list-stock-add-workflow-list-item-button").length === 0)
{ {
$("#add-all-items-to-stock-button").addClass("disabled"); $scope("#add-all-items-to-stock-button").addClass("disabled");
} }
} }
OnListItemRemoved(); OnListItemRemoved();
$(document).on("click", "#print-shopping-list-button", function(e) top.on("click", "#print-shopping-list-button", function(e)
{ {
var dialogHtml = ' \ var dialogHtml = ' \
<div class="text-center"><h5>' + __t('Print options') + '</h5><hr></div> \ <div class="text-center"><h5>' + __t('Print options') + '</h5><hr></div> \
@ -381,7 +385,7 @@
callback: function() callback: function()
{ {
bootbox.hideAll(); bootbox.hideAll();
var printHeader = $("#print-show-header").prop("checked"); var printHeader = $scope("#print-show-header").prop("checked");
var thermalPrintDialog = bootbox.dialog({ var thermalPrintDialog = bootbox.dialog({
title: __t('Printing'), title: __t('Printing'),
message: '<p><i class="fa fa-spin fa-spinner"></i> ' + __t('Connecting to printer...') + '</p>' message: '<p><i class="fa fa-spin fa-spinner"></i> ' + __t('Connecting to printer...') + '</p>'
@ -389,7 +393,7 @@
//Delaying for one second so that the alert can be closed //Delaying for one second so that the alert can be closed
setTimeout(function() setTimeout(function()
{ {
Grocy.Api.Get('print/shoppinglist/thermal?list=' + $("#selected-shopping-list").val() + '&printHeader=' + printHeader, Grocy.Api.Get('print/shoppinglist/thermal?list=' + $scope("#selected-shopping-list").val() + '&printHeader=' + printHeader,
function(result) function(result)
{ {
bootbox.hideAll(); bootbox.hideAll();
@ -423,29 +427,29 @@
callback: function() callback: function()
{ {
bootbox.hideAll(); bootbox.hideAll();
$('.modal-backdrop').remove(); $scope('.modal-backdrop').remove();
$(".print-timestamp").text(moment().format("l LT")); $scope(".print-timestamp").text(moment().format("l LT"));
$("#description-for-print").html($("#description").val()); $scope("#description-for-print").html($scope("#description").val());
if ($("#description").text().isEmpty()) if ($scope("#description").text().isEmpty())
{ {
$("#description-for-print").parent().addClass("d-print-none"); $scope("#description-for-print").parent().addClass("d-print-none");
} }
if (!$("#print-show-header").prop("checked")) if (!$scope("#print-show-header").prop("checked"))
{ {
$("#print-header").addClass("d-none"); $scope("#print-header").addClass("d-none");
} }
if (!$("#print-group-by-product-group").prop("checked")) if (!$scope("#print-group-by-product-group").prop("checked"))
{ {
shoppingListPrintShadowTable.rowGroup().enable(false); shoppingListPrintShadowTable.rowGroup().enable(false);
shoppingListPrintShadowTable.order.fixed({}); shoppingListPrintShadowTable.order.fixed({});
shoppingListPrintShadowTable.draw(); shoppingListPrintShadowTable.draw();
} }
$(".print-layout-container").addClass("d-none"); $scope(".print-layout-container").addClass("d-none");
$("." + $("input[name='print-layout-type']:checked").val()).removeClass("d-none"); $scope("." + $scope("input[name='print-layout-type']:checked").val()).removeClass("d-none");
window.print(); window.print();
} }
@ -468,29 +472,29 @@
}); });
}); });
$("#description").on("summernote.change", function() $scope("#description").on("summernote.change", function()
{ {
$("#save-description-button").removeClass("disabled"); $scope("#save-description-button").removeClass("disabled");
if ($("#description").summernote("isEmpty")) if ($scope("#description").summernote("isEmpty"))
{ {
$("#clear-description-button").addClass("disabled"); $scope("#clear-description-button").addClass("disabled");
} }
else else
{ {
$("#clear-description-button").removeClass("disabled"); $scope("#clear-description-button").removeClass("disabled");
} }
}); });
$(document).on("click", "#save-description-button", function(e) top.on("click", "#save-description-button", function(e)
{ {
e.preventDefault(); e.preventDefault();
document.activeElement.blur(); document.activeElement.blur();
Grocy.Api.Put('objects/shopping_lists/' + $("#selected-shopping-list").val(), { description: $("#description").val() }, Grocy.Api.Put('objects/shopping_lists/' + $scope("#selected-shopping-list").val(), { description: $scope("#description").val() },
function(result) function(result)
{ {
$("#save-description-button").addClass("disabled"); $scope("#save-description-button").addClass("disabled");
}, },
function(xhr) function(xhr)
{ {
@ -499,17 +503,17 @@
); );
}); });
$(document).on("click", "#clear-description-button", function(e) top.on("click", "#clear-description-button", function(e)
{ {
e.preventDefault(); e.preventDefault();
document.activeElement.blur(); document.activeElement.blur();
$("#description").summernote("reset"); $scope("#description").summernote("reset");
$("#save-description-button").click(); $scope("#save-description-button").click();
}); });
$("#description").trigger("summernote.change"); $scope("#description").trigger("summernote.change");
$("#save-description-button").addClass("disabled"); $scope("#save-description-button").addClass("disabled");
$(window).on("message", function(e) $(window).on("message", function(e)
{ {
@ -522,7 +526,7 @@
}); });
var dummyCanvas = document.createElement("canvas"); var dummyCanvas = document.createElement("canvas");
$("img.barcode").each(function() $scope("img.barcode").each(function()
{ {
var img = $(this); var img = $(this);
var barcode = img.attr("data-barcode").replace(/\D/g, ""); var barcode = img.attr("data-barcode").replace(/\D/g, "");
@ -547,9 +551,11 @@
img.attr("src", dummyCanvas.toDataURL("image/png")); img.attr("src", dummyCanvas.toDataURL("image/png"));
}); });
if ($(window).width() < 768 || !Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK) if (viewport.width() < 768 || !Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK)
{ {
$("#filter-container").removeClass("border-bottom"); $scope("#filter-container").removeClass("border-bottom");
} }
} }
window.shoppinglistView = shoppinglistView

View File

@ -10,16 +10,16 @@
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
$('#save-shopping-list-button').on('click', function(e) $scope('#save-shopping-list-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#shopping-list-form').serializeJSON(); var jsonData = $scope('#shopping-list-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("shopping-list-form"); Grocy.FrontendHelpers.BeginUiBusy("shopping-list-form");
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
@ -63,12 +63,12 @@
} }
}); });
$('#shopping-list-form input').keyup(function(event) $scope('#shopping-list-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('shopping-list-form'); Grocy.FrontendHelpers.ValidateForm('shopping-list-form');
}); });
$('#shopping-list-form input').keydown(function(event) $scope('#shopping-list-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -80,13 +80,13 @@
} }
else else
{ {
$('#save-shopping-list-button').click(); $scope('#save-shopping-list-button').click();
} }
} }
}); });
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
$('#name').focus(); $scope('#name').focus();
Grocy.FrontendHelpers.ValidateForm('shopping-list-form'); Grocy.FrontendHelpers.ValidateForm('shopping-list-form');
} }

View File

@ -1,4 +1,6 @@
function shoppinglistitemformView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function shoppinglistitemformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,23 +8,21 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("productamountpicker"); Grocy.Use("productamountpicker");
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
Grocy.ShoppingListItemFormInitialLoadDone = false; Grocy.ShoppingListItemFormInitialLoadDone = false;
$('#save-shoppinglist-button').on('click', function(e) $scope('#save-shoppinglist-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#shoppinglist-form').serializeJSON(); var jsonData = $scope('#shoppinglist-form').serializeJSON();
if (!jsonData.product_id) if (!jsonData.product_id)
{ {
jsonData.amount = jsonData.display_amount; jsonData.amount = jsonData.display_amount;
@ -47,8 +47,8 @@
Grocy.Api.Get('stock/products/' + jsonData.product_id, Grocy.Api.Get('stock/products/' + jsonData.product_id,
function(productDetails) function(productDetails)
{ {
window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", __t("Added %1$s of %2$s to the shopping list \"%3$s\"", parseFloat(jsonData.product_amount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }) + " " + __n(jsonData.product_amount, productDetails.default_quantity_unit_purchase.name, productDetails.default_quantity_unit_purchase.name_plural), productDetails.product.name, $("#shopping_list_id option:selected").text())), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", __t("Added %1$s of %2$s to the shopping list \"%3$s\"", parseFloat(jsonData.product_amount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }) + " " + __n(jsonData.product_amount, productDetails.default_quantity_unit_purchase.name, productDetails.default_quantity_unit_purchase.name_plural), productDetails.product.name, $scope("#shopping_list_id option:selected").text())), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("ShoppingListChanged", $scope("#shopping_list_id").val().toString()), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
}, },
function(xhr) function(xhr)
@ -59,7 +59,7 @@
} }
else else
{ {
window.location.href = U('/shoppinglist?list=' + $("#shopping_list_id").val().toString()); window.location.href = U('/shoppinglist?list=' + $scope("#shopping_list_id").val().toString());
} }
}, },
function(xhr) function(xhr)
@ -84,8 +84,8 @@
Grocy.Api.Get('stock/products/' + jsonData.product_id, Grocy.Api.Get('stock/products/' + jsonData.product_id,
function(productDetails) function(productDetails)
{ {
window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", __t("Added %1$s of %2$s to the shopping list \"%3$s\"", parseFloat(jsonData.amount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }) + " " + __n(jsonData.amount, productDetails.default_quantity_unit_purchase.name, productDetails.default_quantity_unit_purchase.name_plural), productDetails.product.name, $("#shopping_list_id option:selected").text())), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", __t("Added %1$s of %2$s to the shopping list \"%3$s\"", parseFloat(jsonData.amount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }) + " " + __n(jsonData.amount, productDetails.default_quantity_unit_purchase.name, productDetails.default_quantity_unit_purchase.name_plural), productDetails.product.name, $scope("#shopping_list_id option:selected").text())), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("ShoppingListChanged", $scope("#shopping_list_id").val().toString()), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
}, },
function(xhr) function(xhr)
@ -96,13 +96,13 @@
} }
else else
{ {
window.parent.postMessage(WindowMessageBag("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("ShoppingListChanged", $scope("#shopping_list_id").val().toString()), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
} }
} }
else else
{ {
window.location.href = U('/shoppinglist?list=' + $("#shopping_list_id").val().toString()); window.location.href = U('/shoppinglist?list=' + $scope("#shopping_list_id").val().toString());
} }
}, },
function(xhr) function(xhr)
@ -126,8 +126,8 @@
Grocy.Api.Get('stock/products/' + jsonData.product_id, Grocy.Api.Get('stock/products/' + jsonData.product_id,
function(productDetails) function(productDetails)
{ {
window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", __t("Added %1$s of %2$s to the shopping list \"%3$s\"", parseFloat(jsonData.amount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }) + " " + __n(jsonData.amount, productDetails.default_quantity_unit_purchase.name, productDetails.default_quantity_unit_purchase.name_plural), productDetails.product.name, $("#shopping_list_id option:selected").text())), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", __t("Added %1$s of %2$s to the shopping list \"%3$s\"", parseFloat(jsonData.amount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }) + " " + __n(jsonData.amount, productDetails.default_quantity_unit_purchase.name, productDetails.default_quantity_unit_purchase.name_plural), productDetails.product.name, $scope("#shopping_list_id option:selected").text())), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("ShoppingListChanged", $scope("#shopping_list_id").val().toString()), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
}, },
function(xhr) function(xhr)
@ -138,13 +138,13 @@
} }
else else
{ {
window.parent.postMessage(WindowMessageBag("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("ShoppingListChanged", $scope("#shopping_list_id").val().toString()), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
} }
} }
else else
{ {
window.location.href = U('/shoppinglist?list=' + $("#shopping_list_id").val().toString()); window.location.href = U('/shoppinglist?list=' + $scope("#shopping_list_id").val().toString());
} }
}, },
function(xhr) function(xhr)
@ -158,7 +158,7 @@
Grocy.Components.ProductPicker.GetPicker().on('change', function(e) Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{ {
var productId = $(e.target).val(); var productId = $scope(e.target).val();
if (productId) if (productId)
{ {
@ -175,13 +175,13 @@
Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.default_quantity_unit_purchase.id); Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.default_quantity_unit_purchase.id);
} }
if ($("#display_amount").val().toString().isEmpty()) if ($scope("#display_amount").val().toString().isEmpty())
{ {
$("#display_amount").val(1); $scope("#display_amount").val(1);
$("#display_amount").trigger("change"); $scope("#display_amount").trigger("change");
} }
$('#display_amount').focus(); $scope('#display_amount').focus();
Grocy.FrontendHelpers.ValidateForm('shoppinglist-form'); Grocy.FrontendHelpers.ValidateForm('shoppinglist-form');
Grocy.ShoppingListItemFormInitialLoadDone = true; Grocy.ShoppingListItemFormInitialLoadDone = true;
}, },
@ -192,8 +192,8 @@
); );
} }
$("#note").trigger("input"); $scope("#note").trigger("input");
$("#product_id").trigger("input"); $scope("#product_id").trigger("input");
}); });
Grocy.FrontendHelpers.ValidateForm('shoppinglist-form'); Grocy.FrontendHelpers.ValidateForm('shoppinglist-form');
@ -209,17 +209,17 @@
Grocy.ShoppingListItemFormInitialLoadDone = true; Grocy.ShoppingListItemFormInitialLoadDone = true;
} }
$('#display_amount').on('focus', function(e) $scope('#display_amount').on('focus', function(e)
{ {
$(this).select(); $(this).select();
}); });
$('#shoppinglist-form input').keyup(function(event) $scope('#shoppinglist-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('shoppinglist-form'); Grocy.FrontendHelpers.ValidateForm('shoppinglist-form');
}); });
$('#shoppinglist-form input').keydown(function(event) $scope('#shoppinglist-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -231,21 +231,21 @@
} }
else else
{ {
$('#save-shoppinglist-button').click(); $scope('#save-shoppinglist-button').click();
} }
} }
}); });
if (GetUriParam("list") !== undefined) if (GetUriParam("list") !== undefined)
{ {
$("#shopping_list_id").val(GetUriParam("list")); $scope("#shopping_list_id").val(GetUriParam("list"));
} }
if (GetUriParam("amount") !== undefined) if (GetUriParam("amount") !== undefined)
{ {
$("#display_amount").val(parseFloat(GetUriParam("amount"))); $scope("#display_amount").val(parseFloat(GetUriParam("amount")));
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('shoppinglist-form'); Grocy.FrontendHelpers.ValidateForm('shoppinglist-form');
} }
@ -254,7 +254,7 @@
if (GetUriParam("product") !== undefined) if (GetUriParam("product") !== undefined)
{ {
Grocy.Components.ProductPicker.GetPicker().trigger('change'); Grocy.Components.ProductPicker.GetPicker().trigger('change');
$("#display_amount").focus(); $scope("#display_amount").focus();
} }
else else
{ {
@ -262,12 +262,12 @@
} }
} }
var eitherRequiredFields = $("#product_id,#product_id_text_input,#note"); var eitherRequiredFields = $scope("#product_id,#product_id_text_input,#note");
eitherRequiredFields.prop('required', ""); eitherRequiredFields.prop('required', "");
eitherRequiredFields.on('input', function() eitherRequiredFields.on('input', function()
{ {
eitherRequiredFields.not(this).prop('required', !$(this).val().length); eitherRequiredFields.not(this).prop('required', !$(this).val().length);
Grocy.FrontendHelpers.ValidateForm('shoppinglist-form'); Grocy.FrontendHelpers.ValidateForm('shoppinglist-form', $scope);
}); });
@ -279,3 +279,6 @@
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
} }
window.shoppinglistitemformView = shoppinglistitemformView

View File

@ -1,4 +1,6 @@
function shoppinglistsettingsView(Grocy, scope = null) import { BoolVal } from '../helpers/extensions';
function shoppinglistsettingsView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,18 +8,18 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { BoolVal } from '../helpers/extensions';
if (BoolVal(Grocy.UserSettings.shopping_list_to_stock_workflow_auto_submit_when_prefilled)) if (BoolVal(Grocy.UserSettings.shopping_list_to_stock_workflow_auto_submit_when_prefilled))
{ {
$("#shopping-list-to-stock-workflow-auto-submit-when-prefilled").prop("checked", true); $scope("#shopping-list-to-stock-workflow-auto-submit-when-prefilled").prop("checked", true);
} }
if (BoolVal(Grocy.UserSettings.shopping_list_show_calendar)) if (BoolVal(Grocy.UserSettings.shopping_list_show_calendar))
{ {
$("#shopping-list-show-calendar").prop("checked", true); $scope("#shopping-list-show-calendar").prop("checked", true);
} }
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
} }
window.shoppinglistsettingsView = shoppinglistsettingsView

View File

@ -1,4 +1,6 @@
function shoppinglocationformView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function shoppinglocationformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,20 +8,18 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
$('#save-shopping-location-button').on('click', function(e) $scope('#save-shopping-location-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#shoppinglocation-form').serializeJSON(); var jsonData = $scope('#shoppinglocation-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("shoppinglocation-form"); Grocy.FrontendHelpers.BeginUiBusy("shoppinglocation-form");
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
@ -73,12 +73,12 @@
} }
}); });
$('#shoppinglocation-form input').keyup(function(event) $scope('#shoppinglocation-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('shoppinglocation-form'); Grocy.FrontendHelpers.ValidateForm('shoppinglocation-form');
}); });
$('#shoppinglocation-form input').keydown(function(event) $scope('#shoppinglocation-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -90,13 +90,15 @@
} }
else else
{ {
$('#save-shopping-location-button').click(); $scope('#save-shopping-location-button').click();
} }
} }
}); });
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
$('#name').focus(); $scope('#name').focus();
Grocy.FrontendHelpers.ValidateForm('shoppinglocation-form'); Grocy.FrontendHelpers.ValidateForm('shoppinglocation-form');
} }
window.shoppinglocationformView = shoppinglocationformView;

View File

@ -6,14 +6,14 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var locationsTable = $('#shoppinglocations-table').DataTable({ var locationsTable = $scope('#shoppinglocations-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#shoppinglocations-table tbody').removeClass("d-none"); $scope('#shoppinglocations-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(locationsTable); Grocy.FrontendHelpers.InitDataTable(locationsTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(

View File

@ -1,6 +1,8 @@
function stockentriesView(Grocy, scope = null) function stockentriesView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
var top = scope != null ? $(scope) : $(document);
if (scope != null) if (scope != null)
{ {
$scope = $(scope).find; $scope = $(scope).find;
@ -9,14 +11,14 @@
Grocy.Use("productcard"); Grocy.Use("productcard");
Grocy.Use("productpicker"); Grocy.Use("productpicker");
var stockEntriesTable = $('#stockentries-table').DataTable({ var stockEntriesTable = $scope('#stockentries-table').DataTable({
'order': [[2, 'asc']], 'order': [[2, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#stockentries-table tbody').removeClass("d-none"); $scope('#stockentries-table tbody').removeClass("d-none");
stockEntriesTable.columns.adjust().draw(); stockEntriesTable.columns.adjust().draw();
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) $.fn.dataTable.ext.search.push(function(settings, data, dataIndex)
@ -31,7 +33,7 @@
return false; return false;
}); });
$("#clear-filter-button").on("click", function() $scope("#clear-filter-button").on("click", function()
{ {
Grocy.Components.ProductPicker.Clear(); Grocy.Components.ProductPicker.Clear();
stockEntriesTable.draw(); stockEntriesTable.draw();
@ -47,7 +49,7 @@
stockEntriesTable.draw(); stockEntriesTable.draw();
}); });
$(document).on('click', '.stock-consume-button', function(e) top.on('click', '.stock-consume-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -57,13 +59,15 @@
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
var productId = $(e.currentTarget).attr('data-product-id');
var locationId = $(e.currentTarget).attr('data-location-id');
var specificStockEntryId = $(e.currentTarget).attr('data-stock-id');
var stockRowId = $(e.currentTarget).attr('data-stockrow-id');
var consumeAmount = $(e.currentTarget).attr('data-consume-amount');
var wasSpoiled = $(e.currentTarget).hasClass("stock-consume-button-spoiled"); var target = $(e.currentTarget);
var productId = target.attr('data-product-id');
var locationId = target.attr('data-location-id');
var specificStockEntryId = target.attr('data-stock-id');
var stockRowId = target.attr('data-stockrow-id');
var consumeAmount = target.attr('data-consume-amount');
var wasSpoiled = target.hasClass("stock-consume-button-spoiled");
Grocy.Api.Post('stock/products/' + productId + '/consume', { 'amount': consumeAmount, 'spoiled': wasSpoiled, 'location_id': locationId, 'stock_entry_id': specificStockEntryId, 'exact_amount': true }, Grocy.Api.Post('stock/products/' + productId + '/consume', { 'amount': consumeAmount, 'spoiled': wasSpoiled, 'location_id': locationId, 'stock_entry_id': specificStockEntryId, 'exact_amount': true },
function(bookingResponse) function(bookingResponse)
@ -96,7 +100,7 @@
); );
}); });
$(document).on('click', '.product-open-button', function(e) top.on('click', '.product-open-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -106,12 +110,13 @@
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
var productId = $(e.currentTarget).attr('data-product-id'); var button = $(e.currentTarget)
var productName = $(e.currentTarget).attr('data-product-name'); var productId = button.attr('data-product-id');
var productQuName = $(e.currentTarget).attr('data-product-qu-name'); var productName = button.attr('data-product-name');
var specificStockEntryId = $(e.currentTarget).attr('data-stock-id'); var productQuName = button.attr('data-product-qu-name');
var stockRowId = $(e.currentTarget).attr('data-stockrow-id'); var specificStockEntryId = button.attr('data-stock-id');
var button = $(e.currentTarget); var stockRowId = button.attr('data-stockrow-id');
Grocy.Api.Post('stock/products/' + productId + '/open', { 'amount': 1, 'stock_entry_id': specificStockEntryId }, Grocy.Api.Post('stock/products/' + productId + '/open', { 'amount': 1, 'stock_entry_id': specificStockEntryId },
function(bookingResponse) function(bookingResponse)
@ -129,13 +134,13 @@
); );
}); });
$(document).on("click", ".stock-name-cell", function(e) top.on("click", ".stock-name-cell", function(e)
{ {
Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-stock-id")); Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-stock-id"));
$("#stockentry-productcard-modal").modal("show"); $scope("#stockentry-productcard-modal").modal("show");
}); });
$(document).on('click', '.stockentry-grocycode-stockentry-label-print', function(e) top.on('click', '.stockentry-grocycode-stockentry-label-print', function(e)
{ {
e.preventDefault(); e.preventDefault();
document.activeElement.blur(); document.activeElement.blur();
@ -155,7 +160,7 @@
Grocy.Api.Get("stock/entry/" + stockRowId, Grocy.Api.Get("stock/entry/" + stockRowId,
function(result) function(result)
{ {
var stockRow = $('#stock-' + stockRowId + '-row'); var stockRow = $scope('#stock-' + stockRowId + '-row');
// If the stock row not exists / is invisible (happens after consume/undo because the undone new stock row has different id), just reload the page for now // If the stock row not exists / is invisible (happens after consume/undo because the undone new stock row has different id), just reload the page for now
if (!stockRow.length || stockRow.hasClass("d-none")) if (!stockRow.length || stockRow.hasClass("d-none"))
@ -167,7 +172,7 @@
{ {
animateCSS("#stock-" + stockRowId + "-row", "fadeOut", function() animateCSS("#stock-" + stockRowId + "-row", "fadeOut", function()
{ {
$("#stock-" + stockRowId + "-row").addClass("d-none"); $scope("#stock-" + stockRowId + "-row").addClass("d-none");
}); });
} }
else else
@ -199,11 +204,11 @@
animateCSS("#stock-" + stockRowId + "-row td:not(:first)", "shake"); animateCSS("#stock-" + stockRowId + "-row td:not(:first)", "shake");
$('#stock-' + stockRowId + '-amount').text(result.amount); $scope('#stock-' + stockRowId + '-amount').text(result.amount);
$('#stock-' + stockRowId + '-due-date').text(result.best_before_date); $scope('#stock-' + stockRowId + '-due-date').text(result.best_before_date);
$('#stock-' + stockRowId + '-due-date-timeago').attr('datetime', result.best_before_date + ' 23:59:59'); $scope('#stock-' + stockRowId + '-due-date-timeago').attr('datetime', result.best_before_date + ' 23:59:59');
$(".stock-consume-button").attr('data-location-id', result.location_id); $scope(".stock-consume-button").attr('data-location-id', result.location_id);
var locationName = ""; var locationName = "";
Grocy.Api.Get("objects/locations/" + result.location_id, Grocy.Api.Get("objects/locations/" + result.location_id,
@ -211,8 +216,8 @@
{ {
locationName = locationResult.name; locationName = locationResult.name;
$('#stock-' + stockRowId + '-location').attr('data-location-id', result.location_id); $scope('#stock-' + stockRowId + '-location').attr('data-location-id', result.location_id);
$('#stock-' + stockRowId + '-location').text(locationName); $scope('#stock-' + stockRowId + '-location').text(locationName);
}, },
function(xhr) function(xhr)
{ {
@ -220,9 +225,9 @@
} }
); );
$('#stock-' + stockRowId + '-price').text(result.price); $scope('#stock-' + stockRowId + '-price').text(result.price);
$('#stock-' + stockRowId + '-purchased-date').text(result.purchased_date); $scope('#stock-' + stockRowId + '-purchased-date').text(result.purchased_date);
$('#stock-' + stockRowId + '-purchased-date-timeago').attr('datetime', result.purchased_date + ' 23:59:59'); $scope('#stock-' + stockRowId + '-purchased-date-timeago').attr('datetime', result.purchased_date + ' 23:59:59');
var shoppingLocationName = ""; var shoppingLocationName = "";
Grocy.Api.Get("objects/shopping_locations/" + result.shopping_location_id, Grocy.Api.Get("objects/shopping_locations/" + result.shopping_location_id,
@ -230,8 +235,8 @@
{ {
shoppingLocationName = shoppingLocationResult.name; shoppingLocationName = shoppingLocationResult.name;
$('#stock-' + stockRowId + '-shopping-location').attr('data-shopping-location-id', result.location_id); $scope('#stock-' + stockRowId + '-shopping-location').attr('data-shopping-location-id', result.location_id);
$('#stock-' + stockRowId + '-shopping-location').text(shoppingLocationName); $scope('#stock-' + stockRowId + '-shopping-location').text(shoppingLocationName);
}, },
function(xhr) function(xhr)
{ {
@ -241,12 +246,12 @@
if (result.open == 1) if (result.open == 1)
{ {
$('#stock-' + stockRowId + '-opened-amount').text(__t('Opened')); $scope('#stock-' + stockRowId + '-opened-amount').text(__t('Opened'));
} }
else else
{ {
$('#stock-' + stockRowId + '-opened-amount').text(""); $scope('#stock-' + stockRowId + '-opened-amount').text("");
$(".product-open-button[data-stockrow-id='" + stockRowId + "']").removeClass("disabled"); $scope(".product-open-button[data-stockrow-id='" + stockRowId + "']").removeClass("disabled");
} }
} }
@ -277,10 +282,10 @@
Grocy.Components.ProductPicker.GetPicker().trigger('change'); Grocy.Components.ProductPicker.GetPicker().trigger('change');
$(document).on("click", ".product-name-cell", function(e) top.on("click", ".product-name-cell", function(e)
{ {
Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-product-id")); Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-product-id"));
$("#productcard-modal").modal("show"); $scope("#productcard-modal").modal("show");
}); });
} }

View File

@ -1,4 +1,6 @@
function stockentryformView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function stockentryformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,24 +8,22 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("datetimepicker"); Grocy.Use("datetimepicker");
Grocy.Use("datetimepicker2"); Grocy.Use("datetimepicker2");
Grocy.Use("locationpicker"); Grocy.Use("locationpicker");
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
Grocy.Use("shoppinglocationpicker"); Grocy.Use("shoppinglocationpicker");
$('#save-stockentry-button').on('click', function(e) $scope('#save-stockentry-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonForm = $('#stockentry-form').serializeJSON(); var jsonForm = $scope('#stockentry-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("stockentry-form"); Grocy.FrontendHelpers.BeginUiBusy("stockentry-form");
if (!jsonForm.price.toString().isEmpty()) if (!jsonForm.price.toString().isEmpty())
@ -48,7 +48,7 @@
jsonData.location_id = 1; jsonData.location_id = 1;
} }
jsonData.open = $("#open").is(":checked"); jsonData.open = $scope("#open").is(":checked");
Grocy.Api.Put("stock/entry/" + Grocy.EditObjectId, jsonData, Grocy.Api.Put("stock/entry/" + Grocy.EditObjectId, jsonData,
function(result) function(result)
@ -70,12 +70,12 @@
Grocy.FrontendHelpers.ValidateForm('stockentry-form'); Grocy.FrontendHelpers.ValidateForm('stockentry-form');
$('#stockentry-form input').keyup(function(event) $scope('#stockentry-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('stockentry-form'); Grocy.FrontendHelpers.ValidateForm('stockentry-form');
}); });
$('#stockentry-form input').keydown(function(event) $scope('#stockentry-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -87,7 +87,7 @@
} }
else else
{ {
$('#save-stockentry-button').click(); $scope('#save-stockentry-button').click();
} }
} }
}); });
@ -115,7 +115,7 @@
Grocy.Api.Get('stock/products/' + Grocy.EditObjectProductId, Grocy.Api.Get('stock/products/' + Grocy.EditObjectProductId,
function(productDetails) function(productDetails)
{ {
$('#amount_qu_unit').text(productDetails.quantity_unit_stock.name); $scope('#amount_qu_unit').text(productDetails.quantity_unit_stock.name);
}, },
function(xhr) function(xhr)
{ {
@ -123,11 +123,13 @@
} }
); );
$("#amount").on("focus", function(e) $scope("#amount").on("focus", function(e)
{ {
$(this).select(); $(this).select();
}); });
$("#amount").focus(); $scope("#amount").focus();
Grocy.FrontendHelpers.ValidateForm("stockentry-form"); Grocy.FrontendHelpers.ValidateForm("stockentry-form");
} }
window.stockentryformView = stockentryformView;

View File

@ -1,12 +1,13 @@
function stockjournalView(Grocy, scope = null) function stockjournalView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
var top = scope != null ? $(scope) : $(document);
if (scope != null) if (scope != null)
{ {
$scope = $(scope).find; $scope = $(scope).find;
} }
var stockJournalTable = $('#stock-journal-table').DataTable({ var stockJournalTable = $scope('#stock-journal-table').DataTable({
'paginate': true, 'paginate': true,
'order': [[3, 'desc']], 'order': [[3, 'desc']],
'columnDefs': [ 'columnDefs': [
@ -14,7 +15,7 @@
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#stock-journal-table tbody').removeClass("d-none"); $scope('#stock-journal-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(stockJournalTable); Grocy.FrontendHelpers.InitDataTable(stockJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#product-filter", 1, stockJournalTable); Grocy.FrontendHelpers.MakeFilterForColumn("#product-filter", 1, stockJournalTable);
@ -24,21 +25,21 @@
if (typeof GetUriParam("product") !== "undefined") if (typeof GetUriParam("product") !== "undefined")
{ {
$("#product-filter").val(GetUriParam("product")); $scope("#product-filter").val(GetUriParam("product"));
$("#product-filter").trigger("change"); $scope("#product-filter").trigger("change");
} }
$(document).on('click', '.undo-stock-booking-button', function(e) top.on('click', '.undo-stock-booking-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
var bookingId = $(e.currentTarget).attr('data-booking-id'); var bookingId = $scope(e.currentTarget).attr('data-booking-id');
var correlationId = $("#stock-booking-" + bookingId + "-row").attr("data-correlation-id"); var correlationId = $scope("#stock-booking-" + bookingId + "-row").attr("data-correlation-id");
var correspondingBookingsRoot = $("#stock-booking-" + bookingId + "-row"); var correspondingBookingsRoot = $scope("#stock-booking-" + bookingId + "-row");
if (!correlationId.isEmpty()) if (!correlationId.isEmpty())
{ {
correspondingBookingsRoot = $(".stock-booking-correlation-" + correlationId); correspondingBookingsRoot = $scope(".stock-booking-correlation-" + correlationId);
} }
Grocy.Api.Post('stock/bookings/' + bookingId.toString() + '/undo', {}, Grocy.Api.Post('stock/bookings/' + bookingId.toString() + '/undo', {},

View File

@ -6,7 +6,7 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var journalSummaryTable = $('#stock-journal-summary-table').DataTable({ var journalSummaryTable = $scope('#stock-journal-summary-table').DataTable({
'paginate': true, 'paginate': true,
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
@ -14,7 +14,7 @@
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#stock-journal-summary-table tbody').removeClass("d-none"); $scope('#stock-journal-summary-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(journalSummaryTable); Grocy.FrontendHelpers.InitDataTable(journalSummaryTable);

View File

@ -1,6 +1,7 @@
function stockoverviewView(Grocy, scope = null) function stockoverviewView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
var top = scope != null ? $(scope) : $(document);
if (scope != null) if (scope != null)
{ {
$scope = $(scope).find; $scope = $(scope).find;
@ -8,7 +9,7 @@
Grocy.Use("productcard"); Grocy.Use("productcard");
var stockOverviewTable = $('#stock-overview-table').DataTable({ var stockOverviewTable = $scope('#stock-overview-table').DataTable({
'order': [[5, 'asc']], 'order': [[5, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
@ -34,18 +35,18 @@
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#stock-overview-table tbody').removeClass("d-none"); $scope('#stock-overview-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(stockOverviewTable); Grocy.FrontendHelpers.InitDataTable(stockOverviewTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#location-filter", 6, stockOverviewTable, null, false, (value) => "xx" + value + "xx"); Grocy.FrontendHelpers.MakeFilterForColumn("#location-filter", 6, stockOverviewTable, null, false, (value) => "xx" + value + "xx");
Grocy.FrontendHelpers.MakeFilterForColumn("#product-group-filter", 8, stockOverviewTable, null, false, (value) => "xx" + value + "xx"); Grocy.FrontendHelpers.MakeFilterForColumn("#product-group-filter", 8, stockOverviewTable, null, false, (value) => "xx" + value + "xx");
Grocy.FrontendHelpers.MakeStatusFilter(stockOverviewTable, 7); Grocy.FrontendHelpers.MakeStatusFilter(stockOverviewTable, 7);
$(document).on('click', '.stockentry-grocycode-product-label-print', function(e) top.on('click', '.stockentry-grocycode-product-label-print', function(e)
{ {
e.preventDefault(); e.preventDefault();
document.activeElement.blur(); document.activeElement.blur();
var productId = $(e.currentTarget).attr('data-product-id'); var productId = $scope(e.currentTarget).attr('data-product-id');
Grocy.Api.Get('stock/products/' + productId + '/printlabel', function(labelData) Grocy.Api.Get('stock/products/' + productId + '/printlabel', function(labelData)
{ {
if (Grocy.Webhooks.labelprinter !== undefined) if (Grocy.Webhooks.labelprinter !== undefined)
@ -55,7 +56,7 @@
}); });
}); });
$(document).on('click', '.product-consume-button', function(e) top.on('click', '.product-consume-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -65,7 +66,7 @@
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
var target = $(e.currentTarget); var target = $scope(e.currentTarget);
var productId = target.attr('data-product-id'); var productId = target.attr('data-product-id');
var consumeAmount = target.attr('data-consume-amount'); var consumeAmount = target.attr('data-consume-amount');
@ -113,7 +114,7 @@
); );
}); });
$(document).on('click', '.product-open-button', function(e) top.on('click', '.product-open-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -123,7 +124,7 @@
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
var button = $(e.currentTarget); var button = $scope(e.currentTarget);
var productId = button.attr('data-product-id'); var productId = button.attr('data-product-id');
var productName = button.attr('data-product-name'); var productName = button.attr('data-product-name');
@ -161,7 +162,7 @@
); );
}); });
$(document).on("click", ".product-name-cell", function(e) top.on("click", ".product-name-cell", function(e)
{ {
Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-product-id")); Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-product-id"));
$("#stockoverview-productcard-modal").modal("show"); $("#stockoverview-productcard-modal").modal("show");
@ -192,14 +193,14 @@
} }
); );
var nextXDays = $("#info-duesoon-products").data("next-x-days"); var nextXDays = $scope("#info-duesoon-products").data("next-x-days");
Grocy.Api.Get('stock/volatile?due_soon_days=' + nextXDays, Grocy.Api.Get('stock/volatile?due_soon_days=' + nextXDays,
function(result) function(result)
{ {
$("#info-duesoon-products").html('<span class="d-block d-md-none">' + result.due_products.length + ' <i class="fas fa-clock"></i></span><span class="d-none d-md-block">' + __n(result.due_products.length, '%s product is due', '%s products are due') + ' ' + __n(nextXDays, 'within the next day', 'within the next %s days') + '</span>'); $scope("#info-duesoon-products").html('<span class="d-block d-md-none">' + result.due_products.length + ' <i class="fas fa-clock"></i></span><span class="d-none d-md-block">' + __n(result.due_products.length, '%s product is due', '%s products are due') + ' ' + __n(nextXDays, 'within the next day', 'within the next %s days') + '</span>');
$("#info-overdue-products").html('<span class="d-block d-md-none">' + result.overdue_products.length + ' <i class="fas fa-times-circle"></i></span><span class="d-none d-md-block">' + __n(result.overdue_products.length, '%s product is overdue', '%s products are overdue') + '</span>'); $scope("#info-overdue-products").html('<span class="d-block d-md-none">' + result.overdue_products.length + ' <i class="fas fa-times-circle"></i></span><span class="d-none d-md-block">' + __n(result.overdue_products.length, '%s product is overdue', '%s products are overdue') + '</span>');
$("#info-expired-products").html('<span class="d-block d-md-none">' + result.expired_products.length + ' <i class="fas fa-times-circle"></i></span><span class="d-none d-md-block">' + __n(result.expired_products.length, '%s product is expired', '%s products are expired') + '</span>'); $scope("#info-expired-products").html('<span class="d-block d-md-none">' + result.expired_products.length + ' <i class="fas fa-times-circle"></i></span><span class="d-none d-md-block">' + __n(result.expired_products.length, '%s product is expired', '%s products are expired') + '</span>');
$("#info-missing-products").html('<span class="d-block d-md-none">' + result.missing_products.length + ' <i class="fas fa-exclamation-circle"></i></span><span class="d-none d-md-block">' + __n(result.missing_products.length, '%s product is below defined min. stock amount', '%s products are below defined min. stock amount') + '</span>'); $scope("#info-missing-products").html('<span class="d-block d-md-none">' + result.missing_products.length + ' <i class="fas fa-exclamation-circle"></i></span><span class="d-none d-md-block">' + __n(result.missing_products.length, '%s product is below defined min. stock amount', '%s products are below defined min. stock amount') + '</span>');
}, },
function(xhr) function(xhr)
{ {
@ -222,8 +223,8 @@
RefreshProductRow(result.product.parent_product_id); RefreshProductRow(result.product.parent_product_id);
} }
var productRow = $('#product-' + productId + '-row'); var productRow = $scope('#product-' + productId + '-row');
var dueSoonThreshold = moment().add($("#info-duesoon-products").data("next-x-days"), "days"); var dueSoonThreshold = moment().add($scope("#info-duesoon-products").data("next-x-days"), "days");
var now = moment(); var now = moment();
var nextDueDate = moment(result.next_due_date); var nextDueDate = moment(result.next_due_date);
@ -253,29 +254,29 @@
{ {
animateCSS("#product-" + productId + "-row", "fadeOut", function() animateCSS("#product-" + productId + "-row", "fadeOut", function()
{ {
$("#product-" + productId + "-row").tooltip("hide"); $scope("#product-" + productId + "-row").tooltip("hide");
$("#product-" + productId + "-row").addClass("d-none"); $scope("#product-" + productId + "-row").addClass("d-none");
}); });
} }
else else
{ {
animateCSS("#product-" + productId + "-row td:not(:first)", "shake"); animateCSS("#product-" + productId + "-row td:not(:first)", "shake");
$('#product-' + productId + '-qu-name').text(__n(result.stock_amount, result.quantity_unit_stock.name, result.quantity_unit_stock.name_plural)); $scope('#product-' + productId + '-qu-name').text(__n(result.stock_amount, result.quantity_unit_stock.name, result.quantity_unit_stock.name_plural));
$('#product-' + productId + '-amount').text(result.stock_amount); $scope('#product-' + productId + '-amount').text(result.stock_amount);
$('#product-' + productId + '-consume-all-button').attr('data-consume-amount', result.stock_amount); $scope('#product-' + productId + '-consume-all-button').attr('data-consume-amount', result.stock_amount);
$('#product-' + productId + '-value').text(result.stock_value); $scope('#product-' + productId + '-value').text(result.stock_value);
$('#product-' + productId + '-next-due-date').text(result.next_due_date); $scope('#product-' + productId + '-next-due-date').text(result.next_due_date);
$('#product-' + productId + '-next-due-date-timeago').attr('datetime', result.next_due_date); $scope('#product-' + productId + '-next-due-date-timeago').attr('datetime', result.next_due_date);
var openedAmount = result.stock_amount_opened || 0; var openedAmount = result.stock_amount_opened || 0;
if (openedAmount > 0) if (openedAmount > 0)
{ {
$('#product-' + productId + '-opened-amount').text(__t('%s opened', openedAmount)); $scope('#product-' + productId + '-opened-amount').text(__t('%s opened', openedAmount));
} }
else else
{ {
$('#product-' + productId + '-opened-amount').text(""); $scope('#product-' + productId + '-opened-amount').text("");
} }
if (result.stock_amount == 0 && result.product.min_stock_amount > 0) if (result.stock_amount == 0 && result.product.min_stock_amount > 0)
@ -284,29 +285,29 @@
} }
} }
$('#product-' + productId + '-next-due-date').text(result.next_due_date); $scope('#product-' + productId + '-next-due-date').text(result.next_due_date);
$('#product-' + productId + '-next-due-date-timeago').attr('datetime', result.next_due_date + ' 23:59:59'); $scope('#product-' + productId + '-next-due-date-timeago').attr('datetime', result.next_due_date + ' 23:59:59');
if (result.stock_amount_opened > 0) if (result.stock_amount_opened > 0)
{ {
$('#product-' + productId + '-opened-amount').text(__t('%s opened', result.stock_amount_opened)); $scope('#product-' + productId + '-opened-amount').text(__t('%s opened', result.stock_amount_opened));
} }
else else
{ {
$('#product-' + productId + '-opened-amount').text(""); $scope('#product-' + productId + '-opened-amount').text("");
} }
if (parseInt(result.is_aggregated_amount) === 1) if (parseInt(result.is_aggregated_amount) === 1)
{ {
$('#product-' + productId + '-amount-aggregated').text(result.stock_amount_aggregated); $scope('#product-' + productId + '-amount-aggregated').text(result.stock_amount_aggregated);
if (result.stock_amount_opened_aggregated > 0) if (result.stock_amount_opened_aggregated > 0)
{ {
$('#product-' + productId + '-opened-amount-aggregated').text(__t('%s opened', result.stock_amount_opened_aggregated)); $scope('#product-' + productId + '-opened-amount-aggregated').text(__t('%s opened', result.stock_amount_opened_aggregated));
} }
else else
{ {
$('#product-' + productId + '-opened-amount-aggregated').text(""); $scope('#product-' + productId + '-opened-amount-aggregated').text("");
} }
} }

View File

@ -1,4 +1,6 @@
function stocksettingsView(Grocy, scope = null) import { BoolVal } from '../helpers/extensions';
function stocksettingsView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,51 +8,52 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { BoolVal } from '../helpers/extensions';
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
$("#product_presets_location_id").val(Grocy.UserSettings.product_presets_location_id); $scope("#product_presets_location_id").val(Grocy.UserSettings.product_presets_location_id);
$("#product_presets_product_group_id").val(Grocy.UserSettings.product_presets_product_group_id); $scope("#product_presets_product_group_id").val(Grocy.UserSettings.product_presets_product_group_id);
$("#product_presets_qu_id").val(Grocy.UserSettings.product_presets_qu_id); $scope("#product_presets_qu_id").val(Grocy.UserSettings.product_presets_qu_id);
$("#stock_due_soon_days").val(Grocy.UserSettings.stock_due_soon_days); $scope("#stock_due_soon_days").val(Grocy.UserSettings.stock_due_soon_days);
$("#stock_default_purchase_amount").val(Grocy.UserSettings.stock_default_purchase_amount); $scope("#stock_default_purchase_amount").val(Grocy.UserSettings.stock_default_purchase_amount);
$("#stock_default_consume_amount").val(Grocy.UserSettings.stock_default_consume_amount); $scope("#stock_default_consume_amount").val(Grocy.UserSettings.stock_default_consume_amount);
$("#stock_decimal_places_amounts").val(Grocy.UserSettings.stock_decimal_places_amounts); $scope("#stock_decimal_places_amounts").val(Grocy.UserSettings.stock_decimal_places_amounts);
$("#stock_decimal_places_prices").val(Grocy.UserSettings.stock_decimal_places_prices); $scope("#stock_decimal_places_prices").val(Grocy.UserSettings.stock_decimal_places_prices);
if (BoolVal(Grocy.UserSettings.show_icon_on_stock_overview_page_when_product_is_on_shopping_list)) if (BoolVal(Grocy.UserSettings.show_icon_on_stock_overview_page_when_product_is_on_shopping_list))
{ {
$("#show_icon_on_stock_overview_page_when_product_is_on_shopping_list").prop("checked", true); $scope("#show_icon_on_stock_overview_page_when_product_is_on_shopping_list").prop("checked", true);
} }
if (BoolVal(Grocy.UserSettings.show_purchased_date_on_purchase)) if (BoolVal(Grocy.UserSettings.show_purchased_date_on_purchase))
{ {
$("#show_purchased_date_on_purchase").prop("checked", true); $scope("#show_purchased_date_on_purchase").prop("checked", true);
} }
if (BoolVal(Grocy.UserSettings.show_warning_on_purchase_when_due_date_is_earlier_than_next)) if (BoolVal(Grocy.UserSettings.show_warning_on_purchase_when_due_date_is_earlier_than_next))
{ {
$("#show_warning_on_purchase_when_due_date_is_earlier_than_next").prop("checked", true); $scope("#show_warning_on_purchase_when_due_date_is_earlier_than_next").prop("checked", true);
} }
if (BoolVal(Grocy.UserSettings.stock_default_consume_amount_use_quick_consume_amount)) if (BoolVal(Grocy.UserSettings.stock_default_consume_amount_use_quick_consume_amount))
{ {
$("#stock_default_consume_amount_use_quick_consume_amount").prop("checked", true); $scope("#stock_default_consume_amount_use_quick_consume_amount").prop("checked", true);
$("#stock_default_consume_amount").attr("disabled", ""); $scope("#stock_default_consume_amount").attr("disabled", "");
} }
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
$("#stock_default_consume_amount_use_quick_consume_amount").on("click", function() $scope("#stock_default_consume_amount_use_quick_consume_amount").on("click", function()
{ {
if (this.checked) if (this.checked)
{ {
$("#stock_default_consume_amount").attr("disabled", ""); $scope("#stock_default_consume_amount").attr("disabled", "");
} }
else else
{ {
$("#stock_default_consume_amount").removeAttr("disabled"); $scope("#stock_default_consume_amount").removeAttr("disabled");
} }
}); });
} }
window.stocksettingsView = stocksettingsView;

View File

@ -6,14 +6,14 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var categoriesTable = $('#taskcategories-table').DataTable({ var categoriesTable = $scope('#taskcategories-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#taskcategories-table tbody').removeClass("d-none"); $scope('#taskcategories-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(categoriesTable); Grocy.FrontendHelpers.InitDataTable(categoriesTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(

View File

@ -8,16 +8,16 @@
import { WindowMessageBag } from '../helpers/messagebag'; import { WindowMessageBag } from '../helpers/messagebag';
$('#save-task-category-button').on('click', function(e) $scope('#save-task-category-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#task-category-form').serializeJSON(); var jsonData = $scope('#task-category-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("task-category-form"); Grocy.FrontendHelpers.BeginUiBusy("task-category-form");
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
@ -71,12 +71,12 @@
} }
}); });
$('#task-category-form input').keyup(function(event) $scope('#task-category-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('task-category-form'); Grocy.FrontendHelpers.ValidateForm('task-category-form');
}); });
$('#task-category-form input').keydown(function(event) $scope('#task-category-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -88,13 +88,13 @@
} }
else else
{ {
$('#save-task-category-button').click(); $scope('#save-task-category-button').click();
} }
} }
}); });
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
$('#name').focus(); $scope('#name').focus();
Grocy.FrontendHelpers.ValidateForm('task-category-form'); Grocy.FrontendHelpers.ValidateForm('task-category-form');
} }

View File

@ -11,16 +11,16 @@
Grocy.Use("datetimepicker"); Grocy.Use("datetimepicker");
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
$('#save-task-button').on('click', function(e) $scope('#save-task-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#task-form').serializeJSON(); var jsonData = $scope('#task-form').serializeJSON();
jsonData.assigned_to_user_id = jsonData.user_id; jsonData.assigned_to_user_id = jsonData.user_id;
delete jsonData.user_id; delete jsonData.user_id;
jsonData.due_date = Grocy.Components.DateTimePicker.GetValue(); jsonData.due_date = Grocy.Components.DateTimePicker.GetValue();
@ -78,12 +78,12 @@
} }
}); });
$('#task-form input').keyup(function(event) $scope('#task-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('task-form'); Grocy.FrontendHelpers.ValidateForm('task-form');
}); });
$('#task-form input').keydown(function(event) $scope('#task-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -95,13 +95,13 @@
} }
else else
{ {
$('#save-task-button').click(); $scope('#save-task-button').click();
} }
} }
}); });
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
$('#name').focus(); $scope('#name').focus();
Grocy.Components.DateTimePicker.GetInputElement().trigger('input'); Grocy.Components.DateTimePicker.GetInputElement().trigger('input');
Grocy.FrontendHelpers.ValidateForm('task-form'); Grocy.FrontendHelpers.ValidateForm('task-form');

View File

@ -1,6 +1,8 @@
function tasksView(Grocy, scope = null) function tasksView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
var top = scope != null ? $(scope) : $(document);
if (scope != null) if (scope != null)
{ {
$scope = $(scope).find; $scope = $(scope).find;
@ -8,7 +10,7 @@
Grocy.Use("userpicker"); Grocy.Use("userpicker");
var tasksTable = $('#tasks-table').DataTable({ var tasksTable = $scope('#tasks-table').DataTable({
'order': [[2, 'asc']], 'order': [[2, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
@ -21,16 +23,16 @@
dataSrc: 3 dataSrc: 3
} }
}); });
$('#tasks-table tbody').removeClass("d-none"); $scope('#tasks-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(tasksTable, null, function() Grocy.FrontendHelpers.InitDataTable(tasksTable, null, function()
{ {
$("#search").val(""); $scope("#search").val("");
$("#search").trigger("keyup"); $scope("#search").trigger("keyup");
$("#show-done-tasks").trigger('checked', false); $scope("#show-done-tasks").trigger('checked', false);
}); });
Grocy.FrontendHelpers.MakeStatusFilter(tasksTable, 5); Grocy.FrontendHelpers.MakeStatusFilter(tasksTable, 5);
$(document).on('click', '.do-task-button', function(e) top.on('click', '.do-task-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -40,26 +42,27 @@
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
var taskId = $(e.currentTarget).attr('data-task-id'); var target = $(e.currentTarget);
var taskName = $(e.currentTarget).attr('data-task-name'); var taskId = target.attr('data-task-id');
var taskName = target.attr('data-task-name');
var doneTime = moment().format('YYYY-MM-DD HH:mm:ss'); var doneTime = moment().format('YYYY-MM-DD HH:mm:ss');
Grocy.Api.Post('tasks/' + taskId + '/complete', { 'done_time': doneTime }, Grocy.Api.Post('tasks/' + taskId + '/complete', { 'done_time': doneTime },
function() function()
{ {
if (!$("#show-done-tasks").is(":checked")) if (!$scope("#show-done-tasks").is(":checked"))
{ {
animateCSS("#task-" + taskId + "-row", "fadeOut", function() animateCSS("#task-" + taskId + "-row", "fadeOut", function()
{ {
$("#task-" + taskId + "-row").tooltip("hide"); $scope("#task-" + taskId + "-row").tooltip("hide");
$("#task-" + taskId + "-row").remove(); $scope("#task-" + taskId + "-row").remove();
}); });
} }
else else
{ {
$('#task-' + taskId + '-row').addClass("text-muted"); $scope('#task-' + taskId + '-row').addClass("text-muted");
$('#task-' + taskId + '-name').addClass("text-strike-through"); $scope('#task-' + taskId + '-name').addClass("text-strike-through");
$('.do-task-button[data-task-id="' + taskId + '"]').addClass("disabled"); $scope('.do-task-button[data-task-id="' + taskId + '"]').addClass("disabled");
} }
Grocy.FrontendHelpers.EndUiBusy(); Grocy.FrontendHelpers.EndUiBusy();
@ -75,7 +78,7 @@
); );
}); });
$(document).on('click', '.undo-task-button', function(e) top.on('click', '.undo-task-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
@ -85,7 +88,7 @@
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
var taskId = $(e.currentTarget).attr('data-task-id'); var taskId = $scope(e.currentTarget).attr('data-task-id');
Grocy.Api.Post('tasks/' + taskId + '/undo', {}, Grocy.Api.Post('tasks/' + taskId + '/undo', {},
function() function()
@ -110,13 +113,13 @@
{ {
animateCSS("#task-" + objectId + "-row", "fadeOut", function() animateCSS("#task-" + objectId + "-row", "fadeOut", function()
{ {
$("#task-" + objectId + "-row").tooltip("hide"); $scope("#task-" + objectId + "-row").tooltip("hide");
$("#task-" + objectId + "-row").remove(); $scope("#task-" + objectId + "-row").remove();
}); });
} }
); );
$("#show-done-tasks").change(function() $scope("#show-done-tasks").change(function()
{ {
if (this.checked) if (this.checked)
{ {
@ -130,12 +133,12 @@
if (GetUriParam('include_done')) if (GetUriParam('include_done'))
{ {
$("#show-done-tasks").prop('checked', true); $scope("#show-done-tasks").prop('checked', true);
} }
function RefreshStatistics() function RefreshStatistics()
{ {
var nextXDays = $("#info-due-tasks").data("next-x-days"); var nextXDays = $scope("#info-due-tasks").data("next-x-days");
Grocy.Api.Get('tasks', Grocy.Api.Get('tasks',
function(result) function(result)
{ {
@ -156,8 +159,8 @@
} }
}); });
$("#info-due-tasks").html('<span class="d-block d-md-none">' + dueCount + ' <i class="fas fa-clock"></i></span><span class="d-none d-md-block">' + __n(dueCount, '%s task is due to be done', '%s tasks are due to be done') + ' ' + __n(nextXDays, 'within the next day', 'within the next %s days')); $scope("#info-due-tasks").html('<span class="d-block d-md-none">' + dueCount + ' <i class="fas fa-clock"></i></span><span class="d-none d-md-block">' + __n(dueCount, '%s task is due to be done', '%s tasks are due to be done') + ' ' + __n(nextXDays, 'within the next day', 'within the next %s days'));
$("#info-overdue-tasks").html('<span class="d-block d-md-none">' + overdueCount + ' <i class="fas fa-times-circle"></i></span><span class="d-none d-md-block">' + __n(overdueCount, '%s task is overdue to be done', '%s tasks are overdue to be done')); $scope("#info-overdue-tasks").html('<span class="d-block d-md-none">' + overdueCount + ' <i class="fas fa-times-circle"></i></span><span class="d-none d-md-block">' + __n(overdueCount, '%s task is overdue to be done', '%s tasks are overdue to be done'));
}, },
function(xhr) function(xhr)
{ {

View File

@ -8,7 +8,7 @@
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
$("#tasks_due_soon_days").val(Grocy.UserSettings.tasks_due_soon_days); $scope("#tasks_due_soon_days").val(Grocy.UserSettings.tasks_due_soon_days);
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();

View File

@ -1,4 +1,6 @@
function transferView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function transferView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,32 +8,30 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("productpicker"); Grocy.Use("productpicker");
Grocy.Use("productamountpicker"); Grocy.Use("productamountpicker");
Grocy.Use("productcard"); Grocy.Use("productcard");
$('#save-transfer-button').on('click', function(e) $scope('#save-transfer-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonForm = $('#transfer-form').serializeJSON(); var jsonForm = $scope('#transfer-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("transfer-form"); Grocy.FrontendHelpers.BeginUiBusy("transfer-form");
var apiUrl = 'stock/products/' + jsonForm.product_id + '/transfer'; var apiUrl = 'stock/products/' + jsonForm.product_id + '/transfer';
var jsonData = {}; var jsonData = {};
jsonData.amount = jsonForm.amount; jsonData.amount = jsonForm.amount;
jsonData.location_id_to = $("#location_id_to").val(); jsonData.location_id_to = $scope("#location_id_to").val();
jsonData.location_id_from = $("#location_id_from").val(); jsonData.location_id_from = $scope("#location_id_from").val();
if ($("#use_specific_stock_entry").is(":checked")) if ($scope("#use_specific_stock_entry").is(":checked"))
{ {
jsonData.stock_entry_id = jsonForm.specific_stock_entry; jsonData.stock_entry_id = jsonForm.specific_stock_entry;
} }
@ -55,9 +55,9 @@
Grocy.Api.Post('objects/product_barcodes', jsonDataBarcode, Grocy.Api.Post('objects/product_barcodes', jsonDataBarcode,
function(result) function(result)
{ {
$("#flow-info-InplaceAddBarcodeToExistingProduct").addClass("d-none"); $scope("#flow-info-InplaceAddBarcodeToExistingProduct").addClass("d-none");
$('#barcode-lookup-disabled-hint').addClass('d-none'); $scope('#barcode-lookup-disabled-hint').addClass('d-none');
$('#barcode-lookup-hint').removeClass('d-none'); $scope('#barcode-lookup-hint').removeClass('d-none');
window.history.replaceState({}, document.title, U("/transfer")); window.history.replaceState({}, document.title, U("/transfer"));
}, },
function(xhr) function(xhr)
@ -87,8 +87,8 @@
var successMessage = __t('Transfered %1$s of %2$s from %3$s to %4$s', var successMessage = __t('Transfered %1$s of %2$s from %3$s to %4$s',
amount, amount,
productDetails.product.name, productDetails.product.name,
$('option:selected', "#location_id_from").text(), $scope('option:selected', "#location_id_from").text(),
$('option:selected', "#location_id_to").text() $scope('option:selected', "#location_id_to").text()
) + '<br><a class="btn btn-secondary btn-sm mt-2" href="#" onclick="Grocy.UndoStockTransaction(\'' + bookingResponse[0].transaction_id + '\')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>'; ) + '<br><a class="btn btn-secondary btn-sm mt-2" href="#" onclick="Grocy.UndoStockTransaction(\'' + bookingResponse[0].transaction_id + '\')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>';
if (GetUriParam("embedded") !== undefined) if (GetUriParam("embedded") !== undefined)
@ -103,34 +103,34 @@
toastr.success(successMessage); toastr.success(successMessage);
Grocy.Components.ProductPicker.FinishFlow(); Grocy.Components.ProductPicker.FinishFlow();
if (parseInt($("#location_id_from option:selected").attr("data-is-freezer")) === 0 && parseInt($("#location_id_to option:selected").attr("data-is-freezer")) === 1) // Frozen if (parseInt($scope("#location_id_from option:selected").attr("data-is-freezer")) === 0 && parseInt($scope("#location_id_to option:selected").attr("data-is-freezer")) === 1) // Frozen
{ {
toastr.info('<span>' + __t("Frozen") + "</span> <i class='fas fa-snowflake'></i>"); toastr.info('<span>' + __t("Frozen") + "</span> <i class='fas fa-snowflake'></i>");
} }
if (parseInt($("#location_id_from option:selected").attr("data-is-freezer")) === 1 && parseInt($("#location_id_to option:selected").attr("data-is-freezer")) === 0) // Thawed if (parseInt($scope("#location_id_from option:selected").attr("data-is-freezer")) === 1 && parseInt($scope("#location_id_to option:selected").attr("data-is-freezer")) === 0) // Thawed
{ {
toastr.info('<span>' + __t("Thawed") + "</span> <i class='fas fa-fire-alt'></i>"); toastr.info('<span>' + __t("Thawed") + "</span> <i class='fas fa-fire-alt'></i>");
} }
$("#specific_stock_entry").find("option").remove().end().append("<option></option>"); $scope("#specific_stock_entry").find("option").remove().end().append("<option></option>");
$("#specific_stock_entry").attr("disabled", ""); $scope("#specific_stock_entry").attr("disabled", "");
$("#specific_stock_entry").removeAttr("required"); $scope("#specific_stock_entry").removeAttr("required");
if ($("#use_specific_stock_entry").is(":checked")) if ($scope("#use_specific_stock_entry").is(":checked"))
{ {
$("#use_specific_stock_entry").click(); $scope("#use_specific_stock_entry").click();
} }
Grocy.Components.ProductAmountPicker.Reset(); Grocy.Components.ProductAmountPicker.Reset();
$("#location_id_from").find("option").remove().end().append("<option></option>"); $scope("#location_id_from").find("option").remove().end().append("<option></option>");
$("#display_amount").attr("min", Grocy.DefaultMinAmount); $scope("#display_amount").attr("min", Grocy.DefaultMinAmount);
$("#display_amount").removeAttr("max"); $scope("#display_amount").removeAttr("max");
$('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_transfer_amount)); $scope('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_transfer_amount));
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
$("#tare-weight-handling-info").addClass("d-none"); $scope("#tare-weight-handling-info").addClass("d-none");
Grocy.Components.ProductPicker.Clear(); Grocy.Components.ProductPicker.Clear();
$("#location_id_to").val(""); $scope("#location_id_to").val("");
$("#location_id_from").val(""); $scope("#location_id_from").val("");
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
Grocy.Components.ProductCard.Refresh(jsonForm.product_id); Grocy.Components.ProductCard.Refresh(jsonForm.product_id);
Grocy.FrontendHelpers.ValidateForm('transfer-form'); Grocy.FrontendHelpers.ValidateForm('transfer-form');
@ -153,18 +153,18 @@
Grocy.Components.ProductPicker.GetPicker().on('change', function(e) Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{ {
$("#specific_stock_entry").find("option").remove().end().append("<option></option>"); $scope("#specific_stock_entry").find("option").remove().end().append("<option></option>");
if ($("#use_specific_stock_entry").is(":checked") && GetUriParam("stockId") == null) if ($scope("#use_specific_stock_entry").is(":checked") && GetUriParam("stockId") == null)
{ {
$("#use_specific_stock_entry").click(); $scope("#use_specific_stock_entry").click();
} }
$("#location_id_to").val(""); $scope("#location_id_to").val("");
if (GetUriParam("stockId") == null) if (GetUriParam("stockId") == null)
{ {
$("#location_id_from").val(""); $scope("#location_id_from").val("");
} }
var productId = $(e.target).val(); var productId = $scope(e.target).val();
if (productId) if (productId)
{ {
@ -183,7 +183,7 @@
return; return;
} }
$("#location_id_from").find("option").remove().end().append("<option></option>"); $scope("#location_id_from").find("option").remove().end().append("<option></option>");
Grocy.Api.Get("stock/products/" + productId + '/locations', Grocy.Api.Get("stock/products/" + productId + '/locations',
function(stockLocations) function(stockLocations)
{ {
@ -192,18 +192,18 @@
{ {
if (productDetails.location.id == stockLocation.location_id) if (productDetails.location.id == stockLocation.location_id)
{ {
$("#location_id_from").append($("<option>", { $scope("#location_id_from").append($scope("<option>", {
value: stockLocation.location_id, value: stockLocation.location_id,
text: stockLocation.location_name + " (" + __t("Default location") + ")", text: stockLocation.location_name + " (" + __t("Default location") + ")",
"data-is-freezer": stockLocation.location_is_freezer "data-is-freezer": stockLocation.location_is_freezer
})); }));
$("#location_id_from").val(productDetails.location.id); $scope("#location_id_from").val(productDetails.location.id);
$("#location_id_from").trigger('change'); $scope("#location_id_from").trigger('change');
setDefault = 1; setDefault = 1;
} }
else else
{ {
$("#location_id_from").append($("<option>", { $scope("#location_id_from").append($scope("<option>", {
value: stockLocation.location_id, value: stockLocation.location_id,
text: stockLocation.location_name, text: stockLocation.location_name,
"data-is-freezer": stockLocation.location_is_freezer "data-is-freezer": stockLocation.location_is_freezer
@ -212,15 +212,15 @@
if (setDefault == 0) if (setDefault == 0)
{ {
$("#location_id_from").val(stockLocation.location_id); $scope("#location_id_from").val(stockLocation.location_id);
$("#location_id_from").trigger('change'); $scope("#location_id_from").trigger('change');
} }
}); });
if (GetUriParam("locationId") != null) if (GetUriParam("locationId") != null)
{ {
$("#location_id_from").val(GetUriParam("locationId")); $scope("#location_id_from").val(GetUriParam("locationId"));
$("#location_id_from").trigger("change"); $scope("#location_id_from").trigger("change");
} }
}, },
function(xhr) function(xhr)
@ -242,8 +242,8 @@
{ {
if (barcode.amount != null && !barcode.amount.isEmpty()) if (barcode.amount != null && !barcode.amount.isEmpty())
{ {
$("#display_amount").val(barcode.amount); $scope("#display_amount").val(barcode.amount);
$("#display_amount").select(); $scope("#display_amount").select();
} }
if (barcode.qu_id != null) if (barcode.qu_id != null)
@ -251,7 +251,7 @@
Grocy.Components.ProductAmountPicker.SetQuantityUnit(barcode.qu_id); Grocy.Components.ProductAmountPicker.SetQuantityUnit(barcode.qu_id);
} }
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('transfer-form'); Grocy.FrontendHelpers.ValidateForm('transfer-form');
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
} }
@ -266,16 +266,16 @@
if (productDetails.product.enable_tare_weight_handling == 1) if (productDetails.product.enable_tare_weight_handling == 1)
{ {
$("#display_amount").attr("min", productDetails.product.tare_weight); $scope("#display_amount").attr("min", productDetails.product.tare_weight);
$("#tare-weight-handling-info").removeClass("d-none"); $scope("#tare-weight-handling-info").removeClass("d-none");
} }
else else
{ {
$("#display_amount").attr("min", Grocy.DefaultMinAmount); $scope("#display_amount").attr("min", Grocy.DefaultMinAmount);
$("#tare-weight-handling-info").addClass("d-none"); $scope("#tare-weight-handling-info").addClass("d-none");
} }
$('#display_amount').attr("data-stock-amount", productDetails.stock_amount); $scope('#display_amount').attr("data-stock-amount", productDetails.stock_amount);
if ((parseFloat(productDetails.stock_amount) || 0) === 0) if ((parseFloat(productDetails.stock_amount) || 0) === 0)
{ {
@ -288,7 +288,7 @@
{ {
Grocy.Components.ProductPicker.HideCustomError(); Grocy.Components.ProductPicker.HideCustomError();
Grocy.FrontendHelpers.ValidateForm('transfer-form'); Grocy.FrontendHelpers.ValidateForm('transfer-form');
$('#display_amount').focus(); $scope('#display_amount').focus();
} }
}, },
function(xhr) function(xhr)
@ -299,20 +299,20 @@
} }
}); });
$('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_transfer_amount)); $scope('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_transfer_amount));
$(".input-group-productamountpicker").trigger("change"); $scope(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('transfer-form'); Grocy.FrontendHelpers.ValidateForm('transfer-form');
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();
$("#location_id_from").on('change', function(e) $scope("#location_id_from").on('change', function(e)
{ {
var locationId = $(e.target).val(); var locationId = $scope(e.target).val();
var sumValue = 0; var sumValue = 0;
var stockId = null; var stockId = null;
if (locationId == $("#location_id_to").val()) if (locationId == $scope("#location_id_to").val())
{ {
$("#location_id_to").val(""); $scope("#location_id_to").val("");
} }
if (GetUriParam("embedded") !== undefined) if (GetUriParam("embedded") !== undefined)
@ -320,10 +320,10 @@
stockId = GetUriParam('stockId'); stockId = GetUriParam('stockId');
} }
$("#specific_stock_entry").find("option").remove().end().append("<option></option>"); $scope("#specific_stock_entry").find("option").remove().end().append("<option></option>");
if ($("#use_specific_stock_entry").is(":checked") && GetUriParam("stockId") == null) if ($scope("#use_specific_stock_entry").is(":checked") && GetUriParam("stockId") == null)
{ {
$("#use_specific_stock_entry").click(); $scope("#use_specific_stock_entry").click();
} }
if (locationId) if (locationId)
@ -341,22 +341,22 @@
if (stockEntry.location_id == locationId) if (stockEntry.location_id == locationId)
{ {
$("#specific_stock_entry").append($("<option>", { $scope("#specific_stock_entry").append($("<option>", {
value: stockEntry.stock_id, value: stockEntry.stock_id,
amount: stockEntry.amount, amount: stockEntry.amount,
text: __t("Amount: %1$s; Due on %2$s; Bought on %3$s", stockEntry.amount, moment(stockEntry.best_before_date).format("YYYY-MM-DD"), moment(stockEntry.purchased_date).format("YYYY-MM-DD")) + "; " + openTxt text: __t("Amount: %1$s; Due on %2$s; Bought on %3$s", stockEntry.amount, moment(stockEntry.best_before_date).format("YYYY-MM-DD"), moment(stockEntry.purchased_date).format("YYYY-MM-DD")) + "; " + openTxt
})); }));
if (stockEntry.stock_id == stockId) if (stockEntry.stock_id == stockId)
{ {
$("#specific_stock_entry").val(stockId); $scope("#specific_stock_entry").val(stockId);
} }
sumValue = sumValue + parseFloat(stockEntry.amount); sumValue = sumValue + parseFloat(stockEntry.amount);
} }
}); });
$("#display_amount").attr("max", sumValue * $("#qu_id option:selected").attr("data-qu-factor")); $scope("#display_amount").attr("max", sumValue * $scope("#qu_id option:selected").attr("data-qu-factor"));
if (sumValue == 0) if (sumValue == 0)
{ {
$("#display_amount").parent().find(".invalid-feedback").text(__t('There are no units available at this location')); $scope("#display_amount").parent().find(".invalid-feedback").text(__t('There are no units available at this location'));
} }
}, },
function(xhr) function(xhr)
@ -367,38 +367,38 @@
} }
}); });
$("#location_id_to").on('change', function(e) $scope("#location_id_to").on('change', function(e)
{ {
var locationId = $(e.target).val(); var locationId = $scope(e.target).val();
if (locationId == $("#location_id_from").val()) if (locationId == $scope("#location_id_from").val())
{ {
$("#location_id_to").parent().find(".invalid-feedback").text(__t('This cannot be the same as the "From" location')); $scope("#location_id_to").parent().find(".invalid-feedback").text(__t('This cannot be the same as the "From" location'));
$("#location_id_to").val(""); $scope("#location_id_to").val("");
} }
}); });
$("#qu_id").on('change', function(e) $scope("#qu_id").on('change', function(e)
{ {
$("#display_amount").attr("max", parseFloat($('#display_amount').attr("data-stock-amount")) * $("#qu_id option:selected").attr("data-qu-factor")); $scope("#display_amount").attr("max", parseFloat($scope('#display_amount').attr("data-stock-amount")) * $scope("#qu_id option:selected").attr("data-qu-factor"));
}); });
$('#display_amount').on('focus', function(e) $scope('#display_amount').on('focus', function(e)
{ {
$(this).select(); $(this).select();
}); });
$('#transfer-form input').keyup(function(event) $scope('#transfer-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('transfer-form'); Grocy.FrontendHelpers.ValidateForm('transfer-form');
}); });
$('#transfer-form select').change(function(event) $scope('#transfer-form select').change(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('transfer-form'); Grocy.FrontendHelpers.ValidateForm('transfer-form');
}); });
$('#transfer-form input').keydown(function(event) $scope('#transfer-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -410,12 +410,12 @@
} }
else else
{ {
$('#save-transfer-button').click(); $scope('#save-transfer-button').click();
} }
} }
}); });
$("#specific_stock_entry").on("change", function(e) $scope("#specific_stock_entry").on("change", function(e)
{ {
if ($(e.target).val() == "") if ($(e.target).val() == "")
{ {
@ -425,15 +425,15 @@
{ {
stockEntries.forEach(stockEntry => stockEntries.forEach(stockEntry =>
{ {
if (stockEntry.location_id == $("#location_id_from").val() || stockEntry.location_id == "") if (stockEntry.location_id == $scope("#location_id_from").val() || stockEntry.location_id == "")
{ {
sumValue = sumValue + parseFloat(stockEntry.amount); sumValue = sumValue + parseFloat(stockEntry.amount);
} }
}); });
$("#display_amount").attr("max", sumValue * $("#qu_id option:selected").attr("data-qu-factor")); $scope("#display_amount").attr("max", sumValue * $scope("#qu_id option:selected").attr("data-qu-factor"));
if (sumValue == 0) if (sumValue == 0)
{ {
$("#display_amount").parent().find(".invalid-feedback").text(__t('There are no units available at this location')); $scope("#display_amount").parent().find(".invalid-feedback").text(__t('There are no units available at this location'));
} }
}, },
function(xhr) function(xhr)
@ -444,25 +444,25 @@
} }
else else
{ {
$("#display_amount").attr("max", $('option:selected', this).attr('amount')); $scope("#display_amount").attr("max", $scope('option:selected', this).attr('amount'));
} }
}); });
$("#use_specific_stock_entry").on("change", function() $scope("#use_specific_stock_entry").on("change", function()
{ {
var value = $(this).is(":checked"); var value = $(this).is(":checked");
if (value) if (value)
{ {
$("#specific_stock_entry").removeAttr("disabled"); $scope("#specific_stock_entry").removeAttr("disabled");
$("#specific_stock_entry").attr("required", ""); $scope("#specific_stock_entry").attr("required", "");
} }
else else
{ {
$("#specific_stock_entry").attr("disabled", ""); $scope("#specific_stock_entry").attr("disabled", "");
$("#specific_stock_entry").removeAttr("required"); $scope("#specific_stock_entry").removeAttr("required");
$("#specific_stock_entry").val(""); $scope("#specific_stock_entry").val("");
$("#location_id_from").trigger('change'); $scope("#location_id_from").trigger('change');
} }
Grocy.FrontendHelpers.ValidateForm("transfer-form"); Grocy.FrontendHelpers.ValidateForm("transfer-form");
@ -481,10 +481,10 @@
else else
{ {
$("#location_id_from").val(locationId); $scope("#location_id_from").val(locationId);
$("#location_id_from").trigger('change'); $scope("#location_id_from").trigger('change');
$("#use_specific_stock_entry").click(); $scope("#use_specific_stock_entry").click();
$("#use_specific_stock_entry").trigger('change'); $scope("#use_specific_stock_entry").trigger('change');
Grocy.Components.ProductPicker.GetPicker().trigger('change'); Grocy.Components.ProductPicker.GetPicker().trigger('change');
} }
} }
@ -493,3 +493,6 @@
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
} }
window.transferView = transferView;

View File

@ -6,14 +6,14 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var userentitiesTable = $('#userentities-table').DataTable({ var userentitiesTable = $scope('#userentities-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#userentities-table tbody').removeClass("d-none"); $scope('#userentities-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(userentitiesTable); Grocy.FrontendHelpers.InitDataTable(userentitiesTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(

View File

@ -1,4 +1,6 @@
function userentityformView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function userentityformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,18 +8,16 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag'; $scope('#save-userentity-button').on('click', function(e)
$('#save-userentity-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#userentity-form').serializeJSON(); var jsonData = $scope('#userentity-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("userentity-form"); Grocy.FrontendHelpers.BeginUiBusy("userentity-form");
var redirectUrl = U("/userentities"); var redirectUrl = U("/userentities");
@ -66,17 +66,17 @@
} }
}); });
$('#userentity-form input').keyup(function(event) $scope('#userentity-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('userentity-form'); Grocy.FrontendHelpers.ValidateForm('userentity-form');
}); });
$('#userentity-form select').change(function(event) $scope('#userentity-form select').change(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('userentity-form'); Grocy.FrontendHelpers.ValidateForm('userentity-form');
}); });
$('#userentity-form input').keydown(function(event) $scope('#userentity-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -88,28 +88,30 @@
} }
else else
{ {
$('#save-userentity-button').click(); $scope('#save-userentity-button').click();
} }
} }
}); });
$("#show_in_sidebar_menu").on("click", function() $scope("#show_in_sidebar_menu").on("click", function()
{ {
if (this.checked) if (this.checked)
{ {
$("#icon_css_class").removeAttr("disabled"); $scope("#icon_css_class").removeAttr("disabled");
} }
else else
{ {
$("#icon_css_class").attr("disabled", ""); $scope("#icon_css_class").attr("disabled", "");
} }
}); });
$('#name').focus(); $scope('#name').focus();
Grocy.FrontendHelpers.ValidateForm('userentity-form'); Grocy.FrontendHelpers.ValidateForm('userentity-form');
// Click twice to trigger on-click but not change the actual checked state // Click twice to trigger on-click but not change the actual checked state
$("#show_in_sidebar_menu").click(); $scope("#show_in_sidebar_menu").click();
$("#show_in_sidebar_menu").click(); $scope("#show_in_sidebar_menu").click();
} }
window.userentityformView = userentityformView;

View File

@ -1,4 +1,6 @@
function userfieldformView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function userfieldformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,20 +8,18 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
$('#save-userfield-button').on('click', function(e) $scope('#save-userfield-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#userfield-form').serializeJSON(); var jsonData = $scope('#userfield-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("userfield-form"); Grocy.FrontendHelpers.BeginUiBusy("userfield-form");
var redirectUrl = U("/userfields"); var redirectUrl = U("/userfields");
@ -72,17 +72,17 @@
} }
}); });
$('#userfield-form input').keyup(function(event) $scope('#userfield-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('userfield-form'); Grocy.FrontendHelpers.ValidateForm('userfield-form');
}); });
$('#userfield-form select').change(function(event) $scope('#userfield-form select').change(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('userfield-form'); Grocy.FrontendHelpers.ValidateForm('userfield-form');
}); });
$('#userfield-form input').keydown(function(event) $scope('#userfield-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -94,37 +94,39 @@
} }
else else
{ {
$('#save-userfield-button').click(); $scope('#save-userfield-button').click();
} }
} }
}); });
$("#type").on("change", function(e) $scope("#type").on("change", function(e)
{ {
var value = $(this).val(); var value = $(this).val();
if (value === "preset-list" || value === "preset-checklist") if (value === "preset-list" || value === "preset-checklist")
{ {
$("#config").parent().removeClass("d-none"); $scope("#config").parent().removeClass("d-none");
$("#config-hint").text(__t("A predefined list of values, one per line")); $scope("#config-hint").text(__t("A predefined list of values, one per line"));
} }
else else
{ {
$("#config").parent().addClass("d-none"); $scope("#config").parent().addClass("d-none");
$("#config-hint").text(""); $scope("#config-hint").text("");
} }
}); });
$('#entity').focus(); $scope('#entity').focus();
if (typeof GetUriParam("entity") !== "undefined" && !GetUriParam("entity").isEmpty()) if (typeof GetUriParam("entity") !== "undefined" && !GetUriParam("entity").isEmpty())
{ {
$("#entity").val(GetUriParam("entity")); $scope("#entity").val(GetUriParam("entity"));
$("#entity").trigger("change"); $scope("#entity").trigger("change");
$('#name').focus(); $scope('#name').focus();
} }
$("#type").trigger("change"); $scope("#type").trigger("change");
Grocy.FrontendHelpers.ValidateForm('userfield-form'); Grocy.FrontendHelpers.ValidateForm('userfield-form');
} }
window.userfieldformView = userfieldformView;

View File

@ -6,33 +6,33 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var userfieldsTable = $('#userfields-table').DataTable({ var userfieldsTable = $scope('#userfields-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#userfields-table tbody').removeClass("d-none"); $scope('#userfields-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(userfieldsTable, null, function() Grocy.FrontendHelpers.InitDataTable(userfieldsTable, null, function()
{ {
$("#search").val(""); $scope("#search").val("");
$("#entity-filter").val("all"); $scope("#entity-filter").val("all");
userfieldsTable.column(1).search("").draw(); userfieldsTable.column(1).search("").draw();
userfieldsTable.search("").draw(); userfieldsTable.search("").draw();
}); });
$("#entity-filter").on("change", function() $scope("#entity-filter").on("change", function()
{ {
var value = $("#entity-filter option:selected").text(); var value = $scope("#entity-filter option:selected").text();
if (value === __t("All")) if (value === __t("All"))
{ {
value = ""; value = "";
} }
userfieldsTable.column(1).search(value).draw(); userfieldsTable.column(1).search(value).draw();
$("#new-userfield-button").attr("href", U("/userfield/new?embedded&entity=" + value)); $scope("#new-userfield-button").attr("href", U("/userfield/new?embedded&entity=" + value));
}); });
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
@ -46,9 +46,9 @@
if (GetUriParam("entity") != undefined && !GetUriParam("entity").isEmpty()) if (GetUriParam("entity") != undefined && !GetUriParam("entity").isEmpty())
{ {
$("#entity-filter").val(GetUriParam("entity")); $scope("#entity-filter").val(GetUriParam("entity"));
$("#entity-filter").trigger("change"); $scope("#entity-filter").trigger("change");
$("#name").focus(); $scope("#name").focus();
} }
} }

View File

@ -14,7 +14,7 @@
{ {
if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteUserPictureOnSave) if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteUserPictureOnSave)
{ {
Grocy.Api.UploadFile($("#user-picture")[0].files[0], 'userpictures', jsonData.picture_file_name, Grocy.Api.UploadFile($scope("#user-picture")[0].files[0], 'userpictures', jsonData.picture_file_name,
(result) => (result) =>
{ {
window.location.href = U('/users'); window.location.href = U('/users');
@ -33,22 +33,22 @@
}); });
} }
$('#save-user-button').on('click', function(e) $scope('#save-user-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
var jsonData = $('#user-form').serializeJSON(); var jsonData = $scope('#user-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("user-form"); Grocy.FrontendHelpers.BeginUiBusy("user-form");
if ($("#user-picture")[0].files.length > 0) if ($scope("#user-picture")[0].files.length > 0)
{ {
var someRandomStuff = Math.random().toString(36).substring(2, 100) + Math.random().toString(36).substring(2, 100); var someRandomStuff = Math.random().toString(36).substring(2, 100) + Math.random().toString(36).substring(2, 100);
jsonData.picture_file_name = someRandomStuff + $("#user-picture")[0].files[0].name; jsonData.picture_file_name = someRandomStuff + $scope("#user-picture")[0].files[0].name;
} }
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
@ -92,10 +92,10 @@
} }
}); });
$('#user-form input').keyup(function(event) $scope('#user-form input').keyup(function(event)
{ {
var element = document.getElementById("password_confirm"); var element = document.getElementById("password_confirm");
if ($("#password").val() !== $("#password_confirm").val()) if ($scope("#password").val() !== $scope("#password_confirm").val())
{ {
element.setCustomValidity("error"); element.setCustomValidity("error");
} }
@ -107,7 +107,7 @@
Grocy.FrontendHelpers.ValidateForm('user-form'); Grocy.FrontendHelpers.ValidateForm('user-form');
}); });
$('#user-form input').keydown(function(event) $scope('#user-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
@ -119,37 +119,37 @@
} }
else else
{ {
$('#save-user-button').click(); $scope('#save-user-button').click();
} }
} }
}); });
if (GetUriParam("changepw") === "true") if (GetUriParam("changepw") === "true")
{ {
$('#password').focus(); $scope('#password').focus();
} }
else else
{ {
$('#username').focus(); $scope('#username').focus();
} }
$("#user-picture").on("change", function(e) $scope("#user-picture").on("change", function(e)
{ {
$("#user-picture-label").removeClass("d-none"); $scope("#user-picture-label").removeClass("d-none");
$("#user-picture-label-none").addClass("d-none"); $scope("#user-picture-label-none").addClass("d-none");
$("#delete-current-user-picture-on-save-hint").addClass("d-none"); $scope("#delete-current-user-picture-on-save-hint").addClass("d-none");
$("#current-user-picture").addClass("d-none"); $scope("#current-user-picture").addClass("d-none");
Grocy.DeleteUserePictureOnSave = false; Grocy.DeleteUserePictureOnSave = false;
}); });
Grocy.DeleteUserPictureOnSave = false; Grocy.DeleteUserPictureOnSave = false;
$("#delete-current-user-picture-button").on("click", function(e) $scope("#delete-current-user-picture-button").on("click", function(e)
{ {
Grocy.DeleteUserPictureOnSave = true; Grocy.DeleteUserPictureOnSave = true;
$("#current-user-picture").addClass("d-none"); $scope("#current-user-picture").addClass("d-none");
$("#delete-current-user-picture-on-save-hint").removeClass("d-none"); $scope("#delete-current-user-picture-on-save-hint").removeClass("d-none");
$("#user-picture-label").addClass("d-none"); $scope("#user-picture-label").addClass("d-none");
$("#user-picture-label-none").removeClass("d-none"); $scope("#user-picture-label-none").removeClass("d-none");
}); });
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();

View File

@ -1,4 +1,6 @@
function userobjectformView(Grocy, scope = null) import { WindowMessageBag } from '../helpers/messagebag';
function userobjectformView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
if (scope != null) if (scope != null)
@ -6,15 +8,13 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
$('#save-userobject-button').on('click', function(e) $scope('#save-userobject-button').on('click', function(e)
{ {
e.preventDefault(); e.preventDefault();
if ($(".combobox-menu-visible").length) if ($scope(".combobox-menu-visible").length)
{ {
return; return;
} }
@ -76,6 +76,8 @@
}); });
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
$("#userfields-form").removeClass("border").removeClass("border-info").removeClass("p-2").find("h2").addClass("d-none"); $scope("#userfields-form").removeClass("border").removeClass("border-info").removeClass("p-2").find("h2").addClass("d-none");
} }
window.userobjectformView = userobjectformView;

View File

@ -6,14 +6,14 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var userobjectsTable = $('#userobjects-table').DataTable({ var userobjectsTable = $scope('#userobjects-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#userobjects-table tbody').removeClass("d-none"); $scope('#userobjects-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(userobjectsTable); Grocy.FrontendHelpers.InitDataTable(userobjectsTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(

View File

@ -6,7 +6,7 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
$('input.permission-cb').click( $scope('input.permission-cb').click(
function() function()
{ {
check_hierachy(this.checked, this.name); check_hierachy(this.checked, this.name);
@ -16,15 +16,15 @@
function check_hierachy(checked, name) function check_hierachy(checked, name)
{ {
var disabled = checked; var disabled = checked;
$('#permission-sub-' + name).find('input.permission-cb') $scope('#permission-sub-' + name).find('input.permission-cb')
.prop('checked', disabled) .prop('checked', disabled)
.attr('disabled', disabled); .attr('disabled', disabled);
} }
$('#permission-save').click( $scope('#permission-save').click(
function() function()
{ {
var permission_list = $('input.permission-cb') var permission_list = $scope('input.permission-cb')
.filter(function() .filter(function()
{ {
return $(this).prop('checked') && !$(this).attr('disabled'); return $(this).prop('checked') && !$(this).attr('disabled');
@ -48,7 +48,7 @@
if (Grocy.EditObjectId == Grocy.UserId) if (Grocy.EditObjectId == Grocy.UserId)
{ {
$('input.permission-cb[name=ADMIN]').click(function() $scope('input.permission-cb[name=ADMIN]').click(function()
{ {
var element = this; var element = this;

View File

@ -6,14 +6,14 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
var usersTable = $('#users-table').DataTable({ var usersTable = $scope('#users-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
'columnDefs': [ 'columnDefs': [
{ 'orderable': false, 'targets': 0 }, { 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 } { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs) ].concat($.fn.dataTable.defaults.columnDefs)
}); });
$('#users-table tbody').removeClass("d-none"); $scope('#users-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(usersTable); Grocy.FrontendHelpers.InitDataTable(usersTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(

View File

@ -6,7 +6,7 @@
$scope = $(scope).find; $scope = $(scope).find;
} }
$("#locale").val(Grocy.UserSettings.locale); $scope("#locale").val(Grocy.UserSettings.locale);
RefreshLocaleNumberInput(); RefreshLocaleNumberInput();