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,15 +6,15 @@
$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");
}); });
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

@ -9,99 +9,99 @@
Grocy.Use("barcodescanner"); Grocy.Use("barcodescanner");
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);
} }
function OnBarcodeScanned(barcode) function OnBarcodeScanned(barcode)
{ {
if (barcode.length === 0) if (barcode.length === 0)
{ {
return; return;
} }
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
{ {
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);
} }
$(document).on("Grocy.BarcodeScanned", function(e, barcode, target) $(document).on("Grocy.BarcodeScanned", function(e, barcode, target)
{ {
if (target !== "#scanned_barcode") if (target !== "#scanned_barcode")
{ {
return; return;
} }
OnBarcodeScanned(barcode); OnBarcodeScanned(barcode);
}); });
} }

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,14 +14,14 @@
{ "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(
'Are you sure to delete battery "%s"?', 'Are you sure to delete battery "%s"?',
'.battery-delete-button', '.battery-delete-button',
@ -30,8 +30,8 @@
'objects/batteries/', 'objects/batteries/',
'/batteries' '/batteries'
); );
$("#show-disabled").change(function() $scope("#show-disabled").change(function()
{ {
if (this.checked) if (this.checked)
{ {
@ -42,10 +42,10 @@
window.location.href = U('/batteries'); window.location.href = U('/batteries');
} }
}); });
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,23 +14,25 @@
{ '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();
var element = $(e.currentTarget); var element = $(e.currentTarget);
var chargeCycleId = $(e.currentTarget).attr('data-charge-cycle-id'); var chargeCycleId = $(e.currentTarget).attr('data-charge-cycle-id');
Grocy.Api.Post('batteries/charge-cycles/' + chargeCycleId.toString() + '/undo', {}, Grocy.Api.Post('batteries/charge-cycles/' + chargeCycleId.toString() + '/undo', {},
function(result) function(result)
{ {
@ -46,5 +48,5 @@
} }
); );
}); });
} }

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,36 +17,38 @@
{ "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();
// 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();
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 },
function() function()
{ {
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);
batteryRow.removeClass("table-warning"); batteryRow.removeClass("table-warning");
batteryRow.removeClass("table-danger"); batteryRow.removeClass("table-danger");
if (nextExecutionTime.isBefore(now)) if (nextExecutionTime.isBefore(now))
@ -57,17 +59,17 @@
{ {
batteryRow.addClass("table-warning"); batteryRow.addClass("table-warning");
} }
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();
toastr.success(__t('Tracked charge cycle of battery %1$s on %2$s', batteryName, trackedTime)); toastr.success(__t('Tracked charge cycle of battery %1$s on %2$s', batteryName, trackedTime));
RefreshContextualTimeago("#battery-" + batteryId + "-row"); RefreshContextualTimeago("#battery-" + batteryId + "-row");
@ -87,16 +89,18 @@
} }
); );
}); });
$(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)
{ {
@ -116,9 +120,9 @@
dueCount++; dueCount++;
} }
}); });
$("#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)
{ {
@ -126,7 +130,7 @@
} }
); );
} }
RefreshStatistics(); RefreshStatistics();
} }

View File

@ -7,9 +7,9 @@
} }
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,23 +8,21 @@
$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();
if ($(".combobox-menu-visible").length) if ($(".combobox-menu-visible").length)
{ {
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')
{ {
Grocy.Api.Post('objects/batteries', jsonData, Grocy.Api.Post('objects/batteries', jsonData,
@ -73,18 +73,18 @@
); );
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('battery-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('battery-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
@ -95,9 +95,9 @@
} }
} }
}); });
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

@ -8,35 +8,35 @@
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)
@ -53,61 +53,58 @@
} }
); );
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('batterytracking-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('batterytracking-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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,26 +1,30 @@
function calendarView(Grocy, scope = null) 
/* global fullcalendarEventSources */
import { Calendar } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid';
import bootstrapPlugin from '@fullcalendar/bootstrap';
import listPlugin from '@fullcalendar/list';
import timeGridPlugin from '@fullcalendar/timegrid';
import { QrCodeImgHtml } from "../helpers/qrcode";
import '@fullcalendar/core/main.css';
import '@fullcalendar/daygrid/main.css';
import '@fullcalendar/timegrid/main.css';
import '@fullcalendar/list/main.css';
import '@fullcalendar/bootstrap/main.css';
function calendarView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
var $viewport = $(window);
if (scope != null) if (scope != null)
{ {
$scope = $(scope).find; $scope = $(scope).find;
$viewport = $(scope);
} }
/* global fullcalendarEventSources */
import { Calendar } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid';
import bootstrapPlugin from '@fullcalendar/bootstrap';
import listPlugin from '@fullcalendar/list';
import timeGridPlugin from '@fullcalendar/timegrid';
import { QrCodeImgHtml } from "../helpers/qrcode";
import '@fullcalendar/core/main.css';
import '@fullcalendar/daygrid/main.css';
import '@fullcalendar/timegrid/main.css';
import '@fullcalendar/list/main.css';
import '@fullcalendar/bootstrap/main.css';
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",
@ -48,26 +52,26 @@
window.location.href = info.link; window.location.href = info.link;
} }
}; };
if (__t('fullcalendar_locale').replace(" ", "") !== "" && __t('fullcalendar_locale') != 'x') if (__t('fullcalendar_locale').replace(" ", "") !== "" && __t('fullcalendar_locale') != 'x')
{ {
$.getScript(U('/js/locales/fullcalendar-core/' + __t('fullcalendar_locale') + '.js')); $.getScript(U('/js/locales/fullcalendar-core/' + __t('fullcalendar_locale') + '.js'));
calendarOptions.locale = __t('fullcalendar_locale'); calendarOptions.locale = __t('fullcalendar_locale');
} }
var firstDay = null; var firstDay = null;
if (!Grocy.CalendarFirstDayOfWeek.isEmpty()) if (!Grocy.CalendarFirstDayOfWeek.isEmpty())
{ {
firstDay = parseInt(Grocy.CalendarFirstDayOfWeek); firstDay = parseInt(Grocy.CalendarFirstDayOfWeek);
} }
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();
Grocy.Api.Get('calendar/ical/sharing-link', Grocy.Api.Get('calendar/ical/sharing-link',
function(result) function(result)
{ {
@ -84,12 +88,12 @@
} }
); );
}); });
$(window).one("resize", function() $(window).one("resize", function()
{ {
// 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");
} }
@ -98,5 +102,7 @@
calendar.changeView("dayGridMonth"); calendar.changeView("dayGridMonth");
} }
}); });
} }
window.calendarView = calendarView;

View File

@ -8,24 +8,24 @@
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");
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
{ {
Grocy.Api.Post('objects/chores', jsonData, Grocy.Api.Post('objects/chores', jsonData,
@ -82,164 +82,164 @@
); );
} }
}); });
$('#chore-form input').keyup(function(event) $('#chore-form input').keyup(function(event)
{ {
Grocy.FrontendHelpers.ValidateForm('chore-form'); Grocy.FrontendHelpers.ValidateForm('chore-form');
}); });
$('#chore-form input').keydown(function(event) $('#chore-form input').keydown(function(event)
{ {
if (event.keyCode === 13) //Enter if (event.keyCode === 13) //Enter
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('chore-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('chore-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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");
}); });
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)
{ {
@ -248,5 +248,5 @@
); );
} }
}); });
} }

View File

@ -6,21 +6,21 @@
$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(
'Are you sure to delete chore "%s"?', 'Are you sure to delete chore "%s"?',
'.core-delete-button', '.core-delete-button',
@ -29,7 +29,7 @@
'objects/chores/', 'objects/chores/',
'/chroes' '/chroes'
); );
$("#show-disabled").change(function() $("#show-disabled").change(function()
{ {
if (this.checked) if (this.checked)
@ -41,10 +41,10 @@
window.location.href = U('/chores'); window.location.href = U('/chores');
} }
}); });
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,23 +14,25 @@
{ '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', {},
function(result) function(result)
{ {
@ -46,5 +48,5 @@
} }
); );
}); });
} }

View File

@ -1,14 +1,16 @@
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;
} }
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,37 +20,37 @@
{ "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
{ {
RemoveUriParam("user") RemoveUriParam("user")
} }
}); });
$(document).on('click', '.track-chore-button', function(e) top.on('click', '.track-chore-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
// 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();
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)
{ {
@ -57,60 +59,60 @@
{ {
trackedTime = moment().format('YYYY-MM-DD'); trackedTime = moment().format('YYYY-MM-DD');
} }
Grocy.Api.Post('chores/' + choreId + '/execute', { 'tracked_time': trackedTime }, Grocy.Api.Post('chores/' + choreId + '/execute', { 'tracked_time': trackedTime },
function() function()
{ {
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();
toastr.success(__t('Tracked execution of chore %1$s on %2$s', choreName, trackedTime)); toastr.success(__t('Tracked execution of chore %1$s on %2$s', choreName, trackedTime));
RefreshStatistics(); RefreshStatistics();
// Delay due to delayed/animated set of new timestamps above // Delay due to delayed/animated set of new timestamps above
setTimeout(function() setTimeout(function()
{ {
RefreshContextualTimeago("#chore-" + choreId + "-row"); RefreshContextualTimeago("#chore-" + choreId + "-row");
// 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)
@ -134,16 +136,16 @@
} }
); );
}); });
$(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)
{ {
@ -163,16 +165,16 @@
{ {
dueCount++; dueCount++;
} }
if (parseInt(element.next_execution_assigned_to_user_id) == Grocy.UserId) if (parseInt(element.next_execution_assigned_to_user_id) == Grocy.UserId)
{ {
assignedToMeCount++; assignedToMeCount++;
} }
}); });
$("#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)
{ {
@ -180,13 +182,13 @@
} }
); );
} }
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

@ -7,9 +7,9 @@
} }
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

@ -9,34 +9,34 @@
Grocy.Use("chorecard"); Grocy.Use("chorecard");
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)
@ -53,14 +53,14 @@
} }
); );
}); });
$('#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,
@ -82,48 +82,48 @@
console.error(xhr); console.error(xhr);
} }
); );
Grocy.Components.ChoreCard.Refresh(choreId); Grocy.Components.ChoreCard.Refresh(choreId);
Grocy.Components.DateTimePicker.GetInputElement().focus(); Grocy.Components.DateTimePicker.GetInputElement().focus();
Grocy.FrontendHelpers.ValidateForm('choretracking-form'); Grocy.FrontendHelpers.ValidateForm('choretracking-form');
} }
}); });
$('.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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('choretracking-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('choretracking-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
else else
{ {
$('#save-choretracking-button').click(); $scope('#save-choretracking-button').click();
} }
} }
}); });
Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e) Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('choretracking-form'); Grocy.FrontendHelpers.ValidateForm('choretracking-form');
}); });
} }

View File

@ -1,54 +1,56 @@
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)
{ {
jsonData.recipe_id = Grocy.Components.RecipePicker.GetValue(); jsonData.recipe_id = Grocy.Components.RecipePicker.GetValue();
} }
var bookingResponse = null; var bookingResponse = null;
Grocy.Api.Get('stock/products/' + jsonForm.product_id, Grocy.Api.Get('stock/products/' + jsonForm.product_id,
function(productDetails) function(productDetails)
@ -60,21 +62,21 @@
{ {
Grocy.UISound.Success(); Grocy.UISound.Success();
} }
bookingResponse = result; bookingResponse = result;
if (GetUriParam("flow") === "InplaceAddBarcodeToExistingProduct") if (GetUriParam("flow") === "InplaceAddBarcodeToExistingProduct")
{ {
var jsonDataBarcode = {}; var jsonDataBarcode = {};
jsonDataBarcode.barcode = GetUriParam("barcode"); jsonDataBarcode.barcode = GetUriParam("barcode");
jsonDataBarcode.product_id = jsonForm.product_id; jsonDataBarcode.product_id = jsonForm.product_id;
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)
@ -84,13 +86,13 @@
} }
); );
} }
$("#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;
if (productDetails.product.enable_tare_weight_handling == 1 && !jsonData.exact_amount) if (productDetails.product.enable_tare_weight_handling == 1 && !jsonData.exact_amount)
{ {
@ -100,7 +102,7 @@
{ {
successMessage = __t('Removed %1$s of %2$s from stock', Math.abs(jsonForm.amount) + " " + __n(jsonForm.amount, productDetails.quantity_unit_stock.name, productDetails.quantity_unit_stock.name_plural), productDetails.product.name) + '<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>'; successMessage = __t('Removed %1$s of %2$s from stock', Math.abs(jsonForm.amount) + " " + __n(jsonForm.amount, productDetails.quantity_unit_stock.name, productDetails.quantity_unit_stock.name_plural), productDetails.product.name) + '<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)
{ {
window.parent.postMessage(WindowMessageBag("ProductChanged", jsonForm.product_id), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("ProductChanged", jsonForm.product_id), Grocy.BaseUrl);
@ -112,21 +114,21 @@
Grocy.FrontendHelpers.EndUiBusy("consume-form"); Grocy.FrontendHelpers.EndUiBusy("consume-form");
toastr.success(successMessage); toastr.success(successMessage);
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)
@ -156,55 +158,55 @@
} }
); );
}); });
$('#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';
var jsonData = {}; var jsonData = {};
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;
} }
Grocy.Api.Get('stock/products/' + jsonForm.product_id, Grocy.Api.Get('stock/products/' + jsonForm.product_id,
function(productDetails) function(productDetails)
{ {
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");
toastr.success(__t('Marked %1$s of %2$s as opened', parseFloat(jsonForm.amount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }) + " " + __n(jsonForm.amount, productDetails.quantity_unit_stock.name, productDetails.quantity_unit_stock.name_plural), productDetails.product.name) + '<br><a class="btn btn-secondary btn-sm mt-2" href="#" onclick="Grocy.UndoStockTransaction(\'' + result[0].transaction_id + '\')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>'); toastr.success(__t('Marked %1$s of %2$s as opened', parseFloat(jsonForm.amount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }) + " " + __n(jsonForm.amount, productDetails.quantity_unit_stock.name, productDetails.quantity_unit_stock.name_plural), productDetails.product.name) + '<br><a class="btn btn-secondary btn-sm mt-2" href="#" onclick="Grocy.UndoStockTransaction(\'' + result[0].transaction_id + '\')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>');
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,18 +226,18 @@
); );
}); });
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)
{ {
stockId = GetUriParam('stockId'); stockId = GetUriParam('stockId');
@ -243,16 +245,16 @@
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];
} }
} }
} }
if (locationId) if (locationId)
{ {
Grocy.Api.Get("stock/products/" + Grocy.Components.ProductPicker.GetValue() + '/entries?include_sub_products=true', Grocy.Api.Get("stock/products/" + Grocy.Components.ProductPicker.GetValue() + '/entries?include_sub_products=true',
@ -265,25 +267,25 @@
{ {
openTxt = __t("Opened"); openTxt = __t("Opened");
} }
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
})); }));
sumValue = sumValue + parseFloat(stockEntry.amount || 0); sumValue = sumValue + parseFloat(stockEntry.amount || 0);
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);
} }
} }
}); });
Grocy.Api.Get('stock/products/' + Grocy.Components.ProductPicker.GetValue(), Grocy.Api.Get('stock/products/' + Grocy.Components.ProductPicker.GetValue(),
function(productDetails) function(productDetails)
{ {
@ -295,7 +297,7 @@
console.error(xhr); console.error(xhr);
} }
); );
if (document.getElementById("product_id").getAttribute("barcode") == "null") if (document.getElementById("product_id").getAttribute("barcode") == "null")
{ {
Grocy.ScanModeSubmit(); Grocy.ScanModeSubmit();
@ -308,46 +310,46 @@
); );
} }
}); });
Grocy.Components.ProductPicker.GetPicker().on('change', function(e) Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{ {
if (BoolVal(Grocy.UserSettings.scan_mode_consume_enabled)) if (BoolVal(Grocy.UserSettings.scan_mode_consume_enabled))
{ {
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)
{ {
Grocy.Components.ProductCard.Refresh(productId); Grocy.Components.ProductCard.Refresh(productId);
Grocy.Api.Get('stock/products/' + productId, Grocy.Api.Get('stock/products/' + productId,
function(productDetails) function(productDetails)
{ {
current_productDetails = productDetails; current_productDetails = productDetails;
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);
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,29 +358,29 @@
{ {
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
})); }));
} }
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');
} }
}); });
if (document.getElementById("product_id").getAttribute("barcode") != "null") if (document.getElementById("product_id").getAttribute("barcode") != "null")
{ {
Grocy.Api.Get('objects/product_barcodes?query[]=barcode=' + document.getElementById("product_id").getAttribute("barcode"), Grocy.Api.Get('objects/product_barcodes?query[]=barcode=' + document.getElementById("product_id").getAttribute("barcode"),
@ -387,21 +389,21 @@
if (barcodeResult != null) if (barcodeResult != null)
{ {
var barcode = barcodeResult[0]; var barcode = barcodeResult[0];
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)
{ {
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);
@ -420,19 +422,19 @@
console.error(xhr); console.error(xhr);
} }
); );
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)
{ {
Grocy.Components.ProductAmountPicker.Reset(); Grocy.Components.ProductAmountPicker.Reset();
@ -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)
@ -464,50 +466,50 @@
); );
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('consume-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('consume-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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,39 +538,40 @@
} }
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();
}); });
if (GetUriParam("embedded") !== undefined) if (GetUriParam("embedded") !== undefined)
{ {
var locationId = GetUriParam('locationId'); var locationId = GetUriParam('locationId');
if (typeof locationId === 'undefined') if (typeof locationId === 'undefined')
{ {
Grocy.Components.ProductPicker.GetPicker().trigger('change'); Grocy.Components.ProductPicker.GetPicker().trigger('change');
@ -576,40 +579,40 @@
} }
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"))
{ {
Grocy.UISound.AskForPermission(); Grocy.UISound.AskForPermission();
} }
}); });
$("#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()
{ {
@ -618,35 +621,37 @@
{ {
return; return;
} }
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,49 +21,49 @@
'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)
} }
}); });
function DisplayEquipment(id) function DisplayEquipment(id)
{ {
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)
@ -72,7 +72,7 @@
} }
); );
} }
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete equipment "%s"?', 'Are you sure to delete equipment "%s"?',
'.equipment-delete-button', '.equipment-delete-button',
@ -81,22 +81,24 @@
'objects/equipment/', 'objects/equipment/',
'/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,34 +9,31 @@
$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)
{ {
jsonData.instruction_manual_file_name = null; jsonData.instruction_manual_file_name = null;
} }
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
{ {
Grocy.Api.Post('objects/equipment', jsonData, Grocy.Api.Post('objects/equipment', jsonData,
@ -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');
@ -86,7 +86,7 @@
} }
); );
} }
Grocy.Api.Put('objects/equipment/' + Grocy.EditObjectId, jsonData, Grocy.Api.Put('objects/equipment/' + Grocy.EditObjectId, jsonData,
function(result) function(result)
{ {
@ -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');
@ -120,52 +120,52 @@
); );
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('equipment-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('equipment-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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)
{ {
@ -19,19 +19,19 @@
Grocy.Use("productamountpicker"); Grocy.Use("productamountpicker");
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,
function(productDetails) function(productDetails)
{ {
@ -40,7 +40,7 @@
{ {
price = parseFloat(jsonForm.price).toFixed(Grocy.UserSettings.stock_decimal_places_prices); price = parseFloat(jsonForm.price).toFixed(Grocy.UserSettings.stock_decimal_places_prices);
} }
var jsonData = {}; var jsonData = {};
jsonData.new_amount = jsonForm.amount; jsonData.new_amount = jsonForm.amount;
jsonData.best_before_date = Grocy.Components.DateTimePicker.GetValue(); jsonData.best_before_date = Grocy.Components.DateTimePicker.GetValue();
@ -56,29 +56,29 @@
{ {
jsonData.purchased_date = Grocy.Components.DateTimePicker2.GetValue(); jsonData.purchased_date = Grocy.Components.DateTimePicker2.GetValue();
} }
jsonData.price = price; jsonData.price = price;
var bookingResponse = null; var bookingResponse = null;
Grocy.Api.Post('stock/products/' + jsonForm.product_id + '/inventory', jsonData, Grocy.Api.Post('stock/products/' + jsonForm.product_id + '/inventory', jsonData,
function(result) function(result)
{ {
bookingResponse = result; bookingResponse = result;
if (GetUriParam("flow") === "InplaceAddBarcodeToExistingProduct") if (GetUriParam("flow") === "InplaceAddBarcodeToExistingProduct")
{ {
var jsonDataBarcode = {}; var jsonDataBarcode = {};
jsonDataBarcode.barcode = GetUriParam("barcode"); jsonDataBarcode.barcode = GetUriParam("barcode");
jsonDataBarcode.product_id = jsonForm.product_id; jsonDataBarcode.product_id = jsonForm.product_id;
jsonDataBarcode.shopping_location_id = jsonForm.shopping_location_id; jsonDataBarcode.shopping_location_id = jsonForm.shopping_location_id;
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)
@ -88,12 +88,12 @@
} }
); );
} }
Grocy.Api.Get('stock/products/' + jsonForm.product_id, Grocy.Api.Get('stock/products/' + jsonForm.product_id,
function(result) function(result)
{ {
var successMessage = __t('Stock amount of %1$s is now %2$s', result.product.name, result.stock_amount + " " + __n(result.stock_amount, result.quantity_unit_stock.name, result.quantity_unit_stock.name_plural)) + '<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>'; var successMessage = __t('Stock amount of %1$s is now %2$s', result.product.name, result.stock_amount + " " + __n(result.stock_amount, result.quantity_unit_stock.name, result.quantity_unit_stock.name_plural)) + '<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)
{ {
window.parent.postMessage(WindowMessageBag("ProductChanged", jsonForm.product_id), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("ProductChanged", jsonForm.product_id), Grocy.BaseUrl);
@ -105,15 +105,15 @@
Grocy.FrontendHelpers.EndUiBusy("inventory-form"); Grocy.FrontendHelpers.EndUiBusy("inventory-form");
toastr.success(successMessage); toastr.success(successMessage);
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)
@ -146,36 +146,36 @@
} }
); );
}); });
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.Components.ProductCard.Refresh(productId); Grocy.Components.ProductCard.Refresh(productId);
Grocy.Api.Get('stock/products/' + productId, Grocy.Api.Get('stock/products/' + productId,
function(productDetails) function(productDetails)
{ {
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)
{ {
@ -185,16 +185,16 @@
{ {
Grocy.Components.LocationPicker.SetId(productDetails.location.id); Grocy.Components.LocationPicker.SetId(productDetails.location.id);
} }
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
{ {
if (productDetails.product.default_best_before_days.toString() !== '0') if (productDetails.product.default_best_before_days.toString() !== '0')
{ {
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
@ -203,7 +203,7 @@
} }
} }
} }
if (document.getElementById("product_id").getAttribute("barcode") != "null") if (document.getElementById("product_id").getAttribute("barcode") != "null")
{ {
Grocy.Api.Get('objects/product_barcodes?query[]=barcode=' + document.getElementById("product_id").getAttribute("barcode"), Grocy.Api.Get('objects/product_barcodes?query[]=barcode=' + document.getElementById("product_id").getAttribute("barcode"),
@ -212,21 +212,21 @@
if (barcodeResult != null) if (barcodeResult != null)
{ {
var barcode = barcodeResult[0]; var barcode = barcodeResult[0];
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)
{ {
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();
} }
@ -238,12 +238,12 @@
} }
); );
} }
$('#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)
{ {
@ -252,11 +252,11 @@
); );
} }
}); });
$('#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)
{ {
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
@ -264,14 +264,14 @@
else else
{ {
Grocy.Components.ProductPicker.GetPicker().trigger('change'); Grocy.Components.ProductPicker.GetPicker().trigger('change');
if (Grocy.Components.ProductPicker.InProductModifyWorkflow()) if (Grocy.Components.ProductPicker.InProductModifyWorkflow())
{ {
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
} }
} }
$('#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)
{ {
@ -282,74 +282,74 @@
$(this).select(); $(this).select();
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('inventory-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('inventory-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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');
}); });
Grocy.Components.DateTimePicker.GetInputElement().on('change', function(e) Grocy.Components.DateTimePicker.GetInputElement().on('change', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('inventory-form'); Grocy.FrontendHelpers.ValidateForm('inventory-form');
}); });
Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e) Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e)
{ {
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)
{ {
Grocy.Api.Get('stock/products/' + productId, Grocy.Api.Get('stock/products/' + productId,
function(productDetails) function(productDetails)
{ {
var productStockAmount = parseFloat(productDetails.stock_amount || parseFloat('0')); var productStockAmount = parseFloat(productDetails.stock_amount || parseFloat('0'));
var containerWeight = parseFloat("0"); var containerWeight = parseFloat("0");
if (productDetails.product.enable_tare_weight_handling == 1) if (productDetails.product.enable_tare_weight_handling == 1)
{ {
containerWeight = parseFloat(productDetails.product.tare_weight); containerWeight = parseFloat(productDetails.product.tare_weight);
} }
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,19 +358,19 @@
} }
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)
{ {
Grocy.Components.LocationPicker.GetInputElement().removeAttr('required'); Grocy.Components.LocationPicker.GetInputElement().removeAttr('required');
} }
} }
if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING) if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
{ {
Grocy.Components.DateTimePicker.GetInputElement().removeAttr('required'); Grocy.Components.DateTimePicker.GetInputElement().removeAttr('required');
} }
Grocy.FrontendHelpers.ValidateForm('inventory-form'); Grocy.FrontendHelpers.ValidateForm('inventory-form');
}, },
function(xhr) function(xhr)
@ -380,7 +380,9 @@
); );
} }
}); });
$("#display_amount").attr("min", "0"); $scope("#display_amount").attr("min", "0");
} }
window.inventoryView = inventoryView

View File

@ -1,24 +1,25 @@
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,22 +8,20 @@
$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')
{ {
Grocy.Api.Post('objects/locations', jsonData, Grocy.Api.Post('objects/locations', jsonData,
@ -72,31 +72,33 @@
); );
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('location-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('location-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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,16 +6,16 @@
$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"?',
'.location-delete-button', '.location-delete-button',

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,24 +8,22 @@
$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');
if (createdApiKeyId !== undefined) if (createdApiKeyId !== undefined)
{ {
animateCSS("#apiKeyRow_" + createdApiKeyId, "pulse"); animateCSS("#apiKeyRow_" + createdApiKeyId, "pulse");
} }
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete API key "%s"?', 'Are you sure to delete API key "%s"?',
'.apikey-delete-button', '.apikey-delete-button',
@ -32,7 +32,7 @@
'objects/api_keys/', 'objects/api_keys/',
'/manageapikeys' '/manageapikeys'
); );
function QrCodeForApiKey(apiKeyType, apiKey) function QrCodeForApiKey(apiKeyType, apiKey)
{ {
var content = U('/api') + '|' + apiKey; var content = U('/api') + '|' + apiKey;
@ -40,11 +40,11 @@
{ {
content = U('/api/calendar/ical?secret=' + apiKey); content = U('/api/calendar/ical?secret=' + apiKey);
} }
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({
@ -53,5 +53,7 @@
closeButton: false closeButton: false
}); });
}) })
} }
window.manageapikeysView = manageapikeysView;

View File

@ -1,38 +1,41 @@
function mealplanView(Grocy, scope = null) /* global fullcalendarEventSources, internalRecipes, recipesResolved */
import { Calendar } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid';
import bootstrapPlugin from '@fullcalendar/bootstrap';
import momentPlugin from '@fullcalendar/moment/main';
import { toMoment } from '@fullcalendar/moment/main';
import '@fullcalendar/core/main.css';
import '@fullcalendar/daygrid/main.css';
import '@fullcalendar/bootstrap/main.css';
function mealplanView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
var top = scope != null ? $(scope) : $(document);
var viewport = scope != null ? $(scope) : $(window);
if (scope != null) if (scope != null)
{ {
$scope = $(scope).find; $scope = $(scope).find;
} }
/* global fullcalendarEventSources, internalRecipes, recipesResolved */
import { Calendar } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid';
import bootstrapPlugin from '@fullcalendar/bootstrap';
import momentPlugin from '@fullcalendar/moment/main';
import { toMoment } from '@fullcalendar/moment/main';
import '@fullcalendar/core/main.css';
import '@fullcalendar/daygrid/main.css';
import '@fullcalendar/bootstrap/main.css';
Grocy.Use("numberpicker"); Grocy.Use("numberpicker");
Grocy.Use("productamountpicker"); Grocy.Use("productamountpicker");
Grocy.Use("recipepicker"); Grocy.Use("recipepicker");
var setLocale = false; var setLocale = false;
if (__t('fullcalendar_locale').replace(" ", "") !== "" && __t('fullcalendar_locale') != 'x') if (__t('fullcalendar_locale').replace(" ", "") !== "" && __t('fullcalendar_locale') != 'x')
{ {
setLocale = true; setLocale = true;
$.getScript(U('/js/locales/fullcalendar-core/' + __t('fullcalendar_locale') + '.js')); $.getScript(U('/js/locales/fullcalendar-core/' + __t('fullcalendar_locale') + '.js'));
} }
var firstRender = true; var firstRender = true;
Grocy.IsMealPlanEntryEditAction = false; Grocy.IsMealPlanEntryEditAction = false;
Grocy.MealPlanEntryEditObjectId = -1; Grocy.MealPlanEntryEditObjectId = -1;
var firstDay = null; var firstDay = null;
if (!Grocy.CalendarFirstDayOfWeek.isEmpty()) if (!Grocy.CalendarFirstDayOfWeek.isEmpty())
{ {
@ -42,7 +45,7 @@
{ {
firstDay = parseInt(Grocy.MealPlanFirstDayOfWeek); firstDay = parseInt(Grocy.MealPlanFirstDayOfWeek);
} }
var calendar = new Calendar(document.getElementById("calendar"), { var calendar = new Calendar(document.getElementById("calendar"), {
plugins: [dayGridPlugin, bootstrapPlugin, momentPlugin], plugins: [dayGridPlugin, bootstrapPlugin, momentPlugin],
themeSystem: "bootstrap", themeSystem: "bootstrap",
@ -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)
@ -69,8 +72,8 @@
{ {
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> \
@ -79,10 +82,10 @@
<a class="dropdown-item add-product-button" href="#">' + __t('Add product') + '</a> \ <a class="dropdown-item add-product-button" href="#">' + __t('Add product') + '</a> \
</div> \ </div> \
</div>'); </div>');
var weekRecipeName = start.year() + "-" + ((start.week() - 1).toString().padStart(2, "0")).toString(); var weekRecipeName = start.year() + "-" + ((start.week() - 1).toString().padStart(2, "0")).toString();
var weekRecipe = internalRecipes.find(elem => elem.name == weekRecipeName); var weekRecipe = internalRecipes.find(elem => elem.name == weekRecipeName);
var weekCosts = 0; var weekCosts = 0;
var weekRecipeOrderMissingButtonHtml = ""; var weekRecipeOrderMissingButtonHtml = "";
var weekRecipeConsumeButtonHtml = ""; var weekRecipeConsumeButtonHtml = "";
@ -95,13 +98,13 @@
weekCosts = recipes.costs; weekCosts = recipes.costs;
weekCostsHtml = __t("Week costs") + ': <span class="locale-number locale-number-currency">' + weekCosts.toString() + "</span> "; weekCostsHtml = __t("Week costs") + ': <span class="locale-number locale-number-currency">' + weekCosts.toString() + "</span> ";
} }
var weekRecipeOrderMissingButtonDisabledClasses = ""; var weekRecipeOrderMissingButtonDisabledClasses = "";
if (recipes.need_fulfilled_with_shopping_list == 1) if (recipes.need_fulfilled_with_shopping_list == 1)
{ {
weekRecipeOrderMissingButtonDisabledClasses = "disabled"; weekRecipeOrderMissingButtonDisabledClasses = "disabled";
} }
var weekRecipeConsumeButtonDisabledClasses = ""; var weekRecipeConsumeButtonDisabledClasses = "";
if (recipes.need_fulfilled == 0 || weekCosts == 0) if (recipes.need_fulfilled == 0 || weekCosts == 0)
{ {
@ -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)
{ {
@ -119,17 +122,17 @@
element.removeClass("fc-event"); element.removeClass("fc-event");
element.addClass("text-center"); element.addClass("text-center");
element.attr("data-meal-plan-entry", event.mealPlanEntry); element.attr("data-meal-plan-entry", event.mealPlanEntry);
var mealPlanEntry = JSON.parse(event.mealPlanEntry); var mealPlanEntry = JSON.parse(event.mealPlanEntry);
var costsAndCaloriesPerDay = ""; var costsAndCaloriesPerDay = "";
if (event.type != "note") if (event.type != "note")
{ {
var dayRecipeName = toMoment(info.event.start, calendar).format("YYYY-MM-DD"); var dayRecipeName = toMoment(info.event.start, calendar).format("YYYY-MM-DD");
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,11 +144,11 @@
{ {
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>');
} }
} }
} }
if (event.type == "recipe") if (event.type == "recipe")
{ {
var recipe = JSON.parse(event.recipe); var recipe = JSON.parse(event.recipe);
@ -153,23 +156,23 @@
{ {
return false; return false;
} }
var resolvedRecipe = recipesResolved.find(elem => elem.recipe_id == recipe.id); var resolvedRecipe = recipesResolved.find(elem => elem.recipe_id == recipe.id);
element.attr("data-recipe", event.recipe); element.attr("data-recipe", event.recipe);
var recipeOrderMissingButtonDisabledClasses = ""; var recipeOrderMissingButtonDisabledClasses = "";
if (resolvedRecipe.need_fulfilled_with_shopping_list == 1) if (resolvedRecipe.need_fulfilled_with_shopping_list == 1)
{ {
recipeOrderMissingButtonDisabledClasses = "disabled"; recipeOrderMissingButtonDisabledClasses = "disabled";
} }
var recipeConsumeButtonDisabledClasses = ""; var recipeConsumeButtonDisabledClasses = "";
if (resolvedRecipe.need_fulfilled == 0) if (resolvedRecipe.need_fulfilled == 0)
{ {
recipeConsumeButtonDisabledClasses = "disabled"; recipeConsumeButtonDisabledClasses = "disabled";
} }
var fulfillmentInfoHtml = __t('Enough in stock'); var fulfillmentInfoHtml = __t('Enough in stock');
var fulfillmentIconHtml = '<i class="fas fa-check text-success"></i>'; var fulfillmentIconHtml = '<i class="fas fa-check text-success"></i>';
if (resolvedRecipe.need_fulfilled != 1) if (resolvedRecipe.need_fulfilled != 1)
@ -177,7 +180,7 @@
fulfillmentInfoHtml = __t('Not enough in stock'); fulfillmentInfoHtml = __t('Not enough in stock');
fulfillmentIconHtml = '<i class="fas fa-times text-danger"></i>'; fulfillmentIconHtml = '<i class="fas fa-times text-danger"></i>';
} }
var costsAndCaloriesPerServing = ""; var costsAndCaloriesPerServing = "";
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{ {
@ -187,13 +190,13 @@
{ {
costsAndCaloriesPerServing = '<h5 class="small text-truncate"><span class="locale-number locale-number-generic">' + resolvedRecipe.calories + '</span> kcal ' + __t('per serving') + '<h5>'; costsAndCaloriesPerServing = '<h5 class="small text-truncate"><span class="locale-number locale-number-generic">' + resolvedRecipe.calories + '</span> kcal ' + __t('per serving') + '<h5>';
} }
if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK) if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK)
{ {
fulfillmentIconHtml = ""; fulfillmentIconHtml = "";
fulfillmentInfoHtml = ""; fulfillmentInfoHtml = "";
} }
element.html('\ element.html('\
<div> \ <div> \
<h5 class="text-truncate">' + recipe.name + '<h5> \ <h5 class="text-truncate">' + recipe.name + '<h5> \
@ -208,7 +211,7 @@
<a class="ml-1 btn btn-outline-secondary btn-xs recipe-popup-button" href="#" data-toggle="tooltip" title="' + __t("Display recipe") + '" data-recipe-id="' + recipe.id.toString() + '" data-recipe-name="' + recipe.name + '" data-mealplan-servings="' + mealPlanEntry.recipe_servings + '" data-recipe-type="' + recipe.type + '"><i class="fas fa-eye"></i></a> \ <a class="ml-1 btn btn-outline-secondary btn-xs recipe-popup-button" href="#" data-toggle="tooltip" title="' + __t("Display recipe") + '" data-recipe-id="' + recipe.id.toString() + '" data-recipe-name="' + recipe.name + '" data-mealplan-servings="' + mealPlanEntry.recipe_servings + '" data-recipe-type="' + recipe.type + '"><i class="fas fa-eye"></i></a> \
</h5> \ </h5> \
</div>'); </div>');
if (recipe.picture_file_name && !recipe.picture_file_name.isEmpty()) if (recipe.picture_file_name && !recipe.picture_file_name.isEmpty())
{ {
element.html(element.html() + '<div class="mx-auto"><img data-src="' + U("/api/files/recipepictures/") + btoa(recipe.picture_file_name) + '?force_serve_as=picture&best_fit_width=400" class="img-fluid lazy"></div>') element.html(element.html() + '<div class="mx-auto"><img data-src="' + U("/api/files/recipepictures/") + btoa(recipe.picture_file_name) + '?force_serve_as=picture&best_fit_width=400" class="img-fluid lazy"></div>')
@ -221,26 +224,26 @@
{ {
return false; return false;
} }
if (productDetails.last_price === null) if (productDetails.last_price === null)
{ {
productDetails.last_price = 0; productDetails.last_price = 0;
} }
element.attr("data-product-details", event.productDetails); element.attr("data-product-details", event.productDetails);
var productOrderMissingButtonDisabledClasses = "disabled"; var productOrderMissingButtonDisabledClasses = "disabled";
if (parseFloat(productDetails.stock_amount_aggregated) < parseFloat(mealPlanEntry.product_amount)) if (parseFloat(productDetails.stock_amount_aggregated) < parseFloat(mealPlanEntry.product_amount))
{ {
productOrderMissingButtonDisabledClasses = ""; productOrderMissingButtonDisabledClasses = "";
} }
var productConsumeButtonDisabledClasses = "disabled"; var productConsumeButtonDisabledClasses = "disabled";
if (parseFloat(productDetails.stock_amount_aggregated) >= parseFloat(mealPlanEntry.product_amount)) if (parseFloat(productDetails.stock_amount_aggregated) >= parseFloat(mealPlanEntry.product_amount))
{ {
productConsumeButtonDisabledClasses = ""; productConsumeButtonDisabledClasses = "";
} }
fulfillmentInfoHtml = __t('Not enough in stock'); fulfillmentInfoHtml = __t('Not enough in stock');
fulfillmentIconHtml = '<i class="fas fa-times text-danger"></i>'; fulfillmentIconHtml = '<i class="fas fa-times text-danger"></i>';
if (parseFloat(productDetails.stock_amount_aggregated) >= parseFloat(mealPlanEntry.product_amount)) if (parseFloat(productDetails.stock_amount_aggregated) >= parseFloat(mealPlanEntry.product_amount))
@ -248,7 +251,7 @@
fulfillmentInfoHtml = __t('Enough in stock'); fulfillmentInfoHtml = __t('Enough in stock');
fulfillmentIconHtml = '<i class="fas fa-check text-success"></i>'; fulfillmentIconHtml = '<i class="fas fa-check text-success"></i>';
} }
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{ {
costsAndCaloriesPerServing = '<h5 class="small text-truncate"><span class="locale-number locale-number-currency">' + productDetails.last_price * mealPlanEntry.product_amount + '</span> / <span class="locale-number locale-number-generic">' + productDetails.product.calories * mealPlanEntry.product_amount + '</span> kcal ' + '<h5>'; costsAndCaloriesPerServing = '<h5 class="small text-truncate"><span class="locale-number locale-number-currency">' + productDetails.last_price * mealPlanEntry.product_amount + '</span> / <span class="locale-number locale-number-generic">' + productDetails.product.calories * mealPlanEntry.product_amount + '</span> kcal ' + '<h5>';
@ -257,7 +260,7 @@
{ {
costsAndCaloriesPerServing = '<h5 class="small text-truncate"><span class="locale-number locale-number-generic">' + productDetails.product.calories * mealPlanEntry.product_amount + '</span> kcal ' + '<h5>'; costsAndCaloriesPerServing = '<h5 class="small text-truncate"><span class="locale-number locale-number-generic">' + productDetails.product.calories * mealPlanEntry.product_amount + '</span> kcal ' + '<h5>';
} }
element.html('\ element.html('\
<div> \ <div> \
<h5 class="text-truncate">' + productDetails.product.name + '<h5> \ <h5 class="text-truncate">' + productDetails.product.name + '<h5> \
@ -271,7 +274,7 @@
<a class="ml-1 btn btn-outline-primary btn-xs show-as-dialog-link ' + productOrderMissingButtonDisabledClasses + '" href="' + U("/shoppinglistitem/new?embedded&updateexistingproduct&product=") + mealPlanEntry.product_id + '&amount=' + mealPlanEntry.product_amount + '" data-toggle="tooltip" title="' + __t("Add to shopping list") + '" data-product-id="' + productDetails.product.id.toString() + '" data-product-name="' + productDetails.product.name + '" data-product-amount="' + mealPlanEntry.product_amount + '"><i class="fas fa-cart-plus"></i></a> \ <a class="ml-1 btn btn-outline-primary btn-xs show-as-dialog-link ' + productOrderMissingButtonDisabledClasses + '" href="' + U("/shoppinglistitem/new?embedded&updateexistingproduct&product=") + mealPlanEntry.product_id + '&amount=' + mealPlanEntry.product_amount + '" data-toggle="tooltip" title="' + __t("Add to shopping list") + '" data-product-id="' + productDetails.product.id.toString() + '" data-product-name="' + productDetails.product.name + '" data-product-amount="' + mealPlanEntry.product_amount + '"><i class="fas fa-cart-plus"></i></a> \
</h5> \ </h5> \
</div>'); </div>');
if (productDetails.product.picture_file_name && !productDetails.product.picture_file_name.isEmpty()) if (productDetails.product.picture_file_name && !productDetails.product.picture_file_name.isEmpty())
{ {
element.html(element.html() + '<div class="mx-auto"><img data-src="' + U("/api/files/productpictures/") + btoa(productDetails.product.picture_file_name) + '?force_serve_as=picture&best_fit_width=400" class="img-fluid lazy"></div>') element.html(element.html() + '<div class="mx-auto"><img data-src="' + U("/api/files/productpictures/") + btoa(productDetails.product.picture_file_name) + '?force_serve_as=picture&best_fit_width=400" class="img-fluid lazy"></div>')
@ -298,7 +301,7 @@
RefreshLocaleNumberDisplay(); RefreshLocaleNumberDisplay();
LoadImagesLazy(); LoadImagesLazy();
elem.find('[data-toggle="tooltip"]').tooltip(); elem.find('[data-toggle="tooltip"]').tooltip();
if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK) if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK)
{ {
elem.find(".recipe-order-missing-button").addClass("d-none"); elem.find(".recipe-order-missing-button").addClass("d-none");
@ -312,103 +315,103 @@
{ {
calendar.setOption("locale", __t('fullcalendar_locale')); calendar.setOption("locale", __t('fullcalendar_locale'));
} }
// this triggers a re-render, so we can't do that in the callback; // this triggers a re-render, so we can't do that in the callback;
// but it works here no problem. // but it works here no problem.
if (GetUriParam("week") !== undefined) if (GetUriParam("week") !== undefined)
{ {
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"));
Grocy.Api.Delete('objects/meal_plan/' + mealPlanEntry.id.toString(), {}, Grocy.Api.Delete('objects/meal_plan/' + mealPlanEntry.id.toString(), {},
function(result) function(result)
{ {
@ -420,24 +423,24 @@
} }
); );
}); });
$('#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;
} }
if (document.getElementById("add-recipe-form").checkValidity() === false) //There is at least one validation error if (document.getElementById("add-recipe-form").checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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();
@ -462,24 +465,24 @@
); );
} }
}); });
$('#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;
} }
if (document.getElementById("add-note-form").checkValidity() === false) //There is at least one validation error if (document.getElementById("add-note-form").checkValidity() === false) //There is at least one validation error
{ {
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)
{ {
Grocy.Api.Put('objects/meal_plan/' + Grocy.MealPlanEntryEditObjectId.toString(), jsonData, Grocy.Api.Put('objects/meal_plan/' + Grocy.MealPlanEntryEditObjectId.toString(), jsonData,
@ -506,31 +509,31 @@
} }
); );
} }
}); });
$('#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;
} }
if (document.getElementById("add-product-form").checkValidity() === false) //There is at least one validation error if (document.getElementById("add-product-form").checkValidity() === false) //There is at least one validation error
{ {
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;
jsonData.product_qu_id = jsonData.qu_id; jsonData.product_qu_id = jsonData.qu_id;
delete jsonData.qu_id; delete jsonData.qu_id;
if (Grocy.IsMealPlanEntryEditAction) if (Grocy.IsMealPlanEntryEditAction)
{ {
Grocy.Api.Put('objects/meal_plan/' + Grocy.MealPlanEntryEditObjectId.toString(), jsonData, Grocy.Api.Put('objects/meal_plan/' + Grocy.MealPlanEntryEditObjectId.toString(), jsonData,
@ -558,69 +561,69 @@
); );
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById("add-recipe-form").checkValidity() === false) //There is at least one validation error if (document.getElementById("add-recipe-form").checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById("add-product-form").checkValidity() === false) //There is at least one validation error if (document.getElementById("add-product-form").checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById("add-recipe-form").checkValidity() === false) //There is at least one validation error if (document.getElementById("add-recipe-form").checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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),
closeButton: false, closeButton: false,
@ -639,7 +642,7 @@
if (result === true) if (result === true)
{ {
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
// 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 },
function(result) function(result)
@ -673,20 +676,20 @@
} }
}); });
}); });
$(document).on('click', '.product-consume-button', function(e) top.on('click', '.product-consume-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
// 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();
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)
{ {
@ -694,7 +697,7 @@
function(result) function(result)
{ {
var toastMessage = __t('Removed %1$s of %2$s from stock', consumeAmount.toString() + " " + __n(consumeAmount, result.quantity_unit_stock.name, result.quantity_unit_stock.name_plural), result.product.name) + '<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>'; var toastMessage = __t('Removed %1$s of %2$s from stock', consumeAmount.toString() + " " + __n(consumeAmount, result.quantity_unit_stock.name, result.quantity_unit_stock.name_plural), result.product.name) + '<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>';
Grocy.FrontendHelpers.EndUiBusy(); Grocy.FrontendHelpers.EndUiBusy();
toastr.success(toastMessage); toastr.success(toastMessage);
window.location.reload(); window.location.reload();
@ -713,17 +716,17 @@
} }
); );
}); });
$(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),
closeButton: false, closeButton: false,
@ -742,7 +745,7 @@
if (result === true) if (result === true)
{ {
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
// 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 },
function(result) function(result)
@ -771,16 +774,16 @@
} }
}); });
}); });
$(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 },
function(result) function(result)
@ -808,12 +811,12 @@
} }
); );
}); });
$(window).one("resize", function() $(window).one("resize", function()
{ {
// 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");
} }
@ -822,24 +825,24 @@
calendar.changeView("dayGridWeek"); calendar.changeView("dayGridWeek");
} }
}); });
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)
{ {
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)
@ -849,19 +852,19 @@
); );
} }
}); });
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)
{ {
@ -870,5 +873,5 @@
); );
} }
}); });
} }

View File

@ -1,32 +1,34 @@
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;
Grocy.FrontendHelpers.BeginUiBusy("barcode-form"); Grocy.FrontendHelpers.BeginUiBusy("barcode-form");
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
{ {
Grocy.Api.Post('objects/product_barcodes', jsonData, Grocy.Api.Post('objects/product_barcodes', jsonData,
@ -34,7 +36,7 @@
{ {
Grocy.EditObjectId = result.created_object_id; Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save() Grocy.Components.UserfieldsForm.Save()
window.parent.postMessage(WindowMessageBag("ProductBarcodesChanged"), U("/product/" + GetUriParam("product"))); window.parent.postMessage(WindowMessageBag("ProductBarcodesChanged"), U("/product/" + GetUriParam("product")));
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product"))); window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
}, },
@ -62,60 +64,62 @@
); );
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('barcode-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('barcode-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
else else
{ {
$('#save-barcode-button').click(); $scope('#save-barcode-button').click();
} }
} }
}); });
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,26 +1,28 @@
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");
function saveProductPicture(result, location, jsonData) function saveProductPicture(result, location, jsonData)
{ {
var productId = Grocy.EditObjectId || result.created_object_id; var productId = Grocy.EditObjectId || result.created_object_id;
Grocy.Components.UserfieldsForm.Save(() => Grocy.Components.UserfieldsForm.Save(() =>
{ {
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")
@ -28,7 +30,7 @@
window.location.reload(); window.location.reload();
return return
} }
var returnTo = GetUriParam('returnto'); var returnTo = GetUriParam('returnto');
if (GetUriParam("closeAfterCreation") !== undefined) if (GetUriParam("closeAfterCreation") !== undefined)
{ {
@ -38,19 +40,19 @@
{ {
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
{ {
window.location.href = U(returnTo); window.location.href = U(returnTo);
} }
} }
else else
{ {
window.location.href = U(location + productId); window.location.href = U(location + productId);
} }
}, },
(xhr) => (xhr) =>
{ {
@ -66,7 +68,7 @@
window.location.reload(); window.location.reload();
return return
} }
var returnTo = GetUriParam('returnto'); var returnTo = GetUriParam('returnto');
if (GetUriParam("closeAfterCreation") !== undefined) if (GetUriParam("closeAfterCreation") !== undefined)
{ {
@ -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
{ {
@ -90,30 +92,30 @@
} }
}); });
} }
$('.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;
Grocy.FrontendHelpers.BeginUiBusy("product-form"); Grocy.FrontendHelpers.BeginUiBusy("product-form");
if (jsonData.parent_product_id.toString().isEmpty()) if (jsonData.parent_product_id.toString().isEmpty())
{ {
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')
{ {
Grocy.Api.Post('objects/products', jsonData, Grocy.Api.Post('objects/products', jsonData,
@ -125,11 +127,11 @@
}); });
return; return;
} }
if (Grocy.DeleteProductPictureOnSave) if (Grocy.DeleteProductPictureOnSave)
{ {
jsonData.picture_file_name = null; jsonData.picture_file_name = null;
Grocy.Api.DeleteFile(Grocy.ProductPictureFileName, 'productpictures', {}, Grocy.Api.DeleteFile(Grocy.ProductPictureFileName, 'productpictures', {},
function(result) function(result)
{ {
@ -142,7 +144,7 @@
} }
); );
} }
Grocy.Api.Put('objects/products/' + Grocy.EditObjectId, jsonData, Grocy.Api.Put('objects/products/' + Grocy.EditObjectId, jsonData,
(result) => saveProductPicture(result, location, jsonData), (result) => saveProductPicture(result, location, jsonData),
function(xhr) function(xhr)
@ -152,7 +154,7 @@
} }
); );
}); });
if (Grocy.EditMode == "edit") if (Grocy.EditMode == "edit")
{ {
Grocy.Api.Get('stock/products/' + Grocy.EditObjectId, Grocy.Api.Get('stock/products/' + Grocy.EditObjectId,
@ -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)
@ -169,118 +171,118 @@
} }
); );
} }
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
{ {
event.preventDefault(); event.preventDefault();
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
{ {
return false; return false;
} }
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,20 +308,20 @@
{ '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();
var productId = $(e.currentTarget).attr('data-product-id'); var productId = $(e.currentTarget).attr('data-product-id');
Grocy.Api.Get('stock/products/' + productId + '/printlabel', function(labelData) Grocy.Api.Get('stock/products/' + productId + '/printlabel', function(labelData)
{ {
@ -329,120 +331,72 @@
} }
}); });
}); });
$(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: { Grocy.ProductEditFormRedirectUri = "reload";
label: __t('Yes'), $scope('#save-product-button').click();
className: 'btn-success' }
}, );
cancel: {
label: __t('No'), Grocy.FrontendHelpers.MakeDeleteConfirmBox(
className: 'btn-danger' 'Are you sure to remove this barcode?',
} '.barcode-delete-button',
}, 'data-barcode-id',
callback: function(result) 'data-barcode-id',
{ 'objects/product_barcodes/',
if (result === true) (result, id, name) =>
{ {
Grocy.Api.Delete('objects/quantity_unit_conversions/' + objectId, {}, Grocy.ProductEditFormRedirectUri = "reload";
function(result) $scope('#save-product-button').click();
{ }
Grocy.ProductEditFormRedirectUri = "reload"; )
$('#save-product-button').click();
}, $scope('#qu_id_stock').change(function(e)
function(xhr)
{
console.error(xhr);
}
);
}
}
});
});
$(document).on('click', '.barcode-delete-button', function(e)
{
var objectId = $(e.currentTarget).attr('data-barcode-id');
bootbox.confirm({
message: __t('Are you sure to remove this barcode?'),
closeButton: false,
buttons: {
confirm: {
label: __t('Yes'),
className: 'btn-success'
},
cancel: {
label: __t('No'),
className: 'btn-danger'
}
},
callback: function(result)
{
if (result === true)
{
Grocy.Api.Delete('objects/product_barcodes/' + objectId, {},
function(result)
{
Grocy.ProductEditFormRedirectUri = "reload";
$('#save-product-button').click();
},
function(xhr)
{
console.error(xhr);
}
);
}
}
});
});
$('#qu_id_stock').change(function(e)
{ {
// Preset QU purchase with stock QU if unset // 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)
{ {
quIdPurchase[0].selectedIndex = quIdStock[0].selectedIndex; quIdPurchase[0].selectedIndex = quIdStock[0].selectedIndex;
Grocy.FrontendHelpers.ValidateForm('product-form'); Grocy.FrontendHelpers.ValidateForm('product-form');
} }
}); });
$('#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);
} }
}); });
$(window).on("message", function(e) $(window).on("message", function(e)
{ {
var data = e.originalEvent.data; var data = e.originalEvent.data;
if (data.Message === "ProductBarcodesChanged" || data.Message === "ProductQUConversionChanged") if (data.Message === "ProductBarcodesChanged" || data.Message === "ProductQUConversionChanged")
{ {
window.location.reload(); window.location.reload();
} }
}); });
if (Grocy.EditMode == "create" && GetUriParam("copy-of") != undefined) if (Grocy.EditMode == "create" && GetUriParam("copy-of") != undefined)
{ {
Grocy.Api.Get('objects/products/' + GetUriParam("copy-of"), Grocy.Api.Get('objects/products/' + GetUriParam("copy-of"),
@ -454,44 +408,44 @@
} }
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');
}, },
function(xhr) function(xhr)
@ -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,22 +8,20 @@
$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')
{ {
Grocy.Api.Post('objects/product_groups', jsonData, Grocy.Api.Post('objects/product_groups', jsonData,
@ -58,31 +58,33 @@
); );
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('product-group-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('product-group-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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"?',
@ -23,15 +23,14 @@
'objects/product_groups/', 'objects/product_groups/',
'/productgroups' '/productgroups'
); );
$(window).on("message", function(e) $(window).on("message", function(e)
{ {
var data = e.originalEvent.data; var data = e.originalEvent.data;
if (data.Message === "CloseAllModals") if (data.Message === "CloseAllModals")
{ {
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,22 +15,22 @@
{ "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(
(objectId, objectName) => (objectId, objectName) =>
{ {
@ -44,8 +44,8 @@
'objects/products/', 'objects/products/',
'/products' '/products'
); );
$("#show-disabled").change(function() $scope("#show-disabled").change(function()
{ {
if (this.checked) if (this.checked)
{ {
@ -56,26 +56,26 @@
window.location.href = U('/products'); window.location.href = U('/products');
} }
}); });
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)
{ {
@ -87,5 +87,5 @@
} }
); );
}); });
} }

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)
{ {
@ -19,34 +19,34 @@
Grocy.Use("productamountpicker"); Grocy.Use("productamountpicker");
Grocy.Use("productcard"); Grocy.Use("productcard");
Grocy.Use("shoppinglocationpicker"); Grocy.Use("shoppinglocationpicker");
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");
Grocy.Api.Get('stock/products/' + jsonForm.product_id, Grocy.Api.Get('stock/products/' + jsonForm.product_id,
function(productDetails) function(productDetails)
{ {
var jsonData = {}; var jsonData = {};
jsonData.amount = jsonForm.amount; jsonData.amount = jsonForm.amount;
jsonData.print_stock_label = jsonForm.print_stock_label jsonData.print_stock_label = jsonForm.print_stock_label
if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING) if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{ {
jsonData.price = 0; jsonData.price = 0;
@ -58,21 +58,21 @@
{ {
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);
} }
jsonData.price = price; jsonData.price = price;
} }
if (BoolVal(Grocy.UserSettings.show_purchased_date_on_purchase)) if (BoolVal(Grocy.UserSettings.show_purchased_date_on_purchase))
{ {
jsonData.purchased_date = Grocy.Components.DateTimePicker2.GetValue(); jsonData.purchased_date = Grocy.Components.DateTimePicker2.GetValue();
} }
if (Grocy.Components.DateTimePicker) if (Grocy.Components.DateTimePicker)
{ {
jsonData.best_before_date = Grocy.Components.DateTimePicker.GetValue(); jsonData.best_before_date = Grocy.Components.DateTimePicker.GetValue();
@ -81,7 +81,7 @@
{ {
jsonData.best_before_date = null; jsonData.best_before_date = null;
} }
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{ {
jsonData.shopping_location_id = Grocy.Components.ShoppingLocationPicker.GetValue(); jsonData.shopping_location_id = Grocy.Components.ShoppingLocationPicker.GetValue();
@ -90,38 +90,38 @@
{ {
jsonData.location_id = Grocy.Components.LocationPicker.GetValue(); jsonData.location_id = Grocy.Components.LocationPicker.GetValue();
} }
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)
{ } { }
); );
} }
if (BoolVal(Grocy.UserSettings.scan_mode_purchase_enabled)) if (BoolVal(Grocy.UserSettings.scan_mode_purchase_enabled))
{ {
Grocy.UISound.Success(); Grocy.UISound.Success();
} }
if (GetUriParam("flow") == "InplaceAddBarcodeToExistingProduct") if (GetUriParam("flow") == "InplaceAddBarcodeToExistingProduct")
{ {
var jsonDataBarcode = {}; var jsonDataBarcode = {};
jsonDataBarcode.barcode = GetUriParam("barcode"); jsonDataBarcode.barcode = GetUriParam("barcode");
jsonDataBarcode.product_id = jsonForm.product_id; jsonDataBarcode.product_id = jsonForm.product_id;
jsonDataBarcode.shopping_location_id = jsonForm.shopping_location_id; jsonDataBarcode.shopping_location_id = jsonForm.shopping_location_id;
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)
@ -131,14 +131,14 @@
} }
); );
} }
var amountMessage = parseFloat(jsonForm.amount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }); var amountMessage = parseFloat(jsonForm.amount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts });
if (BoolVal(productDetails.product.enable_tare_weight_handling)) if (BoolVal(productDetails.product.enable_tare_weight_handling))
{ {
amountMessage = parseFloat(jsonForm.amount) - parseFloat(productDetails.stock_amount) - parseFloat(productDetails.product.tare_weight); amountMessage = parseFloat(jsonForm.amount) - parseFloat(productDetails.stock_amount) - parseFloat(productDetails.product.tare_weight);
} }
var successMessage = __t('Added %1$s of %2$s to stock', amountMessage + " " + __n(amountMessage, productDetails.quantity_unit_stock.name, productDetails.quantity_unit_stock.name_plural), productDetails.product.name) + '<br><a class="btn btn-secondary btn-sm mt-2" href="#" onclick="Grocy.UndoStockTransaction(\'' + result[0].transaction_id + '\')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>'; var successMessage = __t('Added %1$s of %2$s to stock', amountMessage + " " + __n(amountMessage, productDetails.quantity_unit_stock.name, productDetails.quantity_unit_stock.name_plural), productDetails.product.name) + '<br><a class="btn btn-secondary btn-sm mt-2" href="#" onclick="Grocy.UndoStockTransaction(\'' + result[0].transaction_id + '\')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>';
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_LABELPRINTER) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_LABELPRINTER)
{ {
if (Grocy.Webhooks.labelprinter !== undefined) if (Grocy.Webhooks.labelprinter !== undefined)
@ -150,7 +150,7 @@
{ {
post_data.duedate = __t('DD') + ': ' + result[0].best_before_date post_data.duedate = __t('DD') + ': ' + result[0].best_before_date
} }
if (jsonForm.print_stock_label > 0) if (jsonForm.print_stock_label > 0)
{ {
var reps = 1; var reps = 1;
@ -162,7 +162,7 @@
} }
} }
} }
if (GetUriParam("embedded") !== undefined) if (GetUriParam("embedded") !== undefined)
{ {
window.parent.postMessage(WindowMessageBag("ProductChanged", jsonForm.product_id), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("ProductChanged", jsonForm.product_id), Grocy.BaseUrl);
@ -176,7 +176,7 @@
Grocy.FrontendHelpers.EndUiBusy("purchase-form"); Grocy.FrontendHelpers.EndUiBusy("purchase-form");
toastr.success(successMessage); toastr.success(successMessage);
Grocy.Components.ProductPicker.FinishFlow(); Grocy.Components.ProductPicker.FinishFlow();
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING && BoolVal(Grocy.UserSettings.show_warning_on_purchase_when_due_date_is_earlier_than_next)) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING && BoolVal(Grocy.UserSettings.show_warning_on_purchase_when_due_date_is_earlier_than_next))
{ {
if (moment(jsonData.best_before_date).isBefore(CurrentProductDetails.next_due_date)) if (moment(jsonData.best_before_date).isBefore(CurrentProductDetails.next_due_date))
@ -184,14 +184,14 @@
toastr.warning(__t("This is due earlier than already in-stock items")); toastr.warning(__t("This is due earlier than already in-stock items"));
} }
} }
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();
@ -207,12 +207,12 @@
} }
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');
} }
}, },
@ -230,7 +230,7 @@
} }
); );
}); });
if (Grocy.Components.ProductPicker !== undefined) if (Grocy.Components.ProductPicker !== undefined)
{ {
Grocy.Components.ProductPicker.GetPicker().on('change', function(e) Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
@ -239,31 +239,31 @@
{ {
Grocy.UISound.BarcodeScannerBeep(); Grocy.UISound.BarcodeScannerBeep();
} }
var productId = $(e.target).val(); var productId = $scope(e.target).val();
if (productId) if (productId)
{ {
Grocy.Components.ProductCard.Refresh(productId); Grocy.Components.ProductCard.Refresh(productId);
Grocy.Api.Get('stock/products/' + productId, Grocy.Api.Get('stock/products/' + productId,
function(productDetails) function(productDetails)
{ {
CurrentProductDetails = productDetails; CurrentProductDetails = productDetails;
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)
{ {
if (productDetails.last_shopping_location_id != null) if (productDetails.last_shopping_location_id != null)
@ -275,48 +275,48 @@
Grocy.Components.ShoppingLocationPicker.SetId(productDetails.default_shopping_location_id); Grocy.Components.ShoppingLocationPicker.SetId(productDetails.default_shopping_location_id);
} }
} }
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{ {
Grocy.Components.LocationPicker.SetId(productDetails.location.id); Grocy.Components.LocationPicker.SetId(productDetails.location.id);
} }
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)
{ {
if (productDetails.product.default_best_before_days.toString() !== '0') if (productDetails.product.default_best_before_days.toString() !== '0')
{ {
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
@ -325,32 +325,32 @@
} }
} }
} }
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();
var elem = document.getElementById("product_id"); var elem = document.getElementById("product_id");
if (elem.getAttribute("barcode") != "null" && !elem.getAttribute("barcode").startsWith("grcy")) if (elem.getAttribute("barcode") != "null" && !elem.getAttribute("barcode").startsWith("grcy"))
@ -361,38 +361,38 @@
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)
{ {
Grocy.Components.ProductAmountPicker.SetQuantityUnit(barcode.qu_id); Grocy.Components.ProductAmountPicker.SetQuantityUnit(barcode.qu_id);
} }
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING && barcode.shopping_location_id != null) if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING && barcode.shopping_location_id != null)
{ {
Grocy.Components.ShoppingLocationPicker.SetId(barcode.shopping_location_id); Grocy.Components.ShoppingLocationPicker.SetId(barcode.shopping_location_id);
} }
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();
} }
} }
Grocy.ScanModeSubmit(false); Grocy.ScanModeSubmit(false);
}, },
function(xhr) function(xhr)
@ -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)
{ {
@ -417,12 +417,12 @@
} }
}); });
} }
$('#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)
{ {
if (Grocy.Components.ProductPicker.InAnyFlow() === false && GetUriParam("embedded") === undefined) if (Grocy.Components.ProductPicker.InAnyFlow() === false && GetUriParam("embedded") === undefined)
@ -432,15 +432,15 @@
else else
{ {
Grocy.Components.ProductPicker.GetPicker().trigger('change'); Grocy.Components.ProductPicker.GetPicker().trigger('change');
if (Grocy.Components.ProductPicker.InProductModifyWorkflow()) if (Grocy.Components.ProductPicker.InProductModifyWorkflow())
{ {
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
} }
} }
} }
$('#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,145 +448,147 @@
} }
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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('purchase-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('purchase-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
else else
{ {
$('#save-purchase-button').click(); $scope('#save-purchase-button').click();
} }
} }
}); });
if (Grocy.Components.DateTimePicker) if (Grocy.Components.DateTimePicker)
{ {
Grocy.Components.DateTimePicker.GetInputElement().on('change', function(e) Grocy.Components.DateTimePicker.GetInputElement().on('change', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('purchase-form'); Grocy.FrontendHelpers.ValidateForm('purchase-form');
}); });
Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e) Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('purchase-form'); Grocy.FrontendHelpers.ValidateForm('purchase-form');
}); });
} }
if (Grocy.Components.DateTimePicker2) if (Grocy.Components.DateTimePicker2)
{ {
Grocy.Components.DateTimePicker2.GetInputElement().on('change', function(e) Grocy.Components.DateTimePicker2.GetInputElement().on('change', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('purchase-form'); Grocy.FrontendHelpers.ValidateForm('purchase-form');
}); });
Grocy.Components.DateTimePicker2.GetInputElement().on('keypress', function(e) Grocy.Components.DateTimePicker2.GetInputElement().on('keypress', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('purchase-form'); Grocy.FrontendHelpers.ValidateForm('purchase-form');
}); });
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');
}); });
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"))
{ {
Grocy.UISound.AskForPermission(); Grocy.UISound.AskForPermission();
} }
}); });
$("#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,29 +8,27 @@
$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')
{ {
Grocy.Api.Post('objects/quantity_unit_conversions', jsonData, Grocy.Api.Post('objects/quantity_unit_conversions', jsonData,
@ -37,12 +37,12 @@
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;
jsonData.factor = 1 / jsonData.factor; jsonData.factor = 1 / jsonData.factor;
//Create Inverse //Create Inverse
Grocy.Api.Post('objects/quantity_unit_conversions', jsonData, Grocy.Api.Post('objects/quantity_unit_conversions', jsonData,
function(result) function(result)
@ -136,88 +136,90 @@
); );
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('quconversion-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('quconversion-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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

@ -7,27 +7,27 @@
} }
import { WindowMessageBag } from '../helpers/messagebag'; import { WindowMessageBag } from '../helpers/messagebag';
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');
if (Grocy.QuantityUnitEditFormRedirectUri !== undefined) if (Grocy.QuantityUnitEditFormRedirectUri !== undefined)
{ {
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";
} }
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
{ {
Grocy.Api.Post('objects/quantity_units', jsonData, Grocy.Api.Post('objects/quantity_units', jsonData,
@ -42,7 +42,7 @@
} }
else else
{ {
if (redirectDestination == "reload") if (redirectDestination == "reload")
{ {
window.location.href = U("/quantityunit/" + result.created_object_id.toString()); window.location.href = U("/quantityunit/" + result.created_object_id.toString());
@ -78,7 +78,7 @@
} }
else else
{ {
if (redirectDestination == "reload") if (redirectDestination == "reload")
{ {
window.location.reload(); window.location.reload();
@ -102,62 +102,62 @@
); );
} }
}); });
$('#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(
'Are you sure to remove this conversion?', 'Are you sure to remove this conversion?',
'.qu-conversion-delete-button', '.qu-conversion-delete-button',
@ -166,14 +166,15 @@
'objects/quantity_unit_conversions/', 'objects/quantity_unit_conversions/',
() => 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>',
closeButton: false, closeButton: false,
@ -185,5 +186,5 @@
} }
}); });
}); });
} }

View File

@ -7,43 +7,43 @@
} }
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())
{ {
return; return;
} }
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,17 +1,18 @@
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");
function saveRecipePicture(result, location, jsonData) function saveRecipePicture(result, location, jsonData)
{ {
var recipeId = Grocy.EditObjectId || result.created_object_id; var recipeId = Grocy.EditObjectId || result.created_object_id;
@ -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);
@ -37,33 +38,33 @@
} }
}); });
} }
$('.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')
{ {
Grocy.Api.Post('objects/recipes', jsonData, Grocy.Api.Post('objects/recipes', jsonData,
(result) => saveRecipePicture(result, location, jsonData)); (result) => saveRecipePicture(result, location, jsonData));
return; return;
} }
if (Grocy.DeleteRecipePictureOnSave) if (Grocy.DeleteRecipePictureOnSave)
{ {
jsonData.picture_file_name = null; jsonData.picture_file_name = null;
Grocy.Api.DeleteFile(Grocy.RecipePictureFileName, 'recipepictures', {}, Grocy.Api.DeleteFile(Grocy.RecipePictureFileName, 'recipepictures', {},
function(result) function(result)
{ {
@ -76,7 +77,7 @@
} }
); );
} }
Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, jsonData, Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, jsonData,
(result) => saveRecipePicture(result, location, jsonData), (result) => saveRecipePicture(result, location, jsonData),
function(xhr) function(xhr)
@ -86,8 +87,8 @@
} }
); );
}); });
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,44 +101,44 @@
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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('recipe-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('recipe-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
else else
{ {
$('#save-recipe-button').click(); $scope('#save-recipe-button').click();
} }
} }
}); });
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete recipe ingredient "%s"?', 'Are you sure to delete recipe ingredient "%s"?',
'.recipe-pos-delete-button', '.recipe-pos-delete-button',
@ -146,7 +147,7 @@
'objects/recipes_pos/', 'objects/recipes_pos/',
() => window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl) () => window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl)
); );
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to remove the included recipe "%s"?', 'Are you sure to remove the included recipe "%s"?',
'.recipe-include-delete-button', '.recipe-include-delete-button',
@ -155,21 +156,22 @@
'objects/recipes_nesting/', 'objects/recipes_nesting/',
() => 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();
var productId = $(e.currentTarget).attr("data-product-id"); var productId = $(e.currentTarget).attr("data-product-id");
var recipePosId = $(e.currentTarget).attr('data-recipe-pos-id'); var recipePosId = $(e.currentTarget).attr('data-recipe-pos-id');
bootbox.dialog({ bootbox.dialog({
message: '<iframe height="650px" class="embed-responsive" src="' + U("/recipe/") + Grocy.EditObjectId.toString() + '/pos/' + recipePosId.toString() + '?embedded&product=' + productId.toString() + '"></iframe>', message: '<iframe height="650px" class="embed-responsive" src="' + U("/recipe/") + Grocy.EditObjectId.toString() + '/pos/' + recipePosId.toString() + '?embedded&product=' + productId.toString() + '"></iframe>',
size: 'large', size: 'large',
@ -187,22 +189,22 @@
} }
}); });
}); });
$(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)
@ -211,11 +213,11 @@
} }
); );
}); });
$("#recipe-pos-add-button").on("click", function(e) $scope("#recipe-pos-add-button").on("click", function(e)
{ {
e.preventDefault(); e.preventDefault();
bootbox.dialog({ bootbox.dialog({
message: '<iframe height="650px" class="embed-responsive" src="' + U("/recipe/") + Grocy.EditObjectId + '/pos/new?embedded"></iframe>', message: '<iframe height="650px" class="embed-responsive" src="' + U("/recipe/") + Grocy.EditObjectId + '/pos/new?embedded"></iframe>',
size: 'large', size: 'large',
@ -233,17 +235,17 @@
} }
}); });
}); });
$("#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)
@ -252,29 +254,29 @@
} }
); );
}); });
$('#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;
} }
if (document.getElementById("recipe-include-form").checkValidity() === false) //There is at least one validation error if (document.getElementById("recipe-include-form").checkValidity() === false) //There is at least one validation error
{ {
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')
{ {
Grocy.Api.Post('objects/recipes_nestings', jsonData, Grocy.Api.Post('objects/recipes_nestings', jsonData,
@ -302,32 +304,32 @@
); );
} }
}); });
$("#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();
$(window).on("message", function(e) $(window).on("message", function(e)
{ {
var data = e.originalEvent.data; var data = e.originalEvent.data;
if (data.Message === "IngredientsChanged") if (data.Message === "IngredientsChanged")
{ {
Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(), Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(),
@ -342,5 +344,7 @@
); );
} }
}); });
} }
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,29 +8,27 @@
$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;
Grocy.FrontendHelpers.BeginUiBusy("recipe-pos-form"); Grocy.FrontendHelpers.BeginUiBusy("recipe-pos-form");
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
{ {
Grocy.Api.Post('objects/recipes_pos', jsonData, Grocy.Api.Post('objects/recipes_pos', jsonData,
@ -60,15 +60,15 @@
); );
} }
}); });
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.Components.ProductCard.Refresh(productId); Grocy.Components.ProductCard.Refresh(productId);
Grocy.Api.Get('stock/products/' + productId, Grocy.Api.Get('stock/products/' + productId,
function(productDetails) function(productDetails)
{ {
@ -80,18 +80,18 @@
{ {
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id); Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
} }
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;
}, },
@ -102,21 +102,21 @@
); );
} }
}); });
Grocy.FrontendHelpers.ValidateForm('recipe-pos-form'); Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
if (Grocy.Components.ProductPicker.InProductAddWorkflow() === false) if (Grocy.Components.ProductPicker.InProductAddWorkflow() === false)
{ {
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
} }
Grocy.Components.ProductPicker.GetPicker().trigger('change'); Grocy.Components.ProductPicker.GetPicker().trigger('change');
if (Grocy.EditMode == "create") if (Grocy.EditMode == "create")
{ {
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)
{ {
@ -127,54 +127,56 @@
$(this).select(); $(this).select();
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('recipe-pos-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('recipe-pos-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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,14 +1,16 @@
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;
} }
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,91 +26,91 @@
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")
{ {
value = ""; value = "";
} }
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');
} }
} }
}); });
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete recipe "%s"?', 'Are you sure to delete recipe "%s"?',
'.recipe-delete', '.recipe-delete',
@ -117,7 +119,7 @@
'objects/recipes/', 'objects/recipes/',
'/recipes' '/recipes'
); );
Grocy.FrontendHelpers.MakeYesNoBox( Grocy.FrontendHelpers.MakeYesNoBox(
(e) => (e) =>
{ {
@ -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) =>
@ -135,13 +137,13 @@
if (result === true) if (result === true)
{ {
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"));
}); });
Grocy.Api.Post('recipes/' + objectId + '/add-not-fulfilled-products-to-shoppinglist', { "excludedProductIds": excludedProductIds }, Grocy.Api.Post('recipes/' + objectId + '/add-not-fulfilled-products-to-shoppinglist', { "excludedProductIds": excludedProductIds },
function(result) function(result)
{ {
@ -156,7 +158,7 @@
} }
} }
); );
Grocy.FrontendHelpers.MakeYesNoBox( Grocy.FrontendHelpers.MakeYesNoBox(
(e) => (e) =>
{ {
@ -172,7 +174,7 @@
if (result === true) if (result === true)
{ {
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
Grocy.Api.Post('recipes/' + objectId + '/consume', {}, Grocy.Api.Post('recipes/' + objectId + '/consume', {},
function(result) function(result)
{ {
@ -189,12 +191,12 @@
} }
} }
); );
recipesTables.on('select', function(e, dt, type, indexes) recipesTables.on('select', function(e, dt, type, indexes)
{ {
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)
{ {
@ -202,24 +204,24 @@
} }
} }
}); });
$(".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";
} }
@ -228,25 +230,25 @@
window.history.replaceState(null, null, " "); window.history.replaceState(null, null, " ");
} }
}); });
$(".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();
Grocy.Api.Put('objects/recipes/' + $(this).data("recipe-id"), data, Grocy.Api.Put('objects/recipes/' + $(this).data("recipe-id"), data,
function(result) function(result)
{ {
@ -258,20 +260,20 @@
} }
); );
}); });
$(document).on("click", ".missing-recipe-pos-select-button", function(e) top.on("click", ".missing-recipe-pos-select-button", function(e)
{ {
e.preventDefault(); e.preventDefault();
var checkbox = $(this).find(".form-check-input"); var checkbox = $(this).find(".form-check-input");
checkbox.prop("checked", !checkbox.prop("checked")); checkbox.prop("checked", !checkbox.prop("checked"));
$(this).toggleClass("list-group-item-primary"); $(this).toggleClass("list-group-item-primary");
}); });
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) 
// this needs to be explicitly imported for some reason,
// otherwise rollup complains.
import bwipjs from '../../node_modules/bwip-js/dist/bwip-js.mjs';
import { WindowMessageBag } from '../helpers/messagebag';
function shoppinglistView(Grocy, scope = null)
{ {
var $scope = $; var $scope = $;
var top = scope != null ? $(scope) : top;
var viewport = scope != null ? $(scope) : $(window);
if (scope != null) if (scope != null)
{ {
$scope = $(scope).find; $scope = $(scope).find;
} }
// this needs to be explicitly imported for some reason,
// otherwise rollup complains.
import bwipjs from '../../node_modules/bwip-js/dist/bwip-js.mjs';
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("calendarcard"); Grocy.Use("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': [
@ -51,41 +55,41 @@
} }
}); });
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);
}); });
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();
// 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 shoppingListItemId = $(e.currentTarget).attr('data-shoppinglist-id'); var shoppingListItemId = $(e.currentTarget).attr('data-shoppinglist-id');
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
Grocy.Api.Delete('objects/shopping_list/' + shoppingListItemId, {}, Grocy.Api.Delete('objects/shopping_list/' + shoppingListItemId, {},
function(result) function(result)
{ {
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();
}); });
}, },
@ -96,22 +100,22 @@
} }
); );
}); });
$(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)
{ {
@ -119,8 +123,8 @@
} }
); );
}); });
$(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)
@ -142,23 +146,23 @@
} }
); );
}); });
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) =>
{ {
if (result === true) if (result === true)
{ {
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();
}); });
}, },
@ -171,120 +175,120 @@
} }
} }
); );
$(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();
// 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 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;
Grocy.ShoppingListToStockWorkflowCurrent = 0; Grocy.ShoppingListToStockWorkflowCurrent = 0;
}) })
$(window).on("message", function(e) $(window).on("message", function(e)
{ {
var data = e.originalEvent.data; var data = e.originalEvent.data;
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();
// 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();
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
var listItemId = $(e.currentTarget).attr('data-item-id'); var listItemId = $(e.currentTarget).attr('data-item-id');
var done = 1; var done = 1;
if ($(e.currentTarget).attr('data-item-done') == 1) if ($(e.currentTarget).attr('data-item-done') == 1)
{ {
done = 0; done = 0;
} }
$(e.currentTarget).attr('data-item-done', done); $(e.currentTarget).attr('data-item-done', done);
Grocy.Api.Put('objects/shopping_list/' + listItemId, { 'done': done }, Grocy.Api.Put('objects/shopping_list/' + listItemId, { 'done': done },
function() function()
{ {
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();
}, },
function(xhr) function(xhr)
@ -293,9 +297,9 @@
console.error(xhr); console.error(xhr);
} }
); );
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", ""));
@ -305,20 +309,20 @@
statusInfoCell.text(statusInfoCell.text() + " xxUNDONExx"); statusInfoCell.text(statusInfoCell.text() + " xxUNDONExx");
} }
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> \
@ -364,7 +368,7 @@
for="print-layout-type-list">' + __t('List') + ' \ for="print-layout-type-list">' + __t('List') + ' \
</label> \ </label> \
</div>'; </div>';
var sizePrintDialog = 'medium'; var sizePrintDialog = 'medium';
var printButtons = { var printButtons = {
cancel: { cancel: {
@ -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,41 +427,41 @@
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();
} }
} }
} }
if (!Grocy.FeatureFlags["GROCY_FEATURE_FLAG_THERMAL_PRINTER"]) if (!Grocy.FeatureFlags["GROCY_FEATURE_FLAG_THERMAL_PRINTER"])
{ {
delete printButtons['printtp']; delete printButtons['printtp'];
sizePrintDialog = 'small'; sizePrintDialog = 'small';
} }
bootbox.dialog({ bootbox.dialog({
message: dialogHtml, message: dialogHtml,
size: sizePrintDialog, size: sizePrintDialog,
@ -467,30 +471,30 @@
buttons: printButtons buttons: printButtons
}); });
}); });
$("#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)
{ {
@ -498,35 +502,35 @@
} }
); );
}); });
$(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)
{ {
var data = e.originalEvent.data; var data = e.originalEvent.data;
if (data.Message === "ShoppingListChanged") if (data.Message === "ShoppingListChanged")
{ {
window.location.href = U('/shoppinglist?list=' + data.Payload); window.location.href = U('/shoppinglist?list=' + data.Payload);
} }
}); });
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, "");
var barcodeType = "code128"; var barcodeType = "code128";
if (barcode.length == 8) if (barcode.length == 8)
{ {
@ -536,20 +540,22 @@
{ {
barcodeType = "ean13"; barcodeType = "ean13";
} }
bwipjs.toCanvas(dummyCanvas, { bwipjs.toCanvas(dummyCanvas, {
bcid: barcodeType, bcid: barcodeType,
text: barcode, text: barcode,
height: 5, height: 5,
includetext: false includetext: false
}); });
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

@ -7,21 +7,21 @@
} }
import { WindowMessageBag } from '../helpers/messagebag'; import { WindowMessageBag } from '../helpers/messagebag';
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')
{ {
Grocy.Api.Post('objects/shopping_lists', jsonData, Grocy.Api.Post('objects/shopping_lists', jsonData,
@ -62,31 +62,31 @@
}); });
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('shopping-list-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('shopping-list-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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,49 +8,47 @@
$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;
} }
delete jsonData.display_amount; delete jsonData.display_amount;
Grocy.FrontendHelpers.BeginUiBusy("shoppinglist-form"); Grocy.FrontendHelpers.BeginUiBusy("shoppinglist-form");
if (GetUriParam("updateexistingproduct") !== undefined) if (GetUriParam("updateexistingproduct") !== undefined)
{ {
jsonData.product_amount = jsonData.amount; jsonData.product_amount = jsonData.amount;
delete jsonData.amount; delete jsonData.amount;
Grocy.Api.Post('stock/shoppinglist/add-product', jsonData, Grocy.Api.Post('stock/shoppinglist/add-product', jsonData,
function(result) function(result)
{ {
Grocy.EditObjectId = result.created_object_id; Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(); Grocy.Components.UserfieldsForm.Save();
if (GetUriParam("embedded") !== undefined) if (GetUriParam("embedded") !== undefined)
{ {
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)
@ -76,7 +76,7 @@
{ {
Grocy.EditObjectId = result.created_object_id; Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(); Grocy.Components.UserfieldsForm.Save();
if (GetUriParam("embedded") !== undefined) if (GetUriParam("embedded") !== undefined)
{ {
if (jsonData.product_id) if (jsonData.product_id)
@ -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)
@ -118,7 +118,7 @@
function(result) function(result)
{ {
Grocy.Components.UserfieldsForm.Save(); Grocy.Components.UserfieldsForm.Save();
if (GetUriParam("embedded") !== undefined) if (GetUriParam("embedded") !== undefined)
{ {
if (jsonData.product_id) if (jsonData.product_id)
@ -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)
@ -155,11 +155,11 @@
); );
} }
}); });
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,
@ -174,14 +174,14 @@
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);
} }
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;
}, },
@ -191,91 +191,94 @@
} }
); );
} }
$("#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');
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
if (Grocy.EditMode === "edit") if (Grocy.EditMode === "edit")
{ {
Grocy.Components.ProductPicker.GetPicker().trigger('change'); Grocy.Components.ProductPicker.GetPicker().trigger('change');
} }
if (Grocy.EditMode == "create") if (Grocy.EditMode == "create")
{ {
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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('shoppinglist-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('shoppinglist-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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');
} }
if (GetUriParam("embedded") !== undefined) if (GetUriParam("embedded") !== undefined)
{ {
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
{ {
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
} }
} }
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);
}); });
if (GetUriParam("product-name") != null) if (GetUriParam("product-name") != null)
{ {
Grocy.Components.ProductPicker.GetPicker().trigger('change'); Grocy.Components.ProductPicker.GetPicker().trigger('change');
} }
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,22 +8,20 @@
$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')
{ {
Grocy.Api.Post('objects/shopping_locations', jsonData, Grocy.Api.Post('objects/shopping_locations', jsonData,
@ -72,31 +72,33 @@
); );
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('shoppinglocation-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('shoppinglocation-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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,16 +6,16 @@
$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(
'Are you sure to delete store "%s"?', 'Are you sure to delete store "%s"?',
'.shoppinglocation-delete-button', '.shoppinglocation-delete-button',

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;
@ -8,63 +10,65 @@
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)
{ {
var productId = Grocy.Components.ProductPicker.GetValue(); var productId = Grocy.Components.ProductPicker.GetValue();
if ((isNaN(productId) || productId == "" || productId == data[1])) if ((isNaN(productId) || productId == "" || productId == data[1]))
{ {
return true; return true;
} }
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();
}); });
Grocy.Components.ProductPicker.GetPicker().on('change', function(e) Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{ {
stockEntriesTable.draw(); stockEntriesTable.draw();
}); });
Grocy.Components.ProductPicker.GetInputElement().on('keyup', function(e) Grocy.Components.ProductPicker.GetInputElement().on('keyup', function(e)
{ {
stockEntriesTable.draw(); stockEntriesTable.draw();
}); });
$(document).on('click', '.stock-consume-button', function(e) top.on('click', '.stock-consume-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
// 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();
Grocy.FrontendHelpers.BeginUiBusy(); Grocy.FrontendHelpers.BeginUiBusy();
var productId = $(e.currentTarget).attr('data-product-id');
var locationId = $(e.currentTarget).attr('data-location-id'); var target = $(e.currentTarget);
var specificStockEntryId = $(e.currentTarget).attr('data-stock-id'); var productId = target.attr('data-product-id');
var stockRowId = $(e.currentTarget).attr('data-stockrow-id'); var locationId = target.attr('data-location-id');
var consumeAmount = $(e.currentTarget).attr('data-consume-amount'); var specificStockEntryId = target.attr('data-stock-id');
var stockRowId = target.attr('data-stockrow-id');
var wasSpoiled = $(e.currentTarget).hasClass("stock-consume-button-spoiled"); 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)
{ {
@ -76,7 +80,7 @@
{ {
toastMessage += " (" + __t("Spoiled") + ")"; toastMessage += " (" + __t("Spoiled") + ")";
} }
Grocy.FrontendHelpers.EndUiBusy(); Grocy.FrontendHelpers.EndUiBusy();
RefreshStockEntryRow(stockRowId); RefreshStockEntryRow(stockRowId);
toastr.success(toastMessage); toastr.success(toastMessage);
@ -95,24 +99,25 @@
} }
); );
}); });
$(document).on('click', '.product-open-button', function(e) top.on('click', '.product-open-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
// 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();
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)
{ {
@ -128,18 +133,18 @@
} }
); );
}); });
$(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();
var stockId = $(e.currentTarget).attr('data-stock-id'); var stockId = $(e.currentTarget).attr('data-stock-id');
Grocy.Api.Get('stock/entry/' + stockId + '/printlabel', function(labelData) Grocy.Api.Get('stock/entry/' + stockId + '/printlabel', function(labelData)
{ {
@ -149,25 +154,25 @@
} }
}); });
}); });
function RefreshStockEntryRow(stockRowId) function RefreshStockEntryRow(stockRowId)
{ {
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"))
{ {
window.location.reload(); window.location.reload();
} }
if (result == null || result.amount == 0) if (result == null || result.amount == 0)
{ {
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
@ -175,7 +180,7 @@
var dueThreshold = moment().add(Grocy.UserSettings.stock_due_soon_days, "days"); var dueThreshold = moment().add(Grocy.UserSettings.stock_due_soon_days, "days");
var now = moment(); var now = moment();
var bestBeforeDate = moment(result.best_before_date); var bestBeforeDate = moment(result.best_before_date);
stockRow.removeClass("table-warning"); stockRow.removeClass("table-warning");
stockRow.removeClass("table-danger"); stockRow.removeClass("table-danger");
stockRow.removeClass("table-info"); stockRow.removeClass("table-info");
@ -196,60 +201,60 @@
{ {
stockRow.addClass("table-warning"); stockRow.addClass("table-warning");
} }
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,
function(locationResult) function(locationResult)
{ {
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)
{ {
console.error(xhr); console.error(xhr);
} }
); );
$('#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,
function(shoppingLocationResult) function(shoppingLocationResult)
{ {
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)
{ {
console.error(xhr); console.error(xhr);
} }
); );
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");
} }
} }
// Needs to be delayed because of the animation above the date-text would be wrong if fired immediately... // Needs to be delayed because of the animation above the date-text would be wrong if fired immediately...
setTimeout(function() setTimeout(function()
{ {
@ -264,23 +269,23 @@
} }
); );
} }
$(window).on("message", function(e) $(window).on("message", function(e)
{ {
var data = e.originalEvent.data; var data = e.originalEvent.data;
if (data.Message === "StockEntryChanged") if (data.Message === "StockEntryChanged")
{ {
RefreshStockEntryRow(data.Payload); RefreshStockEntryRow(data.Payload);
} }
}); });
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,31 +8,29 @@
$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())
{ {
jsonData.price = parseFloat(jsonForm.price).toFixed(Grocy.UserSettings.stock_decimal_places_prices); jsonData.price = parseFloat(jsonForm.price).toFixed(Grocy.UserSettings.stock_decimal_places_prices);
} }
var jsonData = {}; var jsonData = {};
jsonData.amount = jsonForm.amount; jsonData.amount = jsonForm.amount;
jsonData.best_before_date = Grocy.Components.DateTimePicker.GetValue(); jsonData.best_before_date = Grocy.Components.DateTimePicker.GetValue();
@ -47,14 +47,14 @@
{ {
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)
{ {
var successMessage = __t('Stock entry successfully updated') + '<br><a class="btn btn-secondary btn-sm mt-2" href="#" onclick="Grocy.UndoStockBookingEntry(\'' + result.id + '\',\'' + Grocy.EditObjectId + '\')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>'; var successMessage = __t('Stock entry successfully updated') + '<br><a class="btn btn-secondary btn-sm mt-2" href="#" onclick="Grocy.UndoStockBookingEntry(\'' + result.id + '\',\'' + Grocy.EditObjectId + '\')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>';
window.parent.postMessage(WindowMessageBag("StockEntryChanged", Grocy.EditObjectId), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("StockEntryChanged", Grocy.EditObjectId), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", successMessage), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", successMessage), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("Ready"), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("Ready"), Grocy.BaseUrl);
@ -67,67 +67,69 @@
} }
); );
}); });
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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('stockentry-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('stockentry-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
else else
{ {
$('#save-stockentry-button').click(); $scope('#save-stockentry-button').click();
} }
} }
}); });
Grocy.Components.DateTimePicker.GetInputElement().on('change', function(e) Grocy.Components.DateTimePicker.GetInputElement().on('change', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('stockentry-form'); Grocy.FrontendHelpers.ValidateForm('stockentry-form');
}); });
Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e) Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('stockentry-form'); Grocy.FrontendHelpers.ValidateForm('stockentry-form');
}); });
Grocy.Components.DateTimePicker2.GetInputElement().on('change', function(e) Grocy.Components.DateTimePicker2.GetInputElement().on('change', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('stockentry-form'); Grocy.FrontendHelpers.ValidateForm('stockentry-form');
}); });
Grocy.Components.DateTimePicker2.GetInputElement().on('keypress', function(e) Grocy.Components.DateTimePicker2.GetInputElement().on('keypress', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('stockentry-form'); Grocy.FrontendHelpers.ValidateForm('stockentry-form');
}); });
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)
{ {
console.error(xhr); console.error(xhr);
} }
); );
$("#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,33 +15,33 @@
{ '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);
Grocy.FrontendHelpers.MakeFilterForColumn("#transaction-type-filter", 4, stockJournalTable); Grocy.FrontendHelpers.MakeFilterForColumn("#transaction-type-filter", 4, stockJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#location-filter", 5, stockJournalTable); Grocy.FrontendHelpers.MakeFilterForColumn("#location-filter", 5, stockJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#user-filter", 6, stockJournalTable); Grocy.FrontendHelpers.MakeFilterForColumn("#user-filter", 6, stockJournalTable);
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', {},
function(result) function(result)
{ {
@ -57,5 +58,5 @@
} }
); );
}); });
} }

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,10 +14,10 @@
{ '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);
Grocy.FrontendHelpers.MakeFilterForColumn("#product-filter", 1, journalSummaryTable); Grocy.FrontendHelpers.MakeFilterForColumn("#product-filter", 1, journalSummaryTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#transaction-type-filter", 2, journalSummaryTable); Grocy.FrontendHelpers.MakeFilterForColumn("#transaction-type-filter", 2, journalSummaryTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#user-filter", 3, journalSummaryTable); Grocy.FrontendHelpers.MakeFilterForColumn("#user-filter", 3, journalSummaryTable);

View File

@ -1,14 +1,15 @@
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;
} }
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 },
@ -33,19 +34,19 @@
{ "type": "num", "targets": 13 } { "type": "num", "targets": 13 }
].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)
@ -54,24 +55,24 @@
} }
}); });
}); });
$(document).on('click', '.product-consume-button', function(e) top.on('click', '.product-consume-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
// 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();
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');
var originalTotalStockAmount = target.attr('data-original-total-stock-amount'); var originalTotalStockAmount = target.attr('data-original-total-stock-amount');
var wasSpoiled = target.hasClass("product-consume-button-spoiled"); var wasSpoiled = target.hasClass("product-consume-button-spoiled");
Grocy.Api.Post('stock/products/' + productId + '/consume', { 'amount': consumeAmount, 'spoiled': wasSpoiled, 'allow_subproduct_substitution': true }, Grocy.Api.Post('stock/products/' + productId + '/consume', { 'amount': consumeAmount, 'spoiled': wasSpoiled, 'allow_subproduct_substitution': true },
function(bookingResponse) function(bookingResponse)
{ {
@ -87,12 +88,12 @@
{ {
toastMessage = __t('Removed %1$s of %2$s from stock', parseFloat(consumeAmount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }) + " " + __n(consumeAmount, result.quantity_unit_stock.name, result.quantity_unit_stock.name_plural), result.product.name) + '<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>'; toastMessage = __t('Removed %1$s of %2$s from stock', parseFloat(consumeAmount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }) + " " + __n(consumeAmount, result.quantity_unit_stock.name, result.quantity_unit_stock.name_plural), result.product.name) + '<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 (wasSpoiled) if (wasSpoiled)
{ {
toastMessage += " (" + __t("Spoiled") + ")"; toastMessage += " (" + __t("Spoiled") + ")";
} }
Grocy.FrontendHelpers.EndUiBusy(); Grocy.FrontendHelpers.EndUiBusy();
toastr.success(toastMessage); toastr.success(toastMessage);
RefreshStatistics(); RefreshStatistics();
@ -112,24 +113,24 @@
} }
); );
}); });
$(document).on('click', '.product-open-button', function(e) top.on('click', '.product-open-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
// 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();
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');
var productQuName = button.attr('data-product-qu-name'); var productQuName = button.attr('data-product-qu-name');
var amount = button.attr('data-open-amount'); var amount = button.attr('data-open-amount');
Grocy.Api.Post('stock/products/' + productId + '/open', { 'amount': amount, 'allow_subproduct_substitution': true }, Grocy.Api.Post('stock/products/' + productId + '/open', { 'amount': amount, 'allow_subproduct_substitution': true },
function(bookingResponse) function(bookingResponse)
{ {
@ -140,7 +141,7 @@
{ {
button.addClass("disabled"); button.addClass("disabled");
} }
Grocy.FrontendHelpers.EndUiBusy(); Grocy.FrontendHelpers.EndUiBusy();
toastr.success(__t('Marked %1$s of %2$s as opened', parseFloat(amount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }) + " " + productQuName, productName) + '<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>'); toastr.success(__t('Marked %1$s of %2$s as opened', parseFloat(amount).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }) + " " + productQuName, productName) + '<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>');
RefreshStatistics(); RefreshStatistics();
@ -160,13 +161,13 @@
} }
); );
}); });
$(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");
}); });
function RefreshStatistics() function RefreshStatistics()
{ {
Grocy.Api.Get('stock', Grocy.Api.Get('stock',
@ -191,15 +192,15 @@
console.error(xhr); console.error(xhr);
} }
); );
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)
{ {
@ -208,11 +209,11 @@
); );
} }
RefreshStatistics(); RefreshStatistics();
function RefreshProductRow(productId) function RefreshProductRow(productId)
{ {
productId = productId.toString(); productId = productId.toString();
Grocy.Api.Get('stock/products/' + productId, Grocy.Api.Get('stock/products/' + productId,
function(result) function(result)
{ {
@ -221,12 +222,12 @@
{ {
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);
productRow.removeClass("table-warning"); productRow.removeClass("table-warning");
productRow.removeClass("table-danger"); productRow.removeClass("table-danger");
productRow.removeClass("table-secondary"); productRow.removeClass("table-secondary");
@ -248,68 +249,68 @@
{ {
productRow.addClass("table-warning"); productRow.addClass("table-warning");
} }
if (result.stock_amount == 0 && result.stock_amount_aggregated == 0 && result.product.min_stock_amount == 0) if (result.stock_amount == 0 && result.stock_amount_aggregated == 0 && result.product.min_stock_amount == 0)
{ {
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)
{ {
productRow.addClass("table-info"); productRow.addClass("table-info");
} }
} }
$('#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("");
} }
} }
// Needs to be delayed because of the animation above the date-text would be wrong if fired immediately... // Needs to be delayed because of the animation above the date-text would be wrong if fired immediately...
setTimeout(function() setTimeout(function()
{ {
@ -324,16 +325,16 @@
} }
); );
} }
$(window).on("message", function(e) $(window).on("message", function(e)
{ {
var data = e.originalEvent.data; var data = e.originalEvent.data;
if (data.Message === "ProductChanged") if (data.Message === "ProductChanged")
{ {
RefreshProductRow(data.Payload); RefreshProductRow(data.Payload);
RefreshStatistics(); RefreshStatistics();
} }
}); });
} }

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,16 +6,16 @@
$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(
'Are you sure to delete task category "%s"?', 'Are you sure to delete task category "%s"?',
'.task-category-delete-button', '.task-category-delete-button',

View File

@ -7,19 +7,19 @@
} }
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')
{ {
Grocy.Api.Post('objects/task_categories', jsonData, Grocy.Api.Post('objects/task_categories', jsonData,
@ -70,31 +70,31 @@
); );
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('task-category-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('task-category-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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

@ -7,26 +7,26 @@
} }
import { WindowMessageBag } from '../helpers/messagebag'; import { WindowMessageBag } from '../helpers/messagebag';
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();
Grocy.FrontendHelpers.BeginUiBusy("task-form"); Grocy.FrontendHelpers.BeginUiBusy("task-form");
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
{ {
Grocy.Api.Post('objects/tasks', jsonData, Grocy.Api.Post('objects/tasks', jsonData,
@ -77,32 +77,32 @@
); );
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('task-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('task-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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,14 +1,16 @@
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;
} }
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,47 +23,48 @@
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();
// 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();
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();
toastr.success(__t('Marked task %s as completed on %s', taskName, doneTime)); toastr.success(__t('Marked task %s as completed on %s', taskName, doneTime));
RefreshContextualTimeago("#task-" + taskId + "-row"); RefreshContextualTimeago("#task-" + taskId + "-row");
@ -74,19 +77,19 @@
} }
); );
}); });
$(document).on('click', '.undo-task-button', function(e) top.on('click', '.undo-task-button', function(e)
{ {
e.preventDefault(); e.preventDefault();
// 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();
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()
{ {
@ -99,7 +102,7 @@
} }
); );
}); });
Grocy.FrontendHelpers.MakeDeleteConfirmBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete task "%s"?', 'Are you sure to delete task "%s"?',
'.delete-task-button', '.delete-task-button',
@ -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)
{ {
@ -127,15 +130,15 @@
window.location.href = U('/tasks'); window.location.href = U('/tasks');
} }
}); });
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)
{ {
@ -155,9 +158,9 @@
dueCount++; dueCount++;
} }
}); });
$("#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)
{ {
@ -165,7 +168,7 @@
} }
); );
} }
RefreshStatistics(); RefreshStatistics();
} }

View File

@ -7,9 +7,9 @@
} }
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,38 +8,36 @@
$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;
} }
var bookingResponse = null; var bookingResponse = null;
Grocy.Api.Get('stock/products/' + jsonForm.product_id, Grocy.Api.Get('stock/products/' + jsonForm.product_id,
function(productDetails) function(productDetails)
{ {
@ -45,19 +45,19 @@
function(result) function(result)
{ {
bookingResponse = result; bookingResponse = result;
if (GetUriParam("flow") === "InplaceAddBarcodeToExistingProduct") if (GetUriParam("flow") === "InplaceAddBarcodeToExistingProduct")
{ {
var jsonDataBarcode = {}; var jsonDataBarcode = {};
jsonDataBarcode.barcode = GetUriParam("barcode"); jsonDataBarcode.barcode = GetUriParam("barcode");
jsonDataBarcode.product_id = jsonForm.product_id; jsonDataBarcode.product_id = jsonForm.product_id;
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)
@ -71,26 +71,26 @@
if (productDetails.product.enable_tare_weight_handling == 1) if (productDetails.product.enable_tare_weight_handling == 1)
{ {
amount = Math.abs(jsonForm.amount - parseFloat(productDetails.product.tare_weight)).toString(); amount = Math.abs(jsonForm.amount - parseFloat(productDetails.product.tare_weight)).toString();
} }
else else
{ {
amount = Math.abs(jsonForm.amount).toString() amount = Math.abs(jsonForm.amount).toString()
} }
amount += " " + amount += " " +
__n(jsonForm.amount, __n(jsonForm.amount,
productDetails.quantity_unit_stock.name, productDetails.quantity_unit_stock.name,
productDetails.quantity_unit_stock.name_plural productDetails.quantity_unit_stock.name_plural
); );
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)
{ {
window.parent.postMessage(WindowMessageBag("ProductChanged", jsonForm.product_id), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("ProductChanged", jsonForm.product_id), Grocy.BaseUrl);
@ -102,35 +102,35 @@
Grocy.FrontendHelpers.EndUiBusy("transfer-form"); Grocy.FrontendHelpers.EndUiBusy("transfer-form");
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');
@ -150,40 +150,40 @@
} }
); );
}); });
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)
{ {
Grocy.Components.ProductCard.Refresh(productId); Grocy.Components.ProductCard.Refresh(productId);
Grocy.Api.Get('stock/products/' + productId, Grocy.Api.Get('stock/products/' + productId,
function(productDetails) function(productDetails)
{ {
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);
if (productDetails.product.enable_tare_weight_handling == 1) if (productDetails.product.enable_tare_weight_handling == 1)
{ {
Grocy.Components.ProductPicker.GetPicker().parent().find(".invalid-feedback").text(__t('Products with tare weight enabled are currently not supported for transfer')); Grocy.Components.ProductPicker.GetPicker().parent().find(".invalid-feedback").text(__t('Products with tare weight enabled are currently not supported for transfer'));
Grocy.Components.ProductPicker.Clear(); Grocy.Components.ProductPicker.Clear();
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,35 +192,35 @@
{ {
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
})); }));
} }
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)
@ -228,7 +228,7 @@
console.error(xhr); console.error(xhr);
} }
); );
if (document.getElementById("product_id").getAttribute("barcode") != "null") if (document.getElementById("product_id").getAttribute("barcode") != "null")
{ {
Grocy.Api.Get('objects/product_barcodes?query[]=barcode=' + document.getElementById("product_id").getAttribute("barcode"), Grocy.Api.Get('objects/product_barcodes?query[]=barcode=' + document.getElementById("product_id").getAttribute("barcode"),
@ -237,21 +237,21 @@
if (barcodeResult != null) if (barcodeResult != null)
{ {
var barcode = barcodeResult[0]; var barcode = barcodeResult[0];
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)
{ {
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();
} }
@ -263,20 +263,20 @@
} }
); );
} }
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)
{ {
Grocy.Components.ProductPicker.Clear(); Grocy.Components.ProductPicker.Clear();
@ -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)
@ -298,34 +298,34 @@
); );
} }
}); });
$('#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)
{ {
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)
{ {
Grocy.Api.Get("stock/products/" + Grocy.Components.ProductPicker.GetValue() + '/entries', Grocy.Api.Get("stock/products/" + Grocy.Components.ProductPicker.GetValue() + '/entries',
@ -338,25 +338,25 @@
{ {
openTxt = __t("Opened"); openTxt = __t("Opened");
} }
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)
@ -366,56 +366,56 @@
); );
} }
}); });
$("#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('transfer-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('transfer-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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,35 +444,35 @@
} }
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");
}); });
if (GetUriParam("embedded") !== undefined) if (GetUriParam("embedded") !== undefined)
{ {
var locationId = GetUriParam('locationId'); var locationId = GetUriParam('locationId');
if (typeof locationId === 'undefined') if (typeof locationId === 'undefined')
{ {
Grocy.Components.ProductPicker.GetPicker().trigger('change'); Grocy.Components.ProductPicker.GetPicker().trigger('change');
@ -480,16 +480,19 @@
} }
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');
} }
} }
// Default input field // Default input field
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
} }
window.transferView = transferView;

View File

@ -6,16 +6,16 @@
$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(
'Are you sure to delete userentity "%s"?', 'Are you sure to delete userentity "%s"?',
'.userentity-delete-button', '.userentity-delete-button',

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,22 +8,20 @@
$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");
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
{ {
Grocy.Api.Post('objects/userentities', jsonData, Grocy.Api.Post('objects/userentities', jsonData,
@ -65,51 +65,53 @@
); );
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('userentity-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('userentity-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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,28 +8,26 @@
$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");
if (typeof GetUriParam("entity") !== "undefined" && !GetUriParam("entity").isEmpty()) if (typeof GetUriParam("entity") !== "undefined" && !GetUriParam("entity").isEmpty())
{ {
redirectUrl = U("/userfields?entity=" + GetUriParam("entity")); redirectUrl = U("/userfields?entity=" + GetUriParam("entity"));
} }
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
{ {
Grocy.Api.Post('objects/userfields', jsonData, Grocy.Api.Post('objects/userfields', jsonData,
@ -71,60 +71,62 @@
); );
} }
}); });
$('#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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('userfield-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('userfield-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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,35 +6,35 @@
$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(
'Are you sure to delete user field "%s"?', 'Are you sure to delete user field "%s"?',
'.userfield-delete-button', '.userfield-delete-button',
@ -43,12 +43,12 @@
'objects/userfields/', 'objects/userfields/',
'/userfields' '/userfields'
); );
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

@ -7,14 +7,14 @@
} }
Grocy.Use("userfieldsform"); Grocy.Use("userfieldsform");
function SaveUserPicture(result, jsonData) function SaveUserPicture(result, jsonData)
{ {
Grocy.Components.UserfieldsForm.Save(() => Grocy.Components.UserfieldsForm.Save(() =>
{ {
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');
@ -32,25 +32,25 @@
} }
}); });
} }
$('#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')
{ {
Grocy.Api.Post('users', jsonData, Grocy.Api.Post('users', jsonData,
@ -67,7 +67,7 @@
if (Grocy.DeleteUserPictureOnSave) if (Grocy.DeleteUserPictureOnSave)
{ {
jsonData.picture_file_name = null; jsonData.picture_file_name = null;
Grocy.Api.DeleteFile(Grocy.UserPictureFileName, 'userpictures', {}, Grocy.Api.DeleteFile(Grocy.UserPictureFileName, 'userpictures', {},
function(result) function(result)
{ {
@ -80,7 +80,7 @@
} }
); );
} }
Grocy.Api.Put('users/' + Grocy.EditObjectId, jsonData, Grocy.Api.Put('users/' + Grocy.EditObjectId, jsonData,
(result) => SaveUserPicture(result, jsonData), (result) => SaveUserPicture(result, jsonData),
function(xhr) function(xhr)
@ -91,11 +91,11 @@
); );
} }
}); });
$('#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");
} }
@ -103,56 +103,56 @@
{ {
element.setCustomValidity(""); element.setCustomValidity("");
} }
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
{ {
event.preventDefault(); event.preventDefault();
if (document.getElementById('user-form').checkValidity() === false) //There is at least one validation error if (document.getElementById('user-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return false;
} }
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();
Grocy.FrontendHelpers.ValidateForm('user-form'); Grocy.FrontendHelpers.ValidateForm('user-form');
} }

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,24 +8,22 @@
$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;
} }
var jsonData = {}; var jsonData = {};
jsonData.userentity_id = Grocy.EditObjectParentId; jsonData.userentity_id = Grocy.EditObjectParentId;
Grocy.FrontendHelpers.BeginUiBusy("userobject-form"); Grocy.FrontendHelpers.BeginUiBusy("userobject-form");
if (Grocy.EditMode === 'create') if (Grocy.EditMode === 'create')
{ {
Grocy.Api.Post('objects/userobjects', jsonData, Grocy.Api.Post('objects/userobjects', jsonData,
@ -74,8 +74,10 @@
); );
} }
}); });
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,16 +6,16 @@
$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(
'Are you sure to delete this userobject?', 'Are you sure to delete this userobject?',
'.userobject-delete-button', '.userobject-delete-button',

View File

@ -6,25 +6,25 @@
$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);
} }
); );
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');
@ -32,7 +32,7 @@
{ {
return $(this).data('perm-id'); return $(this).data('perm-id');
}).toArray(); }).toArray();
Grocy.Api.Put('users/' + Grocy.EditObjectId + '/permissions', { 'permissions': permission_list }, Grocy.Api.Put('users/' + Grocy.EditObjectId + '/permissions', { 'permissions': permission_list },
function(result) function(result)
{ {
@ -45,13 +45,13 @@
); );
} }
); );
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;
if (!element.checked) if (!element.checked)
{ {
bootbox.confirm({ bootbox.confirm({
@ -79,5 +79,5 @@
} }
}) })
} }
} }

View File

@ -6,16 +6,16 @@
$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(
'Are you sure to delete user "%s"?', 'Are you sure to delete user "%s"?',
'.user-delete-button', '.user-delete-button',

View File

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