viewjs: Wrap in fuctions

This commit's contents were auto-generated. They wrap all viewjs
in functions and define a common prologue.

New file contents:

```js
function VIEWNAMEView(Grocy, scope = null)
{
    var $scope = $;
    if(scope != null)
    {
        $scope = $(scope).find;
    }

    // original contents indented with \t

}
```
This commit is contained in:
Katharina Bogad 2021-06-22 22:38:55 +02:00
parent 151722ea38
commit fd61d1ef62
68 changed files with 9280 additions and 8609 deletions

View File

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

View File

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

View File

@ -1,41 +1,51 @@
var batteriesTable = $('#batteries-table').DataTable({ function batteriesView(Grocy, scope = null)
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ "type": "num", "targets": 4 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#batteries-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(batteriesTable, null, function()
{ {
$("#search").val(""); var $scope = $;
batteriesTable.search("").draw(); if (scope != null)
$("#show-disabled").prop('checked', false);
});
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete battery "%s"?',
'.battery-delete-button',
'data-battery-name',
'data-battery-id',
'objects/batteries/',
'/batteries'
);
$("#show-disabled").change(function()
{
if (this.checked)
{ {
window.location.href = U('/batteries?include_disabled'); $scope = $(scope).find;
}
var batteriesTable = $('#batteries-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ "type": "num", "targets": 4 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#batteries-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(batteriesTable, null, function()
{
$("#search").val("");
batteriesTable.search("").draw();
$("#show-disabled").prop('checked', false);
});
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete battery "%s"?',
'.battery-delete-button',
'data-battery-name',
'data-battery-id',
'objects/batteries/',
'/batteries'
);
$("#show-disabled").change(function()
{
if (this.checked)
{
window.location.href = U('/batteries?include_disabled');
}
else
{
window.location.href = U('/batteries');
}
});
if (GetUriParam('include_disabled'))
{
$("#show-disabled").prop('checked', true);
} }
else
{
window.location.href = U('/batteries');
}
});
if (GetUriParam('include_disabled'))
{
$("#show-disabled").prop('checked', true);
} }

View File

@ -1,40 +1,50 @@
var batteriesJournalTable = $('#batteries-journal-table').DataTable({ function batteriesjournalView(Grocy, scope = null)
'paginate': true,
'order': [[2, 'desc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#batteries-journal-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(batteriesJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#battery-filter", 1, batteriesJournalTable);
if (typeof GetUriParam("battery") !== "undefined")
{ {
$("#battery-filter").val(GetUriParam("battery")); var $scope = $;
$("#battery-filter").trigger("change"); if (scope != null)
{
$scope = $(scope).find;
}
var batteriesJournalTable = $('#batteries-journal-table').DataTable({
'paginate': true,
'order': [[2, 'desc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#batteries-journal-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(batteriesJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#battery-filter", 1, batteriesJournalTable);
if (typeof GetUriParam("battery") !== "undefined")
{
$("#battery-filter").val(GetUriParam("battery"));
$("#battery-filter").trigger("change");
}
$(document).on('click', '.undo-battery-execution-button', function(e)
{
e.preventDefault();
var element = $(e.currentTarget);
var chargeCycleId = $(e.currentTarget).attr('data-charge-cycle-id');
Grocy.Api.Post('batteries/charge-cycles/' + chargeCycleId.toString() + '/undo', {},
function(result)
{
element.closest("tr").addClass("text-muted");
element.parent().siblings().find("span.name-anchor").addClass("text-strike-through").after("<br>" + __t("Undone on") + " " + moment().format("YYYY-MM-DD HH:mm:ss") + " <time class='timeago timeago-contextual' datetime='" + moment().format("YYYY-MM-DD HH:mm:ss") + "'></time>");
element.closest(".undo-battery-execution-button").addClass("disabled");
RefreshContextualTimeago("#charge-cycle-" + chargeCycleId + "-row");
toastr.success(__t("Charge cycle successfully undone"));
},
function(xhr)
{
console.error(xhr);
}
);
});
} }
$(document).on('click', '.undo-battery-execution-button', function(e)
{
e.preventDefault();
var element = $(e.currentTarget);
var chargeCycleId = $(e.currentTarget).attr('data-charge-cycle-id');
Grocy.Api.Post('batteries/charge-cycles/' + chargeCycleId.toString() + '/undo', {},
function(result)
{
element.closest("tr").addClass("text-muted");
element.parent().siblings().find("span.name-anchor").addClass("text-strike-through").after("<br>" + __t("Undone on") + " " + moment().format("YYYY-MM-DD HH:mm:ss") + " <time class='timeago timeago-contextual' datetime='" + moment().format("YYYY-MM-DD HH:mm:ss") + "'></time>");
element.closest(".undo-battery-execution-button").addClass("disabled");
RefreshContextualTimeago("#charge-cycle-" + chargeCycleId + "-row");
toastr.success(__t("Charge cycle successfully undone"));
},
function(xhr)
{
console.error(xhr);
}
);
});

View File

@ -1,122 +1,132 @@
Grocy.Use("batterycard"); function batteriesoverviewView(Grocy, scope = null)
var batteriesOverviewTable = $('#batteries-overview-table').DataTable({
'order': [[4, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ "type": "html", "targets": 3 },
{ "type": "html", "targets": 4 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#batteries-overview-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(batteriesOverviewTable);
Grocy.FrontendHelpers.MakeStatusFilter(batteriesOverviewTable, 5);
$(document).on('click', '.track-charge-cycle-button', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
{
$scope = $(scope).find;
}
// Remove the focus from the current button Grocy.Use("batterycard");
// to prevent that the tooltip stays until clicked anywhere else
document.activeElement.blur();
Grocy.FrontendHelpers.BeginUiBusy(); var batteriesOverviewTable = $('#batteries-overview-table').DataTable({
'order': [[4, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ "type": "html", "targets": 3 },
{ "type": "html", "targets": 4 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#batteries-overview-table tbody').removeClass("d-none");
var batteryId = $(e.currentTarget).attr('data-battery-id'); Grocy.FrontendHelpers.InitDataTable(batteriesOverviewTable);
var batteryName = $(e.currentTarget).attr('data-battery-name'); Grocy.FrontendHelpers.MakeStatusFilter(batteriesOverviewTable, 5);
var trackedTime = moment().format('YYYY-MM-DD HH:mm:ss');
Grocy.Api.Post('batteries/' + batteryId + '/charge', { 'tracked_time': trackedTime }, $(document).on('click', '.track-charge-cycle-button', function(e)
function() {
{ e.preventDefault();
Grocy.Api.Get('batteries/' + batteryId,
function(result)
{
var batteryRow = $('#battery-' + batteryId + '-row');
var nextXDaysThreshold = moment().add($("#info-due-batteries").data("next-x-days"), "days");
var now = moment();
var nextExecutionTime = moment(result.next_estimated_charge_time);
batteryRow.removeClass("table-warning"); // Remove the focus from the current button
batteryRow.removeClass("table-danger"); // to prevent that the tooltip stays until clicked anywhere else
if (nextExecutionTime.isBefore(now)) document.activeElement.blur();
{
batteryRow.addClass("table-danger");
}
else if (nextExecutionTime.isBefore(nextXDaysThreshold))
{
batteryRow.addClass("table-warning");
}
animateCSS("#battery-" + batteryId + "-row td:not(:first)", "shake"); Grocy.FrontendHelpers.BeginUiBusy();
$('#battery-' + batteryId + '-last-tracked-time').text(trackedTime); var batteryId = $(e.currentTarget).attr('data-battery-id');
$('#battery-' + batteryId + '-last-tracked-time-timeago').attr('datetime', trackedTime); var batteryName = $(e.currentTarget).attr('data-battery-name');
if (result.battery.charge_interval_days != 0) var trackedTime = moment().format('YYYY-MM-DD HH:mm:ss');
{
$('#battery-' + batteryId + '-next-charge-time').text(result.next_estimated_charge_time);
$('#battery-' + batteryId + '-next-charge-time-timeago').attr('datetime', result.next_estimated_charge_time);
}
Grocy.FrontendHelpers.EndUiBusy(); Grocy.Api.Post('batteries/' + batteryId + '/charge', { 'tracked_time': trackedTime },
toastr.success(__t('Tracked charge cycle of battery %1$s on %2$s', batteryName, trackedTime)); function()
RefreshContextualTimeago("#battery-" + batteryId + "-row");
RefreshStatistics();
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
$(document).on("click", ".battery-name-cell", function(e)
{
Grocy.Components.BatteryCard.Refresh($(e.currentTarget).attr("data-battery-id"));
$("#batteriesoverview-batterycard-modal").modal("show");
});
function RefreshStatistics()
{
var nextXDays = $("#info-due-batteries").data("next-x-days");
Grocy.Api.Get('batteries',
function(result)
{
var dueCount = 0;
var overdueCount = 0;
var now = moment();
var nextXDaysThreshold = moment().add(nextXDays, "days");
result.forEach(element =>
{ {
var date = moment(element.next_estimated_charge_time); Grocy.Api.Get('batteries/' + batteryId,
if (date.isBefore(now)) function(result)
{ {
overdueCount++; var batteryRow = $('#battery-' + batteryId + '-row');
} var nextXDaysThreshold = moment().add($("#info-due-batteries").data("next-x-days"), "days");
else if (date.isBefore(nextXDaysThreshold)) var now = moment();
{ var nextExecutionTime = moment(result.next_estimated_charge_time);
dueCount++;
} batteryRow.removeClass("table-warning");
}); batteryRow.removeClass("table-danger");
if (nextExecutionTime.isBefore(now))
{
batteryRow.addClass("table-danger");
}
else if (nextExecutionTime.isBefore(nextXDaysThreshold))
{
batteryRow.addClass("table-warning");
}
animateCSS("#battery-" + batteryId + "-row td:not(:first)", "shake");
$('#battery-' + batteryId + '-last-tracked-time').text(trackedTime);
$('#battery-' + batteryId + '-last-tracked-time-timeago').attr('datetime', trackedTime);
if (result.battery.charge_interval_days != 0)
{
$('#battery-' + batteryId + '-next-charge-time').text(result.next_estimated_charge_time);
$('#battery-' + batteryId + '-next-charge-time-timeago').attr('datetime', result.next_estimated_charge_time);
}
Grocy.FrontendHelpers.EndUiBusy();
toastr.success(__t('Tracked charge cycle of battery %1$s on %2$s', batteryName, trackedTime));
RefreshContextualTimeago("#battery-" + batteryId + "-row");
RefreshStatistics();
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
$(document).on("click", ".battery-name-cell", function(e)
{
Grocy.Components.BatteryCard.Refresh($(e.currentTarget).attr("data-battery-id"));
$("#batteriesoverview-batterycard-modal").modal("show");
});
function RefreshStatistics()
{
var nextXDays = $("#info-due-batteries").data("next-x-days");
Grocy.Api.Get('batteries',
function(result)
{
var dueCount = 0;
var overdueCount = 0;
var now = moment();
var nextXDaysThreshold = moment().add(nextXDays, "days");
result.forEach(element =>
{
var date = moment(element.next_estimated_charge_time);
if (date.isBefore(now))
{
overdueCount++;
}
else if (date.isBefore(nextXDaysThreshold))
{
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'));
$("#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)
{
console.error(xhr);
}
);
}
RefreshStatistics();
$("#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'));
},
function(xhr)
{
console.error(xhr);
}
);
} }
RefreshStatistics();

View File

@ -1,5 +1,15 @@
Grocy.Use("numberpicker"); function batteriessettingsView(Grocy, scope = null)
{
var $scope = $;
if (scope != null)
{
$scope = $(scope).find;
}
$("#batteries_due_soon_days").val(Grocy.UserSettings.batteries_due_soon_days); Grocy.Use("numberpicker");
RefreshLocaleNumberInput(); $("#batteries_due_soon_days").val(Grocy.UserSettings.batteries_due_soon_days);
RefreshLocaleNumberInput();
}

View File

@ -1,93 +1,103 @@
import { WindowMessageBag } from '../helpers/messagebag'; function batteryformView(Grocy, scope = null)
Grocy.Use("numberpicker");
Grocy.Use("userfieldsform");
$('#save-battery-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#battery-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
Grocy.FrontendHelpers.BeginUiBusy("battery-form");
if (Grocy.EditMode === 'create') Grocy.Use("numberpicker");
Grocy.Use("userfieldsform");
$('#save-battery-button').on('click', function(e)
{ {
Grocy.Api.Post('objects/batteries', jsonData, e.preventDefault();
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/batteries');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("battery-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/batteries/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/batteries');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("battery-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$('#battery-form input').keyup(function(event) if ($(".combobox-menu-visible").length)
{
Grocy.FrontendHelpers.ValidateForm('battery-form');
});
$('#battery-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('battery-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return;
}
var jsonData = $('#battery-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("battery-form");
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/batteries', jsonData,
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/batteries');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("battery-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
else else
{ {
$('#save-battery-button').click(); Grocy.Api.Put('objects/batteries/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/batteries');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("battery-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
} });
});
Grocy.Components.UserfieldsForm.Load(); $('#battery-form input').keyup(function(event)
$('#name').focus(); {
Grocy.FrontendHelpers.ValidateForm('battery-form'); Grocy.FrontendHelpers.ValidateForm('battery-form');
});
$('#battery-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('battery-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-battery-button').click();
}
}
});
Grocy.Components.UserfieldsForm.Load();
$('#name').focus();
Grocy.FrontendHelpers.ValidateForm('battery-form');
}

View File

@ -1,103 +1,113 @@
Grocy.Use("batterycard"); function batterytrackingView(Grocy, scope = null)
Grocy.Use("datetimepicker");
$('#save-batterytracking-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonForm = $('#batterytracking-form').serializeJSON(); Grocy.Use("batterycard");
Grocy.FrontendHelpers.BeginUiBusy("batterytracking-form"); Grocy.Use("datetimepicker");
Grocy.Api.Get('batteries/' + jsonForm.battery_id, $('#save-batterytracking-button').on('click', function(e)
function(batteryDetails) {
{ e.preventDefault();
Grocy.Api.Post('batteries/' + jsonForm.battery_id + '/charge', { 'tracked_time': $('#tracked_time').find('input').val() },
function(result) if ($(".combobox-menu-visible").length)
{ {
Grocy.FrontendHelpers.EndUiBusy("batterytracking-form"); return;
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>'); }
Grocy.Components.BatteryCard.Refresh($('#battery_id').val());
var jsonForm = $('#batterytracking-form').serializeJSON();
$('#battery_id').val(''); Grocy.FrontendHelpers.BeginUiBusy("batterytracking-form");
$('#battery_id_text_input').focus();
$('#battery_id_text_input').val(''); Grocy.Api.Get('batteries/' + jsonForm.battery_id,
$('#tracked_time').find('input').val(moment().format('YYYY-MM-DD HH:mm:ss')); function(batteryDetails)
$('#tracked_time').find('input').trigger('change'); {
$('#battery_id_text_input').trigger('change'); Grocy.Api.Post('batteries/' + jsonForm.battery_id + '/charge', { 'tracked_time': $('#tracked_time').find('input').val() },
Grocy.FrontendHelpers.ValidateForm('batterytracking-form'); function(result)
}, {
function(xhr) 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>');
Grocy.FrontendHelpers.EndUiBusy("batterytracking-form"); Grocy.Components.BatteryCard.Refresh($('#battery_id').val());
console.error(xhr);
} $('#battery_id').val('');
); $('#battery_id_text_input').focus();
}, $('#battery_id_text_input').val('');
function(xhr) $('#tracked_time').find('input').val(moment().format('YYYY-MM-DD HH:mm:ss'));
{ $('#tracked_time').find('input').trigger('change');
Grocy.FrontendHelpers.EndUiBusy("batterytracking-form"); $('#battery_id_text_input').trigger('change');
console.error(xhr); Grocy.FrontendHelpers.ValidateForm('batterytracking-form');
} },
); function(xhr)
}); {
Grocy.FrontendHelpers.EndUiBusy("batterytracking-form");
$('#battery_id').on('change', function(e) console.error(xhr);
{ }
var input = $('#battery_id_text_input').val().toString(); );
$('#battery_id_text_input').val(input); },
$('#battery_id').data('combobox').refresh(); function(xhr)
{
var batteryId = $(e.target).val(); Grocy.FrontendHelpers.EndUiBusy("batterytracking-form");
if (batteryId) console.error(xhr);
}
);
});
$('#battery_id').on('change', function(e)
{
var input = $('#battery_id_text_input').val().toString();
$('#battery_id_text_input').val(input);
$('#battery_id').data('combobox').refresh();
var batteryId = $(e.target).val();
if (batteryId)
{
Grocy.Components.BatteryCard.Refresh(batteryId);
$('#tracked_time').find('input').focus();
Grocy.FrontendHelpers.ValidateForm('batterytracking-form');
}
});
$('.combobox').combobox({
appendId: '_text_input',
bsVersion: '4'
});
$('#battery_id').val('');
$('#battery_id_text_input').focus();
$('#battery_id_text_input').val('');
$('#battery_id_text_input').trigger('change');
Grocy.Components.DateTimePicker.GetInputElement().trigger('input');
Grocy.FrontendHelpers.ValidateForm('batterytracking-form');
$('#batterytracking-form input').keyup(function(event)
{ {
Grocy.Components.BatteryCard.Refresh(batteryId);
$('#tracked_time').find('input').focus();
Grocy.FrontendHelpers.ValidateForm('batterytracking-form'); Grocy.FrontendHelpers.ValidateForm('batterytracking-form');
} });
});
$('.combobox').combobox({ $('#batterytracking-form input').keydown(function(event)
appendId: '_text_input',
bsVersion: '4'
});
$('#battery_id').val('');
$('#battery_id_text_input').focus();
$('#battery_id_text_input').val('');
$('#battery_id_text_input').trigger('change');
Grocy.Components.DateTimePicker.GetInputElement().trigger('input');
Grocy.FrontendHelpers.ValidateForm('batterytracking-form');
$('#batterytracking-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('batterytracking-form');
});
$('#batterytracking-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{ {
event.preventDefault(); if (event.keyCode === 13) //Enter
if (document.getElementById('batterytracking-form').checkValidity() === false) //There is at least one validation error
{ {
return false; event.preventDefault();
if (document.getElementById('batterytracking-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-batterytracking-button').click();
}
} }
else });
{
$('#save-batterytracking-button').click();
}
}
});
$('#tracked_time').find('input').on('keypress', function(e) $('#tracked_time').find('input').on('keypress', function(e)
{ {
Grocy.FrontendHelpers.ValidateForm('batterytracking-form'); Grocy.FrontendHelpers.ValidateForm('batterytracking-form');
}); });
}

View File

@ -1,92 +1,102 @@
/* global fullcalendarEventSources */ function calendarView(Grocy, scope = null)
{
import { Calendar } from '@fullcalendar/core'; var $scope = $;
import dayGridPlugin from '@fullcalendar/daygrid'; if (scope != null)
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 = {
plugins: [bootstrapPlugin, dayGridPlugin, listPlugin, timeGridPlugin],
themeSystem: "bootstrap",
header: {
left: "dayGridMonth,timeGridWeek,timeGridDay,listWeek",
center: "title",
right: "prev,next"
},
weekNumbers: Grocy.CalendarShowWeekNumbers,
defaultView: ($(window).width() < 768) ? "timeGridDay" : "dayGridMonth",
firstDay: firstDay,
eventLimit: false,
height: "auto",
events: fullcalendarEventSources,
// fullcalendar 4 doesn't translate the default view names (?)
// so we have to supply our own.
views: {
dayGridMonth: { buttonText: __t("Month") },
timeGridWeek: { buttonText: __t("Week") },
timeGridDay: { buttonText: __t("Day") },
listWeek: { buttonText: __t("List") }
},
eventClick: function(info)
{ {
window.location.href = info.link; $scope = $(scope).find;
} }
};
if (__t('fullcalendar_locale').replace(" ", "") !== "" && __t('fullcalendar_locale') != 'x') /* global fullcalendarEventSources */
{
$.getScript(U('/js/locales/fullcalendar-core/' + __t('fullcalendar_locale') + '.js'));
calendarOptions.locale = __t('fullcalendar_locale');
}
var firstDay = null; import { Calendar } from '@fullcalendar/core';
if (!Grocy.CalendarFirstDayOfWeek.isEmpty()) import dayGridPlugin from '@fullcalendar/daygrid';
{ import bootstrapPlugin from '@fullcalendar/bootstrap';
firstDay = parseInt(Grocy.CalendarFirstDayOfWeek); import listPlugin from '@fullcalendar/list';
} import timeGridPlugin from '@fullcalendar/timegrid';
import { QrCodeImgHtml } from "../helpers/qrcode";
var calendar = new Calendar(document.getElementById("calendar"), calendarOptions); import '@fullcalendar/core/main.css';
calendar.render(); import '@fullcalendar/daygrid/main.css';
import '@fullcalendar/timegrid/main.css';
import '@fullcalendar/list/main.css';
import '@fullcalendar/bootstrap/main.css';
$("#ical-button").on("click", function(e) var calendarOptions = {
{ plugins: [bootstrapPlugin, dayGridPlugin, listPlugin, timeGridPlugin],
e.preventDefault(); themeSystem: "bootstrap",
header: {
Grocy.Api.Get('calendar/ical/sharing-link', left: "dayGridMonth,timeGridWeek,timeGridDay,listWeek",
function(result) center: "title",
{ right: "prev,next"
bootbox.alert({
title: __t('Share/Integrate calendar (iCal)'),
message: __t('Use the following (public) URL to share or integrate the calendar in iCal format') + '<input type="text" class="form-control form-control-sm mt-2 easy-link-copy-textbox" value="' + result.url + '"><p class="text-center mt-4">'
+ QrCodeImgHtml(result.url) + "</p>",
closeButton: false
});
}, },
function(xhr) weekNumbers: Grocy.CalendarShowWeekNumbers,
defaultView: ($(window).width() < 768) ? "timeGridDay" : "dayGridMonth",
firstDay: firstDay,
eventLimit: false,
height: "auto",
events: fullcalendarEventSources,
// fullcalendar 4 doesn't translate the default view names (?)
// so we have to supply our own.
views: {
dayGridMonth: { buttonText: __t("Month") },
timeGridWeek: { buttonText: __t("Week") },
timeGridDay: { buttonText: __t("Day") },
listWeek: { buttonText: __t("List") }
},
eventClick: function(info)
{ {
console.error(xhr); window.location.href = info.link;
} }
); };
});
$(window).one("resize", function() if (__t('fullcalendar_locale').replace(" ", "") !== "" && __t('fullcalendar_locale') != 'x')
{
// Automatically switch the calendar to "basicDay" view on small screens
// and to "month" otherwise
if ($(window).width() < 768)
{ {
calendar.changeView("timeGridDay"); $.getScript(U('/js/locales/fullcalendar-core/' + __t('fullcalendar_locale') + '.js'));
calendarOptions.locale = __t('fullcalendar_locale');
} }
else
var firstDay = null;
if (!Grocy.CalendarFirstDayOfWeek.isEmpty())
{ {
calendar.changeView("dayGridMonth"); firstDay = parseInt(Grocy.CalendarFirstDayOfWeek);
} }
});
var calendar = new Calendar(document.getElementById("calendar"), calendarOptions);
calendar.render();
$("#ical-button").on("click", function(e)
{
e.preventDefault();
Grocy.Api.Get('calendar/ical/sharing-link',
function(result)
{
bootbox.alert({
title: __t('Share/Integrate calendar (iCal)'),
message: __t('Use the following (public) URL to share or integrate the calendar in iCal format') + '<input type="text" class="form-control form-control-sm mt-2 easy-link-copy-textbox" value="' + result.url + '"><p class="text-center mt-4">'
+ QrCodeImgHtml(result.url) + "</p>",
closeButton: false
});
},
function(xhr)
{
console.error(xhr);
}
);
});
$(window).one("resize", function()
{
// Automatically switch the calendar to "basicDay" view on small screens
// and to "month" otherwise
if ($(window).width() < 768)
{
calendar.changeView("timeGridDay");
}
else
{
calendar.changeView("dayGridMonth");
}
});
}

View File

@ -1,242 +1,252 @@
Grocy.Use("numberpicker"); function choreformView(Grocy, scope = null)
Grocy.Use("userfieldsform");
$('#save-chore-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#chore-form').serializeJSON(); Grocy.Use("numberpicker");
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_CHORES_ASSIGNMENTS) Grocy.Use("userfieldsform");
$('#save-chore-button').on('click', function(e)
{ {
jsonData.assignment_config = $("#assignment_config").val().join(","); e.preventDefault();
}
Grocy.FrontendHelpers.BeginUiBusy("chore-form"); if ($(".combobox-menu-visible").length)
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/chores', jsonData,
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
Grocy.Api.Post('chores/executions/calculate-next-assignments', { "chore_id": Grocy.EditObjectId },
function(result)
{
window.location.href = U('/chores');
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("chore-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/chores/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
Grocy.Api.Post('chores/executions/calculate-next-assignments', { "chore_id": Grocy.EditObjectId },
function(result)
{
window.location.href = U('/chores');
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("chore-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$('#chore-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('chore-form');
});
$('#chore-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('chore-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return;
}
var jsonData = $('#chore-form').serializeJSON();
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_CHORES_ASSIGNMENTS)
{
jsonData.assignment_config = $("#assignment_config").val().join(",");
}
Grocy.FrontendHelpers.BeginUiBusy("chore-form");
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/chores', jsonData,
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
Grocy.Api.Post('chores/executions/calculate-next-assignments', { "chore_id": Grocy.EditObjectId },
function(result)
{
window.location.href = U('/chores');
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("chore-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
else else
{ {
$('#save-chore-button').click(); Grocy.Api.Put('objects/chores/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
Grocy.Api.Post('chores/executions/calculate-next-assignments', { "chore_id": Grocy.EditObjectId },
function(result)
{
window.location.href = U('/chores');
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("chore-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$('#chore-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('chore-form');
});
$('#chore-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('chore-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-chore-button').click();
}
}
});
var checkboxValues = $("#period_config").val().split(",");
for (var i = 0; i < checkboxValues.length; i++)
{
if (!checkboxValues[i].isEmpty())
{
$("#" + checkboxValues[i]).prop('checked', true);
} }
} }
});
var checkboxValues = $("#period_config").val().split(","); Grocy.Components.UserfieldsForm.Load();
for (var i = 0; i < checkboxValues.length; i++) $('#name').focus();
{ Grocy.FrontendHelpers.ValidateForm('chore-form');
if (!checkboxValues[i].isEmpty())
setTimeout(function()
{ {
$("#" + checkboxValues[i]).prop('checked', true); $(".input-group-chore-period-type").trigger("change");
} $(".input-group-chore-assignment-type").trigger("change");
// Click twice to trigger on-click but not change the actual checked state
$("#consume_product_on_execution").click();
$("#consume_product_on_execution").click();
Grocy.Components.ProductPicker.GetPicker().trigger('change');
}, 100);
$('.input-group-chore-period-type').on('change', function(e)
{
var periodType = $('#period_type').val();
var periodDays = $('#period_days').val();
var periodInterval = $('#period_interval').val();
$(".period-type-input").addClass("d-none");
$(".period-type-" + periodType).removeClass("d-none");
$('#chore-period-type-info').attr("data-original-title", "");
$("#period_config").val("");
if (periodType === 'manually')
{
$('#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')
{
$("label[for='period_days']").text(__t("Period days"));
$("#period_days").attr("min", "0");
$("#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()));
}
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'));
$('#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')
{
$('#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(","));
$('#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')
{
$('#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"));
$("#period_days").attr("min", "1");
$("#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()));
}
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'));
$('#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');
});
$('.input-group-chore-assignment-type').on('change', function(e)
{
var assignmentType = $('#assignment_type').val();
$('#chore-period-assignment-info').text("");
$("#assignment_config").removeAttr("required");
$("#assignment_config").attr("disabled", "");
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'));
}
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'));
$("#assignment_config").attr("required", "");
$("#assignment_config").removeAttr("disabled");
}
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'));
$("#assignment_config").attr("required", "");
$("#assignment_config").removeAttr("disabled");
}
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'));
$("#assignment_config").attr("required", "");
$("#assignment_config").removeAttr("disabled");
}
Grocy.FrontendHelpers.ValidateForm('chore-form');
});
$("#consume_product_on_execution").on("click", function()
{
if (this.checked)
{
Grocy.Components.ProductPicker.Enable();
$("#product_amount").removeAttr("disabled");
}
else
{
Grocy.Components.ProductPicker.Disable();
$("#product_amount").attr("disabled", "");
}
Grocy.FrontendHelpers.ValidateForm("chore-form");
});
Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{
var productId = $(e.target).val();
if (productId)
{
Grocy.Api.Get('stock/products/' + productId,
function(productDetails)
{
$('#amount_qu_unit').text(productDetails.quantity_unit_stock.name);
},
function(xhr)
{
console.error(xhr);
}
);
}
});
} }
Grocy.Components.UserfieldsForm.Load();
$('#name').focus();
Grocy.FrontendHelpers.ValidateForm('chore-form');
setTimeout(function()
{
$(".input-group-chore-period-type").trigger("change");
$(".input-group-chore-assignment-type").trigger("change");
// Click twice to trigger on-click but not change the actual checked state
$("#consume_product_on_execution").click();
$("#consume_product_on_execution").click();
Grocy.Components.ProductPicker.GetPicker().trigger('change');
}, 100);
$('.input-group-chore-period-type').on('change', function(e)
{
var periodType = $('#period_type').val();
var periodDays = $('#period_days').val();
var periodInterval = $('#period_interval').val();
$(".period-type-input").addClass("d-none");
$(".period-type-" + periodType).removeClass("d-none");
$('#chore-period-type-info').attr("data-original-title", "");
$("#period_config").val("");
if (periodType === 'manually')
{
$('#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')
{
$("label[for='period_days']").text(__t("Period days"));
$("#period_days").attr("min", "0");
$("#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()));
}
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'));
$('#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')
{
$('#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(","));
$('#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')
{
$('#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"));
$("#period_days").attr("min", "1");
$("#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()));
}
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'));
$('#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');
});
$('.input-group-chore-assignment-type').on('change', function(e)
{
var assignmentType = $('#assignment_type').val();
$('#chore-period-assignment-info').text("");
$("#assignment_config").removeAttr("required");
$("#assignment_config").attr("disabled", "");
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'));
}
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'));
$("#assignment_config").attr("required", "");
$("#assignment_config").removeAttr("disabled");
}
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'));
$("#assignment_config").attr("required", "");
$("#assignment_config").removeAttr("disabled");
}
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'));
$("#assignment_config").attr("required", "");
$("#assignment_config").removeAttr("disabled");
}
Grocy.FrontendHelpers.ValidateForm('chore-form');
});
$("#consume_product_on_execution").on("click", function()
{
if (this.checked)
{
Grocy.Components.ProductPicker.Enable();
$("#product_amount").removeAttr("disabled");
}
else
{
Grocy.Components.ProductPicker.Disable();
$("#product_amount").attr("disabled", "");
}
Grocy.FrontendHelpers.ValidateForm("chore-form");
});
Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{
var productId = $(e.target).val();
if (productId)
{
Grocy.Api.Get('stock/products/' + productId,
function(productDetails)
{
$('#amount_qu_unit').text(productDetails.quantity_unit_stock.name);
},
function(xhr)
{
console.error(xhr);
}
);
}
});

View File

@ -1,40 +1,50 @@
var choresTable = $('#chores-table').DataTable({ function choresView(Grocy, scope = null)
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#chores-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(choresTable, null, function()
{ {
$("#search").val(""); var $scope = $;
choresTable.search("").draw(); if (scope != null)
$("#show-disabled").prop('checked', false);
});
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete chore "%s"?',
'.core-delete-button',
'data-chore-name',
'data-chore-id',
'objects/chores/',
'/chroes'
);
$("#show-disabled").change(function()
{
if (this.checked)
{ {
window.location.href = U('/chores?include_disabled'); $scope = $(scope).find;
}
var choresTable = $('#chores-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#chores-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(choresTable, null, function()
{
$("#search").val("");
choresTable.search("").draw();
$("#show-disabled").prop('checked', false);
});
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete chore "%s"?',
'.core-delete-button',
'data-chore-name',
'data-chore-id',
'objects/chores/',
'/chroes'
);
$("#show-disabled").change(function()
{
if (this.checked)
{
window.location.href = U('/chores?include_disabled');
}
else
{
window.location.href = U('/chores');
}
});
if (GetUriParam('include_disabled'))
{
$("#show-disabled").prop('checked', true);
} }
else
{
window.location.href = U('/chores');
}
});
if (GetUriParam('include_disabled'))
{
$("#show-disabled").prop('checked', true);
} }

View File

@ -1,40 +1,50 @@
var choresJournalTable = $('#chores-journal-table').DataTable({ function choresjournalView(Grocy, scope = null)
'paginate': true,
'order': [[2, 'desc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#chores-journal-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(choresJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#chore-filter", 1, choresJournalTable);
if (typeof GetUriParam("chore") !== "undefined")
{ {
$("#chore-filter").val(GetUriParam("chore")); var $scope = $;
$("#chore-filter").trigger("change"); if (scope != null)
{
$scope = $(scope).find;
}
var choresJournalTable = $('#chores-journal-table').DataTable({
'paginate': true,
'order': [[2, 'desc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#chores-journal-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(choresJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#chore-filter", 1, choresJournalTable);
if (typeof GetUriParam("chore") !== "undefined")
{
$("#chore-filter").val(GetUriParam("chore"));
$("#chore-filter").trigger("change");
}
$(document).on('click', '.undo-chore-execution-button', function(e)
{
e.preventDefault();
var element = $(e.currentTarget);
var executionId = element.attr('data-execution-id');
Grocy.Api.Post('chores/executions/' + executionId.toString() + '/undo', {},
function(result)
{
element.closest("tr").addClass("text-muted");
element.parent().siblings().find("span.name-anchor").addClass("text-strike-through").after("<br>" + __t("Undone on") + " " + moment().format("YYYY-MM-DD HH:mm:ss") + " <time class='timeago timeago-contextual' datetime='" + moment().format("YYYY-MM-DD HH:mm:ss") + "'></time>");
element.closest(".undo-stock-booking-button").addClass("disabled");
RefreshContextualTimeago("#chore-execution-" + executionId + "-row");
toastr.success(__t("Chore execution successfully undone"));
},
function(xhr)
{
console.error(xhr);
}
);
});
} }
$(document).on('click', '.undo-chore-execution-button', function(e)
{
e.preventDefault();
var element = $(e.currentTarget);
var executionId = element.attr('data-execution-id');
Grocy.Api.Post('chores/executions/' + executionId.toString() + '/undo', {},
function(result)
{
element.closest("tr").addClass("text-muted");
element.parent().siblings().find("span.name-anchor").addClass("text-strike-through").after("<br>" + __t("Undone on") + " " + moment().format("YYYY-MM-DD HH:mm:ss") + " <time class='timeago timeago-contextual' datetime='" + moment().format("YYYY-MM-DD HH:mm:ss") + "'></time>");
element.closest(".undo-stock-booking-button").addClass("disabled");
RefreshContextualTimeago("#chore-execution-" + executionId + "-row");
toastr.success(__t("Chore execution successfully undone"));
},
function(xhr)
{
console.error(xhr);
}
);
});

View File

@ -1,182 +1,192 @@
Grocy.Use("chorecard"); function choresoverviewView(Grocy, scope = null)
var choresOverviewTable = $('#chores-overview-table').DataTable({
'order': [[2, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ "type": "html", "targets": 5 },
{ "type": "html", "targets": 2 },
{ "type": "html", "targets": 3 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#chores-overview-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(choresOverviewTable);
Grocy.FrontendHelpers.MakeValueFilter("status", 5, choresOverviewTable);
Grocy.FrontendHelpers.MakeValueFilter("user", 6, choresOverviewTable, "");
$("#user-filter").on("change", function()
{ {
var user = $(this).val(); var $scope = $;
if (user !== null && !user.isEmpty()) if (scope != null)
{ {
UpdateUriParam("user", $("#user-filter option:selected").data("user-id")); $scope = $(scope).find;
} }
else
Grocy.Use("chorecard");
var choresOverviewTable = $('#chores-overview-table').DataTable({
'order': [[2, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ "type": "html", "targets": 5 },
{ "type": "html", "targets": 2 },
{ "type": "html", "targets": 3 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#chores-overview-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(choresOverviewTable);
Grocy.FrontendHelpers.MakeValueFilter("status", 5, choresOverviewTable);
Grocy.FrontendHelpers.MakeValueFilter("user", 6, choresOverviewTable, "");
$("#user-filter").on("change", function()
{ {
RemoveUriParam("user") var user = $(this).val();
} if (user !== null && !user.isEmpty())
});
$(document).on('click', '.track-chore-button', function(e)
{
e.preventDefault();
// Remove the focus from the current button
// to prevent that the tooltip stays until clicked anywhere else
document.activeElement.blur();
Grocy.FrontendHelpers.BeginUiBusy();
var choreId = $(e.currentTarget).attr('data-chore-id');
var choreName = $(e.currentTarget).attr('data-chore-name');
Grocy.Api.Get('objects/chores/' + choreId,
function(chore)
{ {
var trackedTime = moment().format('YYYY-MM-DD HH:mm:ss'); UpdateUriParam("user", $("#user-filter option:selected").data("user-id"));
if (chore.track_date_only == 1) }
else
{
RemoveUriParam("user")
}
});
$(document).on('click', '.track-chore-button', function(e)
{
e.preventDefault();
// Remove the focus from the current button
// to prevent that the tooltip stays until clicked anywhere else
document.activeElement.blur();
Grocy.FrontendHelpers.BeginUiBusy();
var choreId = $(e.currentTarget).attr('data-chore-id');
var choreName = $(e.currentTarget).attr('data-chore-name');
Grocy.Api.Get('objects/chores/' + choreId,
function(chore)
{ {
trackedTime = moment().format('YYYY-MM-DD'); var trackedTime = moment().format('YYYY-MM-DD HH:mm:ss');
if (chore.track_date_only == 1)
{
trackedTime = moment().format('YYYY-MM-DD');
}
Grocy.Api.Post('chores/' + choreId + '/execute', { 'tracked_time': trackedTime },
function()
{
Grocy.Api.Get('chores/' + choreId,
function(result)
{
var choreRow = $('#chore-' + choreId + '-row');
var nextXDaysThreshold = moment().add($("#info-due-chores").data("next-x-days"), "days");
var now = moment();
var nextExecutionTime = moment(result.next_estimated_execution_time);
choreRow.removeClass("table-warning");
choreRow.removeClass("table-danger");
$('#chore-' + choreId + '-due-filter-column').html("");
if (nextExecutionTime.isBefore(now))
{
choreRow.addClass("table-danger");
$('#chore-' + choreId + '-due-filter-column').html("overdue");
}
else if (nextExecutionTime.isBefore(nextXDaysThreshold))
{
choreRow.addClass("table-warning");
$('#chore-' + choreId + '-due-filter-column').html("duesoon");
}
animateCSS("#chore-" + choreId + "-row td:not(:first)", "shake");
$('#chore-' + choreId + '-last-tracked-time').text(trackedTime);
$('#chore-' + choreId + '-last-tracked-time-timeago').attr('datetime', trackedTime);
if (result.chore.period_type == "dynamic-regular")
{
$('#chore-' + choreId + '-next-execution-time').text(result.next_estimated_execution_time);
$('#chore-' + choreId + '-next-execution-time-timeago').attr('datetime', result.next_estimated_execution_time);
}
if (result.chore.next_execution_assigned_to_user_id != null)
{
$('#chore-' + choreId + '-next-execution-assigned-user').text(result.next_execution_assigned_user.display_name);
}
Grocy.FrontendHelpers.EndUiBusy();
toastr.success(__t('Tracked execution of chore %1$s on %2$s', choreName, trackedTime));
RefreshStatistics();
// Delay due to delayed/animated set of new timestamps above
setTimeout(function()
{
RefreshContextualTimeago("#chore-" + choreId + "-row");
// Refresh the DataTable to re-apply filters
choresOverviewTable.rows().invalidate().draw(false);
$(".input-group-filter").trigger("change");
}, 550);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("choretracking-form");
console.error(xhr);
} }
);
});
Grocy.Api.Post('chores/' + choreId + '/execute', { 'tracked_time': trackedTime }, $(document).on("click", ".chore-name-cell", function(e)
function() {
{ Grocy.Components.ChoreCard.Refresh($(e.currentTarget).attr("data-chore-id"));
Grocy.Api.Get('chores/' + choreId, $("#choresoverview-chorecard-modal").modal("show");
function(result) });
{
var choreRow = $('#chore-' + choreId + '-row');
var nextXDaysThreshold = moment().add($("#info-due-chores").data("next-x-days"), "days");
var now = moment();
var nextExecutionTime = moment(result.next_estimated_execution_time);
choreRow.removeClass("table-warning"); function RefreshStatistics()
choreRow.removeClass("table-danger"); {
$('#chore-' + choreId + '-due-filter-column').html(""); var nextXDays = $("#info-due-chores").data("next-x-days");
if (nextExecutionTime.isBefore(now)) Grocy.Api.Get('chores',
{ function(result)
choreRow.addClass("table-danger");
$('#chore-' + choreId + '-due-filter-column').html("overdue");
}
else if (nextExecutionTime.isBefore(nextXDaysThreshold))
{
choreRow.addClass("table-warning");
$('#chore-' + choreId + '-due-filter-column').html("duesoon");
}
animateCSS("#chore-" + choreId + "-row td:not(:first)", "shake");
$('#chore-' + choreId + '-last-tracked-time').text(trackedTime);
$('#chore-' + choreId + '-last-tracked-time-timeago').attr('datetime', trackedTime);
if (result.chore.period_type == "dynamic-regular")
{
$('#chore-' + choreId + '-next-execution-time').text(result.next_estimated_execution_time);
$('#chore-' + choreId + '-next-execution-time-timeago').attr('datetime', result.next_estimated_execution_time);
}
if (result.chore.next_execution_assigned_to_user_id != null)
{
$('#chore-' + choreId + '-next-execution-assigned-user').text(result.next_execution_assigned_user.display_name);
}
Grocy.FrontendHelpers.EndUiBusy();
toastr.success(__t('Tracked execution of chore %1$s on %2$s', choreName, trackedTime));
RefreshStatistics();
// Delay due to delayed/animated set of new timestamps above
setTimeout(function()
{
RefreshContextualTimeago("#chore-" + choreId + "-row");
// Refresh the DataTable to re-apply filters
choresOverviewTable.rows().invalidate().draw(false);
$(".input-group-filter").trigger("change");
}, 550);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("choretracking-form");
console.error(xhr);
}
);
});
$(document).on("click", ".chore-name-cell", function(e)
{
Grocy.Components.ChoreCard.Refresh($(e.currentTarget).attr("data-chore-id"));
$("#choresoverview-chorecard-modal").modal("show");
});
function RefreshStatistics()
{
var nextXDays = $("#info-due-chores").data("next-x-days");
Grocy.Api.Get('chores',
function(result)
{
var dueCount = 0;
var overdueCount = 0;
var assignedToMeCount = 0;
var now = moment();
var nextXDaysThreshold = moment().add(nextXDays, "days");
result.forEach(element =>
{ {
var date = moment(element.next_estimated_execution_time); var dueCount = 0;
if (date.isBefore(now)) var overdueCount = 0;
var assignedToMeCount = 0;
var now = moment();
var nextXDaysThreshold = moment().add(nextXDays, "days");
result.forEach(element =>
{ {
overdueCount++; var date = moment(element.next_estimated_execution_time);
} if (date.isBefore(now))
else if (date.isBefore(nextXDaysThreshold)) {
{ overdueCount++;
dueCount++; }
} else if (date.isBefore(nextXDaysThreshold))
{
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'));
$("#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'));
},
function(xhr)
{
console.error(xhr);
}
);
}
if (GetUriParam("user") !== undefined)
{
$("#user-filter").val("xx" + GetUriParam("user") + "xx");
$("#user-filter").trigger("change");
}
RefreshStatistics();
$("#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'));
$("#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)
{
console.error(xhr);
}
);
} }
if (GetUriParam("user") !== undefined)
{
$("#user-filter").val("xx" + GetUriParam("user") + "xx");
$("#user-filter").trigger("change");
}
RefreshStatistics();

View File

@ -1,5 +1,15 @@
Grocy.Use("numberpicker"); function choressettingsView(Grocy, scope = null)
{
var $scope = $;
if (scope != null)
{
$scope = $(scope).find;
}
$("#chores_due_soon_days").val(Grocy.UserSettings.chores_due_soon_days); Grocy.Use("numberpicker");
RefreshLocaleNumberInput(); $("#chores_due_soon_days").val(Grocy.UserSettings.chores_due_soon_days);
RefreshLocaleNumberInput();
}

View File

@ -1,119 +1,129 @@
Grocy.Use("chorecard"); function choretrackingView(Grocy, scope = null)
Grocy.Use("datetimepicker");
Grocy.Use("userpicker");
$('#save-choretracking-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonForm = $('#choretracking-form').serializeJSON(); Grocy.Use("chorecard");
Grocy.FrontendHelpers.BeginUiBusy("choretracking-form"); Grocy.Use("datetimepicker");
Grocy.Use("userpicker");
Grocy.Api.Get('chores/' + jsonForm.chore_id, $('#save-choretracking-button').on('click', function(e)
function(choreDetails)
{
Grocy.Api.Post('chores/' + jsonForm.chore_id + '/execute', { 'tracked_time': Grocy.Components.DateTimePicker.GetValue(), 'done_by': $("#user_id").val() },
function(result)
{
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>');
Grocy.Components.ChoreCard.Refresh($('#chore_id').val());
$('#chore_id').val('');
$('#chore_id_text_input').focus();
$('#chore_id_text_input').val('');
Grocy.Components.DateTimePicker.SetValue(moment().format('YYYY-MM-DD HH:mm:ss'));
$('#chore_id_text_input').trigger('change');
Grocy.FrontendHelpers.ValidateForm('choretracking-form');
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("choretracking-form");
console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("choretracking-form");
console.error(xhr);
}
);
});
$('#chore_id').on('change', function(e)
{
var input = $('#chore_id_text_input').val().toString();
$('#chore_id_text_input').val(input);
$('#chore_id').data('combobox').refresh();
var choreId = $(e.target).val();
if (choreId)
{ {
Grocy.Api.Get('objects/chores/' + choreId, e.preventDefault();
function(chore)
if ($(".combobox-menu-visible").length)
{
return;
}
var jsonForm = $('#choretracking-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("choretracking-form");
Grocy.Api.Get('chores/' + jsonForm.chore_id,
function(choreDetails)
{ {
if (chore.track_date_only == 1) Grocy.Api.Post('chores/' + jsonForm.chore_id + '/execute', { 'tracked_time': Grocy.Components.DateTimePicker.GetValue(), 'done_by': $("#user_id").val() },
{ function(result)
Grocy.Components.DateTimePicker.ChangeFormat("YYYY-MM-DD"); {
Grocy.Components.DateTimePicker.SetValue(moment().format("YYYY-MM-DD")); 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>');
else Grocy.Components.ChoreCard.Refresh($('#chore_id').val());
{
Grocy.Components.DateTimePicker.ChangeFormat("YYYY-MM-DD HH:mm:ss"); $('#chore_id').val('');
Grocy.Components.DateTimePicker.SetValue(moment().format("YYYY-MM-DD HH:mm:ss")); $('#chore_id_text_input').focus();
} $('#chore_id_text_input').val('');
Grocy.Components.DateTimePicker.SetValue(moment().format('YYYY-MM-DD HH:mm:ss'));
$('#chore_id_text_input').trigger('change');
Grocy.FrontendHelpers.ValidateForm('choretracking-form');
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("choretracking-form");
console.error(xhr);
}
);
}, },
function(xhr) function(xhr)
{ {
Grocy.FrontendHelpers.EndUiBusy("choretracking-form");
console.error(xhr); console.error(xhr);
} }
); );
});
Grocy.Components.ChoreCard.Refresh(choreId); $('#chore_id').on('change', function(e)
Grocy.Components.DateTimePicker.GetInputElement().focus();
Grocy.FrontendHelpers.ValidateForm('choretracking-form');
}
});
$('.combobox').combobox({
appendId: '_text_input',
bsVersion: '4'
});
$('#chore_id_text_input').focus();
$('#chore_id_text_input').trigger('change');
Grocy.Components.DateTimePicker.GetInputElement().trigger('input');
Grocy.FrontendHelpers.ValidateForm('choretracking-form');
$('#choretracking-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('choretracking-form');
});
$('#choretracking-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{ {
event.preventDefault(); var input = $('#chore_id_text_input').val().toString();
$('#chore_id_text_input').val(input);
$('#chore_id').data('combobox').refresh();
if (document.getElementById('choretracking-form').checkValidity() === false) //There is at least one validation error var choreId = $(e.target).val();
if (choreId)
{ {
return false; Grocy.Api.Get('objects/chores/' + choreId,
} function(chore)
else {
{ if (chore.track_date_only == 1)
$('#save-choretracking-button').click(); {
} Grocy.Components.DateTimePicker.ChangeFormat("YYYY-MM-DD");
} Grocy.Components.DateTimePicker.SetValue(moment().format("YYYY-MM-DD"));
}); }
else
{
Grocy.Components.DateTimePicker.ChangeFormat("YYYY-MM-DD HH:mm:ss");
Grocy.Components.DateTimePicker.SetValue(moment().format("YYYY-MM-DD HH:mm:ss"));
}
},
function(xhr)
{
console.error(xhr);
}
);
Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e) Grocy.Components.ChoreCard.Refresh(choreId);
{ Grocy.Components.DateTimePicker.GetInputElement().focus();
Grocy.FrontendHelpers.ValidateForm('choretracking-form');
}
});
$('.combobox').combobox({
appendId: '_text_input',
bsVersion: '4'
});
$('#chore_id_text_input').focus();
$('#chore_id_text_input').trigger('change');
Grocy.Components.DateTimePicker.GetInputElement().trigger('input');
Grocy.FrontendHelpers.ValidateForm('choretracking-form'); Grocy.FrontendHelpers.ValidateForm('choretracking-form');
});
$('#choretracking-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('choretracking-form');
});
$('#choretracking-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('choretracking-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-choretracking-button').click();
}
}
});
Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e)
{
Grocy.FrontendHelpers.ValidateForm('choretracking-form');
});
}

File diff suppressed because it is too large Load Diff

View File

@ -1,92 +1,102 @@
import { ResizeResponsiveEmbeds } from "../helpers/embeds"; function equipmentView(Grocy, scope = null)
var equipmentTable = $('#equipment-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs),
select: {
style: 'single',
selector: 'tr td:not(:first-child)'
},
'initComplete': function()
{
this.api().row({ order: 'current' }, 0).select();
DisplayEquipment($('#equipment-table tbody tr:eq(0)').data("equipment-id"));
}
});
$('#equipment-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(equipmentTable);
equipmentTable.on('select', function(e, dt, type, indexes)
{ {
if (type === 'row') var $scope = $;
if (scope != null)
{ {
var selectedEquipmentId = $(equipmentTable.row(indexes[0]).node()).data("equipment-id"); $scope = $(scope).find;
DisplayEquipment(selectedEquipmentId)
} }
});
function DisplayEquipment(id) import { ResizeResponsiveEmbeds } from "../helpers/embeds";
{
Grocy.Api.Get('objects/equipment/' + id,
function(equipmentItem)
{
$(".selected-equipment-name").text(equipmentItem.name);
$("#description-tab-content").html(equipmentItem.description);
$(".equipment-edit-button").attr("href", U("/equipment/" + equipmentItem.id.toString()));
if (equipmentItem.instruction_manual_file_name !== null && !equipmentItem.instruction_manual_file_name.isEmpty()) var equipmentTable = $('#equipment-table').DataTable({
{ 'order': [[1, 'asc']],
var pdfUrl = U('/api/files/equipmentmanuals/' + btoa(equipmentItem.instruction_manual_file_name)); 'columnDefs': [
$("#selected-equipment-instruction-manual").attr("src", pdfUrl); { 'orderable': false, 'targets': 0 },
$("#selectedEquipmentInstructionManualDownloadButton").attr("href", pdfUrl); { 'searchable': false, "targets": 0 }
$("#selected-equipment-instruction-manual").removeClass("d-none"); ].concat($.fn.dataTable.defaults.columnDefs),
$("#selectedEquipmentInstructionManualDownloadButton").removeClass("d-none"); select: {
$("#selected-equipment-has-no-instruction-manual-hint").addClass("d-none"); style: 'single',
selector: 'tr td:not(:first-child)'
$("a[href='#instruction-manual-tab']").tab("show");
ResizeResponsiveEmbeds();
}
else
{
$("#selected-equipment-instruction-manual").addClass("d-none");
$("#selectedEquipmentInstructionManualDownloadButton").addClass("d-none");
$("#selected-equipment-has-no-instruction-manual-hint").removeClass("d-none");
$("a[href='#description-tab']").tab("show");
}
}, },
function(xhr) 'initComplete': function()
{ {
console.error(xhr); this.api().row({ order: 'current' }, 0).select();
DisplayEquipment($('#equipment-table tbody tr:eq(0)').data("equipment-id"));
} }
});
$('#equipment-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(equipmentTable);
equipmentTable.on('select', function(e, dt, type, indexes)
{
if (type === 'row')
{
var selectedEquipmentId = $(equipmentTable.row(indexes[0]).node()).data("equipment-id");
DisplayEquipment(selectedEquipmentId)
}
});
function DisplayEquipment(id)
{
Grocy.Api.Get('objects/equipment/' + id,
function(equipmentItem)
{
$(".selected-equipment-name").text(equipmentItem.name);
$("#description-tab-content").html(equipmentItem.description);
$(".equipment-edit-button").attr("href", U("/equipment/" + equipmentItem.id.toString()));
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));
$("#selected-equipment-instruction-manual").attr("src", pdfUrl);
$("#selectedEquipmentInstructionManualDownloadButton").attr("href", pdfUrl);
$("#selected-equipment-instruction-manual").removeClass("d-none");
$("#selectedEquipmentInstructionManualDownloadButton").removeClass("d-none");
$("#selected-equipment-has-no-instruction-manual-hint").addClass("d-none");
$("a[href='#instruction-manual-tab']").tab("show");
ResizeResponsiveEmbeds();
}
else
{
$("#selected-equipment-instruction-manual").addClass("d-none");
$("#selectedEquipmentInstructionManualDownloadButton").addClass("d-none");
$("#selected-equipment-has-no-instruction-manual-hint").removeClass("d-none");
$("a[href='#description-tab']").tab("show");
}
},
function(xhr)
{
console.error(xhr);
}
);
}
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete equipment "%s"?',
'.equipment-delete-button',
'data-equipment-name',
'data-equipment-id',
'objects/equipment/',
'/equipment'
); );
$("#selectedEquipmentInstructionManualToggleFullscreenButton").on('click', function(e)
{
$("#selectedEquipmentInstructionManualCard").toggleClass("fullscreen");
$("#selectedEquipmentInstructionManualCard .card-header").toggleClass("fixed-top");
$("#selectedEquipmentInstructionManualCard .card-body").toggleClass("mt-5");
$("body").toggleClass("fullscreen-card");
ResizeResponsiveEmbeds(true);
});
$("#selectedEquipmentDescriptionToggleFullscreenButton").on('click', function(e)
{
$("#selectedEquipmentDescriptionCard").toggleClass("fullscreen");
$("#selectedEquipmentDescriptionCard .card-header").toggleClass("fixed-top");
$("#selectedEquipmentDescriptionCard .card-body").toggleClass("mt-5");
$("body").toggleClass("fullscreen-card");
});
} }
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete equipment "%s"?',
'.equipment-delete-button',
'data-equipment-name',
'data-equipment-id',
'objects/equipment/',
'/equipment'
);
$("#selectedEquipmentInstructionManualToggleFullscreenButton").on('click', function(e)
{
$("#selectedEquipmentInstructionManualCard").toggleClass("fullscreen");
$("#selectedEquipmentInstructionManualCard .card-header").toggleClass("fixed-top");
$("#selectedEquipmentInstructionManualCard .card-body").toggleClass("mt-5");
$("body").toggleClass("fullscreen-card");
ResizeResponsiveEmbeds(true);
});
$("#selectedEquipmentDescriptionToggleFullscreenButton").on('click', function(e)
{
$("#selectedEquipmentDescriptionCard").toggleClass("fullscreen");
$("#selectedEquipmentDescriptionCard .card-header").toggleClass("fixed-top");
$("#selectedEquipmentDescriptionCard .card-body").toggleClass("mt-5");
$("body").toggleClass("fullscreen-card");
});

View File

@ -1,75 +1,67 @@
import { RandomString } from '../helpers/extensions'; function equipmentformView(Grocy, scope = null)
import { ResizeResponsiveEmbeds } from '../helpers/embeds';
Grocy.Use("userfieldsform");
$('#save-equipment-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#equipment-form').serializeJSON(); import { RandomString } from '../helpers/extensions';
Grocy.FrontendHelpers.BeginUiBusy("equipment-form"); import { ResizeResponsiveEmbeds } from '../helpers/embeds';
if ($("#instruction-manual")[0].files.length > 0) Grocy.Use("userfieldsform");
{
var someRandomStuff = RandomString();
jsonData.instruction_manual_file_name = someRandomStuff + $("#instruction-manual")[0].files[0].name;
}
if (Grocy.DeleteInstructionManualOnSave) $('#save-equipment-button').on('click', function(e)
{ {
jsonData.instruction_manual_file_name = null; e.preventDefault();
}
if ($(".combobox-menu-visible").length)
{
return;
}
var jsonData = $('#equipment-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("equipment-form");
if ($("#instruction-manual")[0].files.length > 0)
{
var someRandomStuff = RandomString();
jsonData.instruction_manual_file_name = someRandomStuff + $("#instruction-manual")[0].files[0].name;
}
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/equipment', jsonData,
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
// https://eslint.org/docs/rules/no-prototype-builtins
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,
function(result)
{
window.location.href = U('/equipment');
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("equipment-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
window.location.href = U('/equipment');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("equipment-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
if (Grocy.DeleteInstructionManualOnSave) if (Grocy.DeleteInstructionManualOnSave)
{ {
Grocy.Api.DeleteFile(Grocy.InstructionManualFileNameName, 'equipmentmanuals', {}, jsonData.instruction_manual_file_name = null;
}
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/equipment', jsonData,
function(result) function(result)
{ {
// Nothing to do Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
// https://eslint.org/docs/rules/no-prototype-builtins
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,
function(result)
{
window.location.href = U('/equipment');
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("equipment-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
window.location.href = U('/equipment');
}
});
}, },
function(xhr) function(xhr)
{ {
@ -78,84 +70,102 @@ $('#save-equipment-button').on('click', function(e)
} }
); );
} }
Grocy.Api.Put('objects/equipment/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
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,
function(result)
{
window.location.href = U('/equipment');
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("equipment-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
window.location.href = U('/equipment');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("equipment-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$('#equipment-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('equipment-form');
});
$('#equipment-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('equipment-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else else
{ {
$('#save-equipment-button').click(); if (Grocy.DeleteInstructionManualOnSave)
{
Grocy.Api.DeleteFile(Grocy.InstructionManualFileNameName, 'equipmentmanuals', {},
function(result)
{
// Nothing to do
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("equipment-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
Grocy.Api.Put('objects/equipment/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
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,
function(result)
{
window.location.href = U('/equipment');
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("equipment-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
window.location.href = U('/equipment');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("equipment-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
} });
});
Grocy.DeleteInstructionManualOnSave = false; $('#equipment-form input').keyup(function(event)
$('#delete-current-instruction-manual-button').on('click', function(e) {
{ Grocy.FrontendHelpers.ValidateForm('equipment-form');
Grocy.DeleteInstructionManualOnSave = true; });
$("#current-equipment-instruction-manual").addClass("d-none");
$("#delete-current-instruction-manual-on-save-hint").removeClass("d-none");
$("#delete-current-instruction-manual-button").addClass("disabled");
$("#instruction-manual-label").addClass("d-none");
$("#instruction-manual-label-none").removeClass("d-none");
});
ResizeResponsiveEmbeds();
Grocy.Components.UserfieldsForm.Load(); $('#equipment-form input').keydown(function(event)
$('#name').focus(); {
Grocy.FrontendHelpers.ValidateForm('equipment-form'); if (event.keyCode === 13) //Enter
{
event.preventDefault();
$("#instruction-manual").on("change", function(e) if (document.getElementById('equipment-form').checkValidity() === false) //There is at least one validation error
{ {
$("#instruction-manual-label").removeClass("d-none"); return false;
$("#instruction-manual-label-none").addClass("d-none"); }
$("#delete-current-instruction-manual-on-save-hint").addClass("d-none"); else
$("#current-instruction-manuale").addClass("d-none"); {
Grocy.DeleteProductPictureOnSave = false; $('#save-equipment-button').click();
}); }
}
});
Grocy.DeleteInstructionManualOnSave = false;
$('#delete-current-instruction-manual-button').on('click', function(e)
{
Grocy.DeleteInstructionManualOnSave = true;
$("#current-equipment-instruction-manual").addClass("d-none");
$("#delete-current-instruction-manual-on-save-hint").removeClass("d-none");
$("#delete-current-instruction-manual-button").addClass("disabled");
$("#instruction-manual-label").addClass("d-none");
$("#instruction-manual-label-none").removeClass("d-none");
});
ResizeResponsiveEmbeds();
Grocy.Components.UserfieldsForm.Load();
$('#name').focus();
Grocy.FrontendHelpers.ValidateForm('equipment-form');
$("#instruction-manual").on("change", function(e)
{
$("#instruction-manual-label").removeClass("d-none");
$("#instruction-manual-label-none").addClass("d-none");
$("#delete-current-instruction-manual-on-save-hint").addClass("d-none");
$("#current-instruction-manuale").addClass("d-none");
Grocy.DeleteProductPictureOnSave = false;
});
}

View File

@ -1,376 +1,386 @@
import { WindowMessageBag } from '../helpers/messagebag'; function inventoryView(Grocy, scope = null)
Grocy.Use("datetimepicker");
if (Grocy.UserSettings.show_purchased_date_on_purchase)
{ {
Grocy.Use("datetimepicker2"); var $scope = $;
} if (scope != null)
Grocy.Use("locationpicker");
Grocy.Use("numberpicker");
Grocy.Use("productpicker");
Grocy.Use("productamountpicker");
Grocy.Use("productcard");
Grocy.Use("shoppinglocationpicker");
$('#save-inventory-button').on('click', function(e)
{
e.preventDefault();
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonForm = $('#inventory-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
Grocy.FrontendHelpers.BeginUiBusy("inventory-form");
Grocy.Api.Get('stock/products/' + jsonForm.product_id, Grocy.Use("datetimepicker");
function(productDetails) if (Grocy.UserSettings.show_purchased_date_on_purchase)
{
Grocy.Use("datetimepicker2");
}
Grocy.Use("locationpicker");
Grocy.Use("numberpicker");
Grocy.Use("productpicker");
Grocy.Use("productamountpicker");
Grocy.Use("productcard");
Grocy.Use("shoppinglocationpicker");
$('#save-inventory-button').on('click', function(e)
{
e.preventDefault();
if ($(".combobox-menu-visible").length)
{ {
var price = ""; return;
if (!jsonForm.price.toString().isEmpty()) }
{
price = parseFloat(jsonForm.price).toFixed(Grocy.UserSettings.stock_decimal_places_prices);
}
var jsonData = {}; var jsonForm = $('#inventory-form').serializeJSON();
jsonData.new_amount = jsonForm.amount; Grocy.FrontendHelpers.BeginUiBusy("inventory-form");
jsonData.best_before_date = Grocy.Components.DateTimePicker.GetValue();
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{
jsonData.shopping_location_id = Grocy.Components.ShoppingLocationPicker.GetValue();
}
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{
jsonData.location_id = Grocy.Components.LocationPicker.GetValue();
}
if (Grocy.UserSettings.show_purchased_date_on_purchase)
{
jsonData.purchased_date = Grocy.Components.DateTimePicker2.GetValue();
}
jsonData.price = price; Grocy.Api.Get('stock/products/' + jsonForm.product_id,
function(productDetails)
var bookingResponse = null; {
var price = "";
Grocy.Api.Post('stock/products/' + jsonForm.product_id + '/inventory', jsonData, if (!jsonForm.price.toString().isEmpty())
function(result)
{ {
bookingResponse = result; price = parseFloat(jsonForm.price).toFixed(Grocy.UserSettings.stock_decimal_places_prices);
}
if (GetUriParam("flow") === "InplaceAddBarcodeToExistingProduct") var jsonData = {};
jsonData.new_amount = jsonForm.amount;
jsonData.best_before_date = Grocy.Components.DateTimePicker.GetValue();
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{
jsonData.shopping_location_id = Grocy.Components.ShoppingLocationPicker.GetValue();
}
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{
jsonData.location_id = Grocy.Components.LocationPicker.GetValue();
}
if (Grocy.UserSettings.show_purchased_date_on_purchase)
{
jsonData.purchased_date = Grocy.Components.DateTimePicker2.GetValue();
}
jsonData.price = price;
var bookingResponse = null;
Grocy.Api.Post('stock/products/' + jsonForm.product_id + '/inventory', jsonData,
function(result)
{ {
var jsonDataBarcode = {}; bookingResponse = result;
jsonDataBarcode.barcode = GetUriParam("barcode");
jsonDataBarcode.product_id = jsonForm.product_id;
jsonDataBarcode.shopping_location_id = jsonForm.shopping_location_id;
Grocy.Api.Post('objects/product_barcodes', jsonDataBarcode, if (GetUriParam("flow") === "InplaceAddBarcodeToExistingProduct")
{
var jsonDataBarcode = {};
jsonDataBarcode.barcode = GetUriParam("barcode");
jsonDataBarcode.product_id = jsonForm.product_id;
jsonDataBarcode.shopping_location_id = jsonForm.shopping_location_id;
Grocy.Api.Post('objects/product_barcodes', jsonDataBarcode,
function(result)
{
$("#flow-info-InplaceAddBarcodeToExistingProduct").addClass("d-none");
$('#barcode-lookup-disabled-hint').addClass('d-none');
$('#barcode-lookup-hint').removeClass('d-none');
window.history.replaceState({}, document.title, U("/inventory"));
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("inventory-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
}
);
}
Grocy.Api.Get('stock/products/' + jsonForm.product_id,
function(result) function(result)
{ {
$("#flow-info-InplaceAddBarcodeToExistingProduct").addClass("d-none"); 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>';
$('#barcode-lookup-disabled-hint').addClass('d-none');
$('#barcode-lookup-hint').removeClass('d-none'); if (GetUriParam("embedded") !== undefined)
window.history.replaceState({}, document.title, U("/inventory")); {
window.parent.postMessage(WindowMessageBag("ProductChanged", jsonForm.product_id), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", successMessage), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
}
else
{
Grocy.FrontendHelpers.EndUiBusy("inventory-form");
toastr.success(successMessage);
Grocy.Components.ProductPicker.FinishFlow();
Grocy.Components.ProductAmountPicker.Reset();
$('#inventory-change-info').addClass('d-none');
$("#tare-weight-handling-info").addClass("d-none");
$("#display_amount").attr("min", "0");
$('#display_amount').val('');
$('#display_amount').removeAttr("data-not-equal");
$(".input-group-productamountpicker").trigger("change");
$('#price').val('');
Grocy.Components.DateTimePicker.Clear();
Grocy.Components.ProductPicker.SetValue('');
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{
Grocy.Components.ShoppingLocationPicker.SetValue('');
}
Grocy.Components.ProductPicker.GetInputElement().focus();
Grocy.Components.ProductCard.Refresh(jsonForm.product_id);
Grocy.FrontendHelpers.ValidateForm('inventory-form');
}
}, },
function(xhr) function(xhr)
{ {
Grocy.FrontendHelpers.EndUiBusy("inventory-form"); Grocy.FrontendHelpers.EndUiBusy();
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response); console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("inventory-form");
console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("inventory-form");
console.error(xhr);
}
);
});
Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{
var productId = $(e.target).val();
if (productId)
{
Grocy.Components.ProductCard.Refresh(productId);
Grocy.Api.Get('stock/products/' + productId,
function(productDetails)
{
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.quantity_unit_stock.id);
$('#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"));
if (productDetails.product.enable_tare_weight_handling == 1)
{
$("#display_amount").attr("min", productDetails.product.tare_weight);
$("#tare-weight-handling-info").removeClass("d-none");
}
else
{
$("#display_amount").attr("min", "0");
$("#tare-weight-handling-info").addClass("d-none");
}
$('#price').val(parseFloat(productDetails.last_price));
RefreshLocaleNumberInput();
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{
Grocy.Components.ShoppingLocationPicker.SetId(productDetails.last_shopping_location_id);
}
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{
Grocy.Components.LocationPicker.SetId(productDetails.location.id);
}
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
{
if (productDetails.product.default_best_before_days.toString() !== '0')
{
if (productDetails.product.default_best_before_days == -1)
{
if (!$("#datetimepicker-shortcut").is(":checked"))
{
$("#datetimepicker-shortcut").click();
}
}
else
{
Grocy.Components.DateTimePicker.SetValue(moment().add(productDetails.product.default_best_before_days, 'days').format('YYYY-MM-DD'));
}
}
}
if (document.getElementById("product_id").getAttribute("barcode") != "null")
{
Grocy.Api.Get('objects/product_barcodes?query[]=barcode=' + document.getElementById("product_id").getAttribute("barcode"),
function(barcodeResult)
{
if (barcodeResult != null)
{
var barcode = barcodeResult[0];
if (barcode != null)
{
if (barcode.amount != null && !barcode.amount.isEmpty())
{
$("#display_amount").val(barcode.amount);
$("#display_amount").select();
}
if (barcode.qu_id != null)
{
Grocy.Components.ProductAmountPicker.SetQuantityUnit(barcode.qu_id);
}
$(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('inventory-form');
RefreshLocaleNumberInput();
}
}
},
function(xhr)
{
console.error(xhr);
} }
); );
} }
Grocy.Api.Get('stock/products/' + jsonForm.product_id, $('#display_amount').val(productDetails.stock_amount);
function(result) RefreshLocaleNumberInput();
{ $(".input-group-productamountpicker").trigger("change");
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>'; $('#display_amount').focus();
$('#display_amount').trigger('keyup');
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("ProductChanged", jsonForm.product_id), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", successMessage), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
}
else
{
Grocy.FrontendHelpers.EndUiBusy("inventory-form");
toastr.success(successMessage);
Grocy.Components.ProductPicker.FinishFlow();
Grocy.Components.ProductAmountPicker.Reset();
$('#inventory-change-info').addClass('d-none');
$("#tare-weight-handling-info").addClass("d-none");
$("#display_amount").attr("min", "0");
$('#display_amount').val('');
$('#display_amount').removeAttr("data-not-equal");
$(".input-group-productamountpicker").trigger("change");
$('#price').val('');
Grocy.Components.DateTimePicker.Clear();
Grocy.Components.ProductPicker.SetValue('');
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{
Grocy.Components.ShoppingLocationPicker.SetValue('');
}
Grocy.Components.ProductPicker.GetInputElement().focus();
Grocy.Components.ProductCard.Refresh(jsonForm.product_id);
Grocy.FrontendHelpers.ValidateForm('inventory-form');
}
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
}, },
function(xhr) function(xhr)
{ {
Grocy.FrontendHelpers.EndUiBusy("inventory-form");
console.error(xhr); console.error(xhr);
} }
); );
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("inventory-form");
console.error(xhr);
} }
); });
});
Grocy.Components.ProductPicker.GetPicker().on('change', function(e) $('#display_amount').val('');
{ $(".input-group-productamountpicker").trigger("change");
var productId = $(e.target).val(); Grocy.FrontendHelpers.ValidateForm('inventory-form');
if (productId) if (Grocy.Components.ProductPicker.InAnyFlow() === false && GetUriParam("embedded") === undefined)
{
Grocy.Components.ProductCard.Refresh(productId);
Grocy.Api.Get('stock/products/' + productId,
function(productDetails)
{
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.quantity_unit_stock.id);
$('#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"));
if (productDetails.product.enable_tare_weight_handling == 1)
{
$("#display_amount").attr("min", productDetails.product.tare_weight);
$("#tare-weight-handling-info").removeClass("d-none");
}
else
{
$("#display_amount").attr("min", "0");
$("#tare-weight-handling-info").addClass("d-none");
}
$('#price').val(parseFloat(productDetails.last_price));
RefreshLocaleNumberInput();
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{
Grocy.Components.ShoppingLocationPicker.SetId(productDetails.last_shopping_location_id);
}
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{
Grocy.Components.LocationPicker.SetId(productDetails.location.id);
}
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
{
if (productDetails.product.default_best_before_days.toString() !== '0')
{
if (productDetails.product.default_best_before_days == -1)
{
if (!$("#datetimepicker-shortcut").is(":checked"))
{
$("#datetimepicker-shortcut").click();
}
}
else
{
Grocy.Components.DateTimePicker.SetValue(moment().add(productDetails.product.default_best_before_days, 'days').format('YYYY-MM-DD'));
}
}
}
if (document.getElementById("product_id").getAttribute("barcode") != "null")
{
Grocy.Api.Get('objects/product_barcodes?query[]=barcode=' + document.getElementById("product_id").getAttribute("barcode"),
function(barcodeResult)
{
if (barcodeResult != null)
{
var barcode = barcodeResult[0];
if (barcode != null)
{
if (barcode.amount != null && !barcode.amount.isEmpty())
{
$("#display_amount").val(barcode.amount);
$("#display_amount").select();
}
if (barcode.qu_id != null)
{
Grocy.Components.ProductAmountPicker.SetQuantityUnit(barcode.qu_id);
}
$(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('inventory-form');
RefreshLocaleNumberInput();
}
}
},
function(xhr)
{
console.error(xhr);
}
);
}
$('#display_amount').val(productDetails.stock_amount);
RefreshLocaleNumberInput();
$(".input-group-productamountpicker").trigger("change");
$('#display_amount').focus();
$('#display_amount').trigger('keyup');
},
function(xhr)
{
console.error(xhr);
}
);
}
});
$('#display_amount').val('');
$(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('inventory-form');
if (Grocy.Components.ProductPicker.InAnyFlow() === false && GetUriParam("embedded") === undefined)
{
Grocy.Components.ProductPicker.GetInputElement().focus();
}
else
{
Grocy.Components.ProductPicker.GetPicker().trigger('change');
if (Grocy.Components.ProductPicker.InProductModifyWorkflow())
{
Grocy.Components.ProductPicker.GetInputElement().focus();
}
}
$('#display_amount').on('focus', function(e)
{
if (Grocy.Components.ProductPicker.GetValue().length === 0)
{ {
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.Components.ProductPicker.GetInputElement().focus();
} }
else else
{ {
$(this).select(); Grocy.Components.ProductPicker.GetPicker().trigger('change');
}
});
$('#inventory-form input').keyup(function(event) if (Grocy.Components.ProductPicker.InProductModifyWorkflow())
{
Grocy.FrontendHelpers.ValidateForm('inventory-form');
});
$('#inventory-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('inventory-form').checkValidity() === false) //There is at least one validation error
{ {
return false; Grocy.Components.ProductPicker.GetInputElement().focus();
}
}
$('#display_amount').on('focus', function(e)
{
if (Grocy.Components.ProductPicker.GetValue().length === 0)
{
Grocy.Components.ProductPicker.GetInputElement().focus();
} }
else else
{ {
$('#save-inventory-button').click(); $(this).select();
} }
} });
});
$('#inventory-form input').keyup(function(event)
$('#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")));
Grocy.FrontendHelpers.ValidateForm('inventory-form');
});
Grocy.Components.DateTimePicker.GetInputElement().on('change', function(e)
{
Grocy.FrontendHelpers.ValidateForm('inventory-form');
});
Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e)
{
Grocy.FrontendHelpers.ValidateForm('inventory-form');
});
$('#display_amount').on('keyup', function(e)
{
var productId = Grocy.Components.ProductPicker.GetValue();
var newAmount = parseInt($('#amount').val());
if (productId)
{ {
Grocy.Api.Get('stock/products/' + productId, Grocy.FrontendHelpers.ValidateForm('inventory-form');
function(productDetails) });
$('#inventory-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('inventory-form').checkValidity() === false) //There is at least one validation error
{ {
var productStockAmount = parseFloat(productDetails.stock_amount || parseFloat('0')); return false;
var containerWeight = parseFloat("0");
if (productDetails.product.enable_tare_weight_handling == 1)
{
containerWeight = parseFloat(productDetails.product.tare_weight);
}
var estimatedBookingAmount = Math.abs(newAmount - productStockAmount - containerWeight);
$('#inventory-change-info').removeClass('d-none');
if (productDetails.product.enable_tare_weight_handling == 1 && newAmount < containerWeight)
{
$('#inventory-change-info').addClass('d-none');
}
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)));
Grocy.Components.DateTimePicker.GetInputElement().attr('required', '');
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{
Grocy.Components.LocationPicker.GetInputElement().attr('required', '');
}
}
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)));
Grocy.Components.DateTimePicker.GetInputElement().removeAttr('required');
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{
Grocy.Components.LocationPicker.GetInputElement().removeAttr('required');
}
}
if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
{
Grocy.Components.DateTimePicker.GetInputElement().removeAttr('required');
}
Grocy.FrontendHelpers.ValidateForm('inventory-form');
},
function(xhr)
{
console.error(xhr);
} }
); else
} {
}); $('#save-inventory-button').click();
}
}
});
$("#display_amount").attr("min", "0");
$('#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")));
Grocy.FrontendHelpers.ValidateForm('inventory-form');
});
Grocy.Components.DateTimePicker.GetInputElement().on('change', function(e)
{
Grocy.FrontendHelpers.ValidateForm('inventory-form');
});
Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e)
{
Grocy.FrontendHelpers.ValidateForm('inventory-form');
});
$('#display_amount').on('keyup', function(e)
{
var productId = Grocy.Components.ProductPicker.GetValue();
var newAmount = parseInt($('#amount').val());
if (productId)
{
Grocy.Api.Get('stock/products/' + productId,
function(productDetails)
{
var productStockAmount = parseFloat(productDetails.stock_amount || parseFloat('0'));
var containerWeight = parseFloat("0");
if (productDetails.product.enable_tare_weight_handling == 1)
{
containerWeight = parseFloat(productDetails.product.tare_weight);
}
var estimatedBookingAmount = Math.abs(newAmount - productStockAmount - containerWeight);
$('#inventory-change-info').removeClass('d-none');
if (productDetails.product.enable_tare_weight_handling == 1 && newAmount < containerWeight)
{
$('#inventory-change-info').addClass('d-none');
}
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)));
Grocy.Components.DateTimePicker.GetInputElement().attr('required', '');
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{
Grocy.Components.LocationPicker.GetInputElement().attr('required', '');
}
}
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)));
Grocy.Components.DateTimePicker.GetInputElement().removeAttr('required');
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{
Grocy.Components.LocationPicker.GetInputElement().removeAttr('required');
}
}
if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_BEST_BEFORE_DATE_TRACKING)
{
Grocy.Components.DateTimePicker.GetInputElement().removeAttr('required');
}
Grocy.FrontendHelpers.ValidateForm('inventory-form');
},
function(xhr)
{
console.error(xhr);
}
);
}
});
$("#display_amount").attr("min", "0");
}

View File

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

View File

@ -1,92 +1,102 @@
import { WindowMessageBag } from '../helpers/messagebag'; function locationformView(Grocy, scope = null)
Grocy.Use("userfieldsform");
$('#save-location-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#location-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
Grocy.FrontendHelpers.BeginUiBusy("location-form");
if (Grocy.EditMode === 'create') Grocy.Use("userfieldsform");
$('#save-location-button').on('click', function(e)
{ {
Grocy.Api.Post('objects/locations', jsonData, e.preventDefault();
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/locations');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("location-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/locations/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/locations');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("location-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$('#location-form input').keyup(function(event) if ($(".combobox-menu-visible").length)
{
Grocy.FrontendHelpers.ValidateForm('location-form');
});
$('#location-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('location-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return;
}
var jsonData = $('#location-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("location-form");
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/locations', jsonData,
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/locations');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("location-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
else else
{ {
$('#save-location-button').click(); Grocy.Api.Put('objects/locations/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/locations');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("location-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
} });
});
Grocy.Components.UserfieldsForm.Load(); $('#location-form input').keyup(function(event)
Grocy.FrontendHelpers.ValidateForm('location-form'); {
$('#name').focus(); Grocy.FrontendHelpers.ValidateForm('location-form');
});
$('#location-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('location-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-location-button').click();
}
}
});
Grocy.Components.UserfieldsForm.Load();
Grocy.FrontendHelpers.ValidateForm('location-form');
$('#name').focus();
}

View File

@ -1,18 +1,27 @@
var locationsTable = $('#locations-table').DataTable({ function locationsView(Grocy, scope = null)
'order': [[1, 'asc']], {
'columnDefs': [ var $scope = $;
{ 'orderable': false, 'targets': 0 }, if (scope != null)
{ 'searchable': false, "targets": 0 } {
].concat($.fn.dataTable.defaults.columnDefs) $scope = $(scope).find;
}); }
$('#locations-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(locationsTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox( var locationsTable = $('#locations-table').DataTable({
'Are you sure to delete location "%s"?', 'order': [[1, 'asc']],
'.location-delete-button', 'columnDefs': [
'data-location-name', { 'orderable': false, 'targets': 0 },
'data-location-id', { 'searchable': false, "targets": 0 }
'objects/locations/', ].concat($.fn.dataTable.defaults.columnDefs)
'/locations' });
); $('#locations-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(locationsTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete location "%s"?',
'.location-delete-button',
'data-location-name',
'data-location-id',
'objects/locations/',
'/locations'
);
}

View File

@ -1,7 +1,17 @@
$('#username').focus(); function loginView(Grocy, scope = null)
if (GetUriParam('invalid') === 'true')
{ {
$('#login-error').text(__t('Invalid credentials, please try again')); var $scope = $;
$('#login-error').removeClass('d-none'); if (scope != null)
{
$scope = $(scope).find;
}
$('#username').focus();
if (GetUriParam('invalid') === 'true')
{
$('#login-error').text(__t('Invalid credentials, please try again'));
$('#login-error').removeClass('d-none');
}
} }

View File

@ -1,47 +1,57 @@
import { QrCodeImgHtml } from "../helpers/qrcode"; function manageapikeysView(Grocy, scope = null)
var apiKeysTable = $('#apikeys-table').DataTable({
'order': [[4, 'desc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#apikeys-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(apiKeysTable);
var createdApiKeyId = GetUriParam('CreatedApiKeyId');
if (createdApiKeyId !== undefined)
{ {
animateCSS("#apiKeyRow_" + createdApiKeyId, "pulse"); var $scope = $;
} if (scope != null)
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete API key "%s"?',
'.apikey-delete-button',
'data-apikey-apikey',
'data-apikey-id',
'objects/api_keys/',
'/manageapikeys'
);
function QrCodeForApiKey(apiKeyType, apiKey)
{
var content = U('/api') + '|' + apiKey;
if (apiKeyType === 'special-purpose-calendar-ical')
{ {
content = U('/api/calendar/ical?secret=' + apiKey); $scope = $(scope).find;
} }
return QrCodeImgHtml(content); import { QrCodeImgHtml } from "../helpers/qrcode";
}
$('.apikey-show-qr-button').on('click', function() var apiKeysTable = $('#apikeys-table').DataTable({
{ 'order': [[4, 'desc']],
var qrcodeHtml = QrCodeForApiKey($(this).data('apikey-type'), $(this).data('apikey-key')); 'columnDefs': [
bootbox.alert({ { 'orderable': false, 'targets': 0 },
title: __t('API key'), { 'searchable': false, "targets": 0 }
message: "<p class='text-center'>" + qrcodeHtml + "</p>", ].concat($.fn.dataTable.defaults.columnDefs)
closeButton: false
}); });
}) $('#apikeys-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(apiKeysTable);
var createdApiKeyId = GetUriParam('CreatedApiKeyId');
if (createdApiKeyId !== undefined)
{
animateCSS("#apiKeyRow_" + createdApiKeyId, "pulse");
}
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete API key "%s"?',
'.apikey-delete-button',
'data-apikey-apikey',
'data-apikey-id',
'objects/api_keys/',
'/manageapikeys'
);
function QrCodeForApiKey(apiKeyType, apiKey)
{
var content = U('/api') + '|' + apiKey;
if (apiKeyType === 'special-purpose-calendar-ical')
{
content = U('/api/calendar/ical?secret=' + apiKey);
}
return QrCodeImgHtml(content);
}
$('.apikey-show-qr-button').on('click', function()
{
var qrcodeHtml = QrCodeForApiKey($(this).data('apikey-type'), $(this).data('apikey-key'));
bootbox.alert({
title: __t('API key'),
message: "<p class='text-center'>" + qrcodeHtml + "</p>",
closeButton: false
});
})
}

File diff suppressed because it is too large Load Diff

View File

@ -1,27 +1,37 @@
/* global SwaggerUIBundle, SwaggerUIStandalonePreset */ function openapiuiView(Grocy, scope = null)
function HideTopbarPlugin()
{ {
return { var $scope = $;
components: { if (scope != null)
Topbar: function() { return null } {
$scope = $(scope).find;
}
/* global SwaggerUIBundle, SwaggerUIStandalonePreset */
function HideTopbarPlugin()
{
return {
components: {
Topbar: function() { return null }
}
} }
} }
const swaggerUi = SwaggerUIBundle({
url: Grocy.OpenApi.SpecUrl,
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl,
HideTopbarPlugin
],
layout: 'StandaloneLayout',
docExpansion: "list"
});
window.ui = swaggerUi;
} }
const swaggerUi = SwaggerUIBundle({
url: Grocy.OpenApi.SpecUrl,
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl,
HideTopbarPlugin
],
layout: 'StandaloneLayout',
docExpansion: "list"
});
window.ui = swaggerUi;

View File

@ -1,111 +1,121 @@
import { WindowMessageBag } from '../helpers/messagebag'; function productbarcodeformView(Grocy, scope = null)
Grocy.Use('barcodescanner');
Grocy.Use("productamountpicker");
Grocy.Use("userfieldsform");
$('#save-barcode-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#barcode-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
jsonData.amount = jsonData.display_amount;
delete jsonData.display_amount;
Grocy.FrontendHelpers.BeginUiBusy("barcode-form"); Grocy.Use('barcodescanner');
Grocy.Use("productamountpicker");
Grocy.Use("userfieldsform");
if (Grocy.EditMode === 'create') $('#save-barcode-button').on('click', function(e)
{ {
Grocy.Api.Post('objects/product_barcodes', jsonData, e.preventDefault();
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save()
window.parent.postMessage(WindowMessageBag("ProductBarcodesChanged"), U("/product/" + GetUriParam("product"))); if ($(".combobox-menu-visible").length)
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("barcode-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
}
);
}
else
{
Grocy.Components.UserfieldsForm.Save();
Grocy.Api.Put('objects/product_barcodes/' + Grocy.EditObjectId, jsonData,
function(result)
{
window.parent.postMessage(WindowMessageBag("ProductBarcodesChanged"), U("/product/" + GetUriParam("product")));
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("barcode-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
}
);
}
});
$('#barcode').on('keyup', function(e)
{
Grocy.FrontendHelpers.ValidateForm('barcode-form');
});
$('#qu_id').on('change', function(e)
{
Grocy.FrontendHelpers.ValidateForm('barcode-form');
});
$('#display_amount').on('keyup', function(e)
{
Grocy.FrontendHelpers.ValidateForm('barcode-form');
});
$('#barcode-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('barcode-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return;
}
var jsonData = $('#barcode-form').serializeJSON();
jsonData.amount = jsonData.display_amount;
delete jsonData.display_amount;
Grocy.FrontendHelpers.BeginUiBusy("barcode-form");
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/product_barcodes', jsonData,
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save()
window.parent.postMessage(WindowMessageBag("ProductBarcodesChanged"), U("/product/" + GetUriParam("product")));
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("barcode-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
}
);
} }
else else
{ {
$('#save-barcode-button').click(); Grocy.Components.UserfieldsForm.Save();
Grocy.Api.Put('objects/product_barcodes/' + Grocy.EditObjectId, jsonData,
function(result)
{
window.parent.postMessage(WindowMessageBag("ProductBarcodesChanged"), U("/product/" + GetUriParam("product")));
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("barcode-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
}
);
} }
} });
});
Grocy.Components.ProductAmountPicker.Reload(Grocy.EditObjectProduct.id, Grocy.EditObjectProduct.qu_id_purchase); $('#barcode').on('keyup', function(e)
if (Grocy.EditMode == "edit")
{
$("#display_amount").val(Grocy.EditObject.amount);
$(".input-group-productamountpicker").trigger("change");
Grocy.Components.ProductAmountPicker.SetQuantityUnit(Grocy.EditObject.qu_id);
}
Grocy.FrontendHelpers.ValidateForm('barcode-form');
$('#barcode').focus();
RefreshLocaleNumberInput();
Grocy.Components.UserfieldsForm.Load()
$(document).on("Grocy.BarcodeScanned", function(e, barcode, target)
{
if (target !== "#barcode")
{ {
return; Grocy.FrontendHelpers.ValidateForm('barcode-form');
});
$('#qu_id').on('change', function(e)
{
Grocy.FrontendHelpers.ValidateForm('barcode-form');
});
$('#display_amount').on('keyup', function(e)
{
Grocy.FrontendHelpers.ValidateForm('barcode-form');
});
$('#barcode-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('barcode-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-barcode-button').click();
}
}
});
Grocy.Components.ProductAmountPicker.Reload(Grocy.EditObjectProduct.id, Grocy.EditObjectProduct.qu_id_purchase);
if (Grocy.EditMode == "edit")
{
$("#display_amount").val(Grocy.EditObject.amount);
$(".input-group-productamountpicker").trigger("change");
Grocy.Components.ProductAmountPicker.SetQuantityUnit(Grocy.EditObject.qu_id);
} }
$("#barcode").val(barcode); Grocy.FrontendHelpers.ValidateForm('barcode-form');
}); $('#barcode').focus();
RefreshLocaleNumberInput();
Grocy.Components.UserfieldsForm.Load()
$(document).on("Grocy.BarcodeScanned", function(e, barcode, target)
{
if (target !== "#barcode")
{
return;
}
$("#barcode").val(barcode);
});
}

View File

@ -1,513 +1,523 @@
import { BoolVal } from '../helpers/extensions'; function productformView(Grocy, scope = null)
Grocy.Use("numberpicker");
Grocy.Use("shoppinglocationpicker");
Grocy.Use("userfieldsform");
function saveProductPicture(result, location, jsonData)
{ {
var productId = Grocy.EditObjectId || result.created_object_id; var $scope = $;
if (scope != null)
Grocy.Components.UserfieldsForm.Save(() =>
{ {
if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteProductPictureOnSave) $scope = $(scope).find;
{ }
Grocy.Api.UploadFile($("#product-picture")[0].files[0], 'productpictures', jsonData.picture_file_name,
(result) =>
{
if (Grocy.ProductEditFormRedirectUri == "reload")
{
window.location.reload();
return
}
var returnTo = GetUriParam('returnto'); import { BoolVal } from '../helpers/extensions';
if (GetUriParam("closeAfterCreation") !== undefined)
Grocy.Use("numberpicker");
Grocy.Use("shoppinglocationpicker");
Grocy.Use("userfieldsform");
function saveProductPicture(result, location, jsonData)
{
var productId = Grocy.EditObjectId || result.created_object_id;
Grocy.Components.UserfieldsForm.Save(() =>
{
if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteProductPictureOnSave)
{
Grocy.Api.UploadFile($("#product-picture")[0].files[0], 'productpictures', jsonData.picture_file_name,
(result) =>
{ {
window.close(); if (Grocy.ProductEditFormRedirectUri == "reload")
}
else if (returnTo !== undefined)
{
if (GetUriParam("flow") !== undefined)
{ {
window.location.href = U(returnTo) + '&product-name=' + encodeURIComponent($('#name').val()); window.location.reload();
return
}
var returnTo = GetUriParam('returnto');
if (GetUriParam("closeAfterCreation") !== undefined)
{
window.close();
}
else if (returnTo !== undefined)
{
if (GetUriParam("flow") !== undefined)
{
window.location.href = U(returnTo) + '&product-name=' + encodeURIComponent($('#name').val());
}
else
{
window.location.href = U(returnTo);
}
} }
else else
{ {
window.location.href = U(returnTo); window.location.href = U(location + productId);
} }
},
(xhr) =>
{
Grocy.FrontendHelpers.EndUiBusy("product-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
if (Grocy.ProductEditFormRedirectUri == "reload")
{
window.location.reload();
return
}
var returnTo = GetUriParam('returnto');
if (GetUriParam("closeAfterCreation") !== undefined)
{
window.close();
}
else if (returnTo !== undefined)
{
if (GetUriParam("flow") !== undefined)
{
window.location.href = U(returnTo) + '&product-name=' + encodeURIComponent($('#name').val());
} }
else else
{ {
window.location.href = U(location + productId); window.location.href = U(returnTo);
} }
}
else
{
window.location.href = U(location + productId);
}
}
});
}
}, $('.save-product-button').on('click', function(e)
{
e.preventDefault();
var jsonData = $('#product-form').serializeJSON();
var parentProductId = jsonData.product_id;
delete jsonData.product_id;
jsonData.parent_product_id = parentProductId;
Grocy.FrontendHelpers.BeginUiBusy("product-form");
if (jsonData.parent_product_id.toString().isEmpty())
{
jsonData.parent_product_id = null;
}
if ($("#product-picture")[0].files.length > 0)
{
var someRandomStuff = Math.random().toString(36).substring(2, 100) + Math.random().toString(36).substring(2, 100);
jsonData.picture_file_name = someRandomStuff + $("#product-picture")[0].files[0].name;
}
const location = $(e.currentTarget).attr('data-location') == 'return' ? '/products?product=' : '/product/';
if (Grocy.EditMode == 'create')
{
Grocy.Api.Post('objects/products', jsonData,
(result) => saveProductPicture(result, location, jsonData),
(xhr) => (xhr) =>
{
Grocy.FrontendHelpers.EndUiBusy("product-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
});
return;
}
if (Grocy.DeleteProductPictureOnSave)
{
jsonData.picture_file_name = null;
Grocy.Api.DeleteFile(Grocy.ProductPictureFileName, 'productpictures', {},
function(result)
{
// Nothing to do
},
function(xhr)
{ {
Grocy.FrontendHelpers.EndUiBusy("product-form"); Grocy.FrontendHelpers.EndUiBusy("product-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response) Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
} }
); );
} }
else
{
if (Grocy.ProductEditFormRedirectUri == "reload")
{
window.location.reload();
return
}
var returnTo = GetUriParam('returnto'); Grocy.Api.Put('objects/products/' + Grocy.EditObjectId, jsonData,
if (GetUriParam("closeAfterCreation") !== undefined)
{
window.close();
}
else if (returnTo !== undefined)
{
if (GetUriParam("flow") !== undefined)
{
window.location.href = U(returnTo) + '&product-name=' + encodeURIComponent($('#name').val());
}
else
{
window.location.href = U(returnTo);
}
}
else
{
window.location.href = U(location + productId);
}
}
});
}
$('.save-product-button').on('click', function(e)
{
e.preventDefault();
var jsonData = $('#product-form').serializeJSON();
var parentProductId = jsonData.product_id;
delete jsonData.product_id;
jsonData.parent_product_id = parentProductId;
Grocy.FrontendHelpers.BeginUiBusy("product-form");
if (jsonData.parent_product_id.toString().isEmpty())
{
jsonData.parent_product_id = null;
}
if ($("#product-picture")[0].files.length > 0)
{
var someRandomStuff = Math.random().toString(36).substring(2, 100) + Math.random().toString(36).substring(2, 100);
jsonData.picture_file_name = someRandomStuff + $("#product-picture")[0].files[0].name;
}
const location = $(e.currentTarget).attr('data-location') == 'return' ? '/products?product=' : '/product/';
if (Grocy.EditMode == 'create')
{
Grocy.Api.Post('objects/products', jsonData,
(result) => saveProductPicture(result, location, jsonData), (result) => saveProductPicture(result, location, jsonData),
(xhr) =>
{
Grocy.FrontendHelpers.EndUiBusy("product-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
});
return;
}
if (Grocy.DeleteProductPictureOnSave)
{
jsonData.picture_file_name = null;
Grocy.Api.DeleteFile(Grocy.ProductPictureFileName, 'productpictures', {},
function(result)
{
// Nothing to do
},
function(xhr) function(xhr)
{ {
Grocy.FrontendHelpers.EndUiBusy("product-form"); Grocy.FrontendHelpers.EndUiBusy("product-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response) console.error(xhr);
}
);
});
if (Grocy.EditMode == "edit")
{
Grocy.Api.Get('stock/products/' + Grocy.EditObjectId,
function(productDetails)
{
if (productDetails.last_purchased == null)
{
$('#qu_id_stock').removeAttr("disabled");
}
},
function(xhr)
{
console.error(xhr);
} }
); );
} }
Grocy.Api.Put('objects/products/' + Grocy.EditObjectId, jsonData, if (GetUriParam("flow") == "InplaceNewProductWithName")
(result) => saveProductPicture(result, location, jsonData), {
function(xhr) $('#name').val(GetUriParam("name"));
$('#name').focus();
}
if (GetUriParam("flow") !== undefined || GetUriParam("returnto") !== undefined)
{
$("#save-hint").addClass("d-none");
$(".save-product-button[data-location='return']").addClass("d-none");
}
$('.input-group-qu').on('change', function(e)
{
var quIdPurchase = $("#qu_id_purchase").val();
var quIdStock = $("#qu_id_stock").val();
var factor = $('#qu_factor_purchase_to_stock').val();
if (factor > 1 || quIdPurchase != quIdStock)
{ {
Grocy.FrontendHelpers.EndUiBusy("product-form"); $('#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"))));
console.error(xhr); $('#qu-conversion-info').removeClass('d-none');
}
);
});
if (Grocy.EditMode == "edit")
{
Grocy.Api.Get('stock/products/' + Grocy.EditObjectId,
function(productDetails)
{
if (productDetails.last_purchased == null)
{
$('#qu_id_stock').removeAttr("disabled");
}
},
function(xhr)
{
console.error(xhr);
}
);
}
if (GetUriParam("flow") == "InplaceNewProductWithName")
{
$('#name').val(GetUriParam("name"));
$('#name').focus();
}
if (GetUriParam("flow") !== undefined || GetUriParam("returnto") !== undefined)
{
$("#save-hint").addClass("d-none");
$(".save-product-button[data-location='return']").addClass("d-none");
}
$('.input-group-qu').on('change', function(e)
{
var quIdPurchase = $("#qu_id_purchase").val();
var quIdStock = $("#qu_id_stock").val();
var factor = $('#qu_factor_purchase_to_stock').val();
if (factor > 1 || quIdPurchase != quIdStock)
{
$('#qu-conversion-info').text(__t('This means 1 %1$s purchased will be converted into %2$s %3$s in stock', $("#qu_id_purchase option:selected").text(), (1 * factor).toString(), __n((1 * factor).toString(), $("#qu_id_stock option:selected").text(), $("#qu_id_stock option:selected").data("plural-form"))));
$('#qu-conversion-info').removeClass('d-none');
}
else
{
$('#qu-conversion-info').addClass('d-none');
}
$("#tare_weight_qu_info").text($("#qu_id_stock option:selected").text());
$("#quick_consume_qu_info").text($("#qu_id_stock option:selected").text());
Grocy.FrontendHelpers.ValidateForm('product-form');
});
$('#product-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('product-form');
$(".input-group-qu").trigger("change");
$("#product-form select").trigger("select");
if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error
{
$("#qu-conversion-add-button").addClass("disabled");
}
else
{
$("#qu-conversion-add-button").removeClass("disabled");
}
if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error
{
$("#barcode-add-button").addClass("disabled");
}
});
$('#location_id').change(function(event)
{
Grocy.FrontendHelpers.ValidateForm('product-form');
});
$('#product-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error
{
return false;
} }
else else
{ {
$('#save-product-button').click(); $('#qu-conversion-info').addClass('d-none');
} }
}
});
$("#enable_tare_weight_handling").on("click", function() $("#tare_weight_qu_info").text($("#qu_id_stock option:selected").text());
{ $("#quick_consume_qu_info").text($("#qu_id_stock option:selected").text());
if (this.checked)
Grocy.FrontendHelpers.ValidateForm('product-form');
});
$('#product-form input').keyup(function(event)
{ {
$("#tare_weight").removeAttr("disabled"); Grocy.FrontendHelpers.ValidateForm('product-form');
$(".input-group-qu").trigger("change");
$("#product-form select").trigger("select");
if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error
{
$("#qu-conversion-add-button").addClass("disabled");
}
else
{
$("#qu-conversion-add-button").removeClass("disabled");
}
if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error
{
$("#barcode-add-button").addClass("disabled");
}
});
$('#location_id').change(function(event)
{
Grocy.FrontendHelpers.ValidateForm('product-form');
});
$('#product-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('product-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-product-button').click();
}
}
});
$("#enable_tare_weight_handling").on("click", function()
{
if (this.checked)
{
$("#tare_weight").removeAttr("disabled");
}
else
{
$("#tare_weight").attr("disabled", "");
}
Grocy.FrontendHelpers.ValidateForm("product-form");
});
$("#product-picture").on("change", function(e)
{
$("#product-picture-label").removeClass("d-none");
$("#product-picture-label-none").addClass("d-none");
$("#delete-current-product-picture-on-save-hint").addClass("d-none");
$("#current-product-picture").addClass("d-none");
Grocy.DeleteProductPictureOnSave = false;
});
Grocy.DeleteProductPictureOnSave = false;
$("#delete-current-product-picture-button").on("click", function(e)
{
Grocy.DeleteProductPictureOnSave = true;
$("#current-product-picture").addClass("d-none");
$("#delete-current-product-picture-on-save-hint").removeClass("d-none");
$("#product-picture-label").addClass("d-none");
$("#product-picture-label-none").removeClass("d-none");
});
var quConversionsTable = $('#qu-conversions-table-products').DataTable({
'order': [[1, 'asc']],
"orderFixed": [[4, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ 'visible': false, 'targets': 4 }
].concat($.fn.dataTable.defaults.columnDefs),
'rowGroup': {
enable: true,
dataSrc: 4
}
});
$('#qu-conversions-table-products tbody').removeClass("d-none");
quConversionsTable.columns.adjust().draw();
var barcodeTable = $('#barcode-table').DataTable({
'order': [[1, 'asc']],
"orderFixed": [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ 'visible': false, 'targets': 5 },
{ 'visible': false, 'targets': 6 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#barcode-table tbody').removeClass("d-none");
barcodeTable.columns.adjust().draw();
Grocy.Components.UserfieldsForm.Load();
$("#name").trigger("keyup");
$('#name').focus();
$('.input-group-qu').trigger('change');
Grocy.FrontendHelpers.ValidateForm('product-form');
$(document).on('click', '.stockentry-grocycode-product-label-print', function(e)
{
e.preventDefault();
document.activeElement.blur();
var productId = $(e.currentTarget).attr('data-product-id');
Grocy.Api.Get('stock/products/' + productId + '/printlabel', function(labelData)
{
if (Grocy.Webhooks.labelprinter !== undefined)
{
Grocy.FrontendHelpers.RunWebhook(Grocy.Webhooks.labelprinter, labelData);
}
});
});
$(document).on('click', '.qu-conversion-delete-button', function(e)
{
var objectId = $(e.currentTarget).attr('data-qu-conversion-id');
bootbox.confirm({
message: __t('Are you sure to remove this conversion?'),
closeButton: false,
buttons: {
confirm: {
label: __t('Yes'),
className: 'btn-success'
},
cancel: {
label: __t('No'),
className: 'btn-danger'
}
},
callback: function(result)
{
if (result === true)
{
Grocy.Api.Delete('objects/quantity_unit_conversions/' + objectId, {},
function(result)
{
Grocy.ProductEditFormRedirectUri = "reload";
$('#save-product-button').click();
},
function(xhr)
{
console.error(xhr);
}
);
}
}
});
});
$(document).on('click', '.barcode-delete-button', function(e)
{
var objectId = $(e.currentTarget).attr('data-barcode-id');
bootbox.confirm({
message: __t('Are you sure to remove this barcode?'),
closeButton: false,
buttons: {
confirm: {
label: __t('Yes'),
className: 'btn-success'
},
cancel: {
label: __t('No'),
className: 'btn-danger'
}
},
callback: function(result)
{
if (result === true)
{
Grocy.Api.Delete('objects/product_barcodes/' + objectId, {},
function(result)
{
Grocy.ProductEditFormRedirectUri = "reload";
$('#save-product-button').click();
},
function(xhr)
{
console.error(xhr);
}
);
}
}
});
});
$('#qu_id_stock').change(function(e)
{
// Preset QU purchase with stock QU if unset
var quIdStock = $('#qu_id_stock');
var quIdPurchase = $('#qu_id_purchase');
if (quIdPurchase[0].selectedIndex === 0 && quIdStock[0].selectedIndex !== 0)
{
quIdPurchase[0].selectedIndex = quIdStock[0].selectedIndex;
Grocy.FrontendHelpers.ValidateForm('product-form');
}
});
$('#allow_label_per_unit').on('change', function()
{
if (this.checked)
{
$('#label-option-per-unit').prop("disabled", false);
}
else
{
if ($('#default_print_stock_label').val() == "2")
{
$("#default_print_stock_label").val("0");
}
$('#label-option-per-unit').prop("disabled", true);
}
});
$(window).on("message", function(e)
{
var data = e.originalEvent.data;
if (data.Message === "ProductBarcodesChanged" || data.Message === "ProductQUConversionChanged")
{
window.location.reload();
}
});
if (Grocy.EditMode == "create" && GetUriParam("copy-of") != undefined)
{
Grocy.Api.Get('objects/products/' + GetUriParam("copy-of"),
function(sourceProduct)
{
if (sourceProduct.parent_product_id != null)
{
Grocy.Components.ProductPicker.SetId(sourceProduct.parent_product_id);
}
if (sourceProduct.description != null)
{
$("#description").summernote("pasteHTML", sourceProduct.description);
}
$("#location_id").val(sourceProduct.location_id);
if (sourceProduct.shopping_location_id != null)
{
Grocy.Components.ShoppingLocationPicker.SetId(sourceProduct.shopping_location_id);
}
$("#min_stock_amount").val(sourceProduct.min_stock_amount);
if (BoolVal(sourceProduct.cumulate_min_stock_amount_of_sub_products))
{
$("#cumulate_min_stock_amount_of_sub_products").prop("checked", true);
}
$("#default_best_before_days").val(sourceProduct.default_best_before_days);
$("#default_best_before_days_after_open").val(sourceProduct.default_best_before_days_after_open);
if (sourceProduct.product_group_id != null)
{
$("#product_group_id").val(sourceProduct.product_group_id);
}
$("#qu_id_stock").val(sourceProduct.qu_id_stock);
$("#qu_id_purchase").val(sourceProduct.qu_id_purchase);
$("#qu_factor_purchase_to_stock").val(sourceProduct.qu_factor_purchase_to_stock);
if (BoolVal(sourceProduct.enable_tare_weight_handling))
{
$("#enable_tare_weight_handling").prop("checked", true);
}
$("#tare_weight").val(sourceProduct.tare_weight);
if (BoolVal(sourceProduct.not_check_stock_fulfillment_for_recipes))
{
$("#not_check_stock_fulfillment_for_recipes").prop("checked", true);
}
if (sourceProduct.calories != null)
{
$("#calories").val(sourceProduct.calories);
}
$("#default_best_before_days_after_freezing").val(sourceProduct.default_best_before_days_after_freezing);
$("#default_best_before_days_after_thawing").val(sourceProduct.default_best_before_days_after_thawing);
$("#quick_consume_amount").val(sourceProduct.quick_consume_amount);
Grocy.FrontendHelpers.ValidateForm('product-form');
},
function(xhr)
{
console.error(xhr);
}
);
} }
else else if (Grocy.EditMode === 'create')
{ {
$("#tare_weight").attr("disabled", ""); if (Grocy.UserSettings.product_presets_location_id.toString() !== '-1')
{
$("#location_id").val(Grocy.UserSettings.product_presets_location_id);
}
if (Grocy.UserSettings.product_presets_product_group_id.toString() !== '-1')
{
$("#product_group_id").val(Grocy.UserSettings.product_presets_product_group_id);
}
if (Grocy.UserSettings.product_presets_qu_id.toString() !== '-1')
{
$("select.input-group-qu").val(Grocy.UserSettings.product_presets_qu_id);
}
} }
Grocy.FrontendHelpers.ValidateForm("product-form"); Grocy.FrontendHelpers.ValidateForm("product-form");
});
$("#product-picture").on("change", function(e)
{
$("#product-picture-label").removeClass("d-none");
$("#product-picture-label-none").addClass("d-none");
$("#delete-current-product-picture-on-save-hint").addClass("d-none");
$("#current-product-picture").addClass("d-none");
Grocy.DeleteProductPictureOnSave = false;
});
Grocy.DeleteProductPictureOnSave = false;
$("#delete-current-product-picture-button").on("click", function(e)
{
Grocy.DeleteProductPictureOnSave = true;
$("#current-product-picture").addClass("d-none");
$("#delete-current-product-picture-on-save-hint").removeClass("d-none");
$("#product-picture-label").addClass("d-none");
$("#product-picture-label-none").removeClass("d-none");
});
var quConversionsTable = $('#qu-conversions-table-products').DataTable({
'order': [[1, 'asc']],
"orderFixed": [[4, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ 'visible': false, 'targets': 4 }
].concat($.fn.dataTable.defaults.columnDefs),
'rowGroup': {
enable: true,
dataSrc: 4
}
});
$('#qu-conversions-table-products tbody').removeClass("d-none");
quConversionsTable.columns.adjust().draw();
var barcodeTable = $('#barcode-table').DataTable({
'order': [[1, 'asc']],
"orderFixed": [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ 'visible': false, 'targets': 5 },
{ 'visible': false, 'targets': 6 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#barcode-table tbody').removeClass("d-none");
barcodeTable.columns.adjust().draw();
Grocy.Components.UserfieldsForm.Load();
$("#name").trigger("keyup");
$('#name').focus();
$('.input-group-qu').trigger('change');
Grocy.FrontendHelpers.ValidateForm('product-form');
$(document).on('click', '.stockentry-grocycode-product-label-print', function(e)
{
e.preventDefault();
document.activeElement.blur();
var productId = $(e.currentTarget).attr('data-product-id');
Grocy.Api.Get('stock/products/' + productId + '/printlabel', function(labelData)
{
if (Grocy.Webhooks.labelprinter !== undefined)
{
Grocy.FrontendHelpers.RunWebhook(Grocy.Webhooks.labelprinter, labelData);
}
});
});
$(document).on('click', '.qu-conversion-delete-button', function(e)
{
var objectId = $(e.currentTarget).attr('data-qu-conversion-id');
bootbox.confirm({
message: __t('Are you sure to remove this conversion?'),
closeButton: false,
buttons: {
confirm: {
label: __t('Yes'),
className: 'btn-success'
},
cancel: {
label: __t('No'),
className: 'btn-danger'
}
},
callback: function(result)
{
if (result === true)
{
Grocy.Api.Delete('objects/quantity_unit_conversions/' + objectId, {},
function(result)
{
Grocy.ProductEditFormRedirectUri = "reload";
$('#save-product-button').click();
},
function(xhr)
{
console.error(xhr);
}
);
}
}
});
});
$(document).on('click', '.barcode-delete-button', function(e)
{
var objectId = $(e.currentTarget).attr('data-barcode-id');
bootbox.confirm({
message: __t('Are you sure to remove this barcode?'),
closeButton: false,
buttons: {
confirm: {
label: __t('Yes'),
className: 'btn-success'
},
cancel: {
label: __t('No'),
className: 'btn-danger'
}
},
callback: function(result)
{
if (result === true)
{
Grocy.Api.Delete('objects/product_barcodes/' + objectId, {},
function(result)
{
Grocy.ProductEditFormRedirectUri = "reload";
$('#save-product-button').click();
},
function(xhr)
{
console.error(xhr);
}
);
}
}
});
});
$('#qu_id_stock').change(function(e)
{
// Preset QU purchase with stock QU if unset
var quIdStock = $('#qu_id_stock');
var quIdPurchase = $('#qu_id_purchase');
if (quIdPurchase[0].selectedIndex === 0 && quIdStock[0].selectedIndex !== 0)
{
quIdPurchase[0].selectedIndex = quIdStock[0].selectedIndex;
Grocy.FrontendHelpers.ValidateForm('product-form');
}
});
$('#allow_label_per_unit').on('change', function()
{
if (this.checked)
{
$('#label-option-per-unit').prop("disabled", false);
}
else
{
if ($('#default_print_stock_label').val() == "2")
{
$("#default_print_stock_label").val("0");
}
$('#label-option-per-unit').prop("disabled", true);
}
});
$(window).on("message", function(e)
{
var data = e.originalEvent.data;
if (data.Message === "ProductBarcodesChanged" || data.Message === "ProductQUConversionChanged")
{
window.location.reload();
}
});
if (Grocy.EditMode == "create" && GetUriParam("copy-of") != undefined)
{
Grocy.Api.Get('objects/products/' + GetUriParam("copy-of"),
function(sourceProduct)
{
if (sourceProduct.parent_product_id != null)
{
Grocy.Components.ProductPicker.SetId(sourceProduct.parent_product_id);
}
if (sourceProduct.description != null)
{
$("#description").summernote("pasteHTML", sourceProduct.description);
}
$("#location_id").val(sourceProduct.location_id);
if (sourceProduct.shopping_location_id != null)
{
Grocy.Components.ShoppingLocationPicker.SetId(sourceProduct.shopping_location_id);
}
$("#min_stock_amount").val(sourceProduct.min_stock_amount);
if (BoolVal(sourceProduct.cumulate_min_stock_amount_of_sub_products))
{
$("#cumulate_min_stock_amount_of_sub_products").prop("checked", true);
}
$("#default_best_before_days").val(sourceProduct.default_best_before_days);
$("#default_best_before_days_after_open").val(sourceProduct.default_best_before_days_after_open);
if (sourceProduct.product_group_id != null)
{
$("#product_group_id").val(sourceProduct.product_group_id);
}
$("#qu_id_stock").val(sourceProduct.qu_id_stock);
$("#qu_id_purchase").val(sourceProduct.qu_id_purchase);
$("#qu_factor_purchase_to_stock").val(sourceProduct.qu_factor_purchase_to_stock);
if (BoolVal(sourceProduct.enable_tare_weight_handling))
{
$("#enable_tare_weight_handling").prop("checked", true);
}
$("#tare_weight").val(sourceProduct.tare_weight);
if (BoolVal(sourceProduct.not_check_stock_fulfillment_for_recipes))
{
$("#not_check_stock_fulfillment_for_recipes").prop("checked", true);
}
if (sourceProduct.calories != null)
{
$("#calories").val(sourceProduct.calories);
}
$("#default_best_before_days_after_freezing").val(sourceProduct.default_best_before_days_after_freezing);
$("#default_best_before_days_after_thawing").val(sourceProduct.default_best_before_days_after_thawing);
$("#quick_consume_amount").val(sourceProduct.quick_consume_amount);
Grocy.FrontendHelpers.ValidateForm('product-form');
},
function(xhr)
{
console.error(xhr);
}
);
} }
else if (Grocy.EditMode === 'create')
{
if (Grocy.UserSettings.product_presets_location_id.toString() !== '-1')
{
$("#location_id").val(Grocy.UserSettings.product_presets_location_id);
}
if (Grocy.UserSettings.product_presets_product_group_id.toString() !== '-1')
{
$("#product_group_id").val(Grocy.UserSettings.product_presets_product_group_id);
}
if (Grocy.UserSettings.product_presets_qu_id.toString() !== '-1')
{
$("select.input-group-qu").val(Grocy.UserSettings.product_presets_qu_id);
}
}
Grocy.FrontendHelpers.ValidateForm("product-form");

View File

@ -1,78 +1,88 @@
import { WindowMessageBag } from '../helpers/messagebag'; function productgroupformView(Grocy, scope = null)
Grocy.Use("userfieldsform");
$('#save-product-group-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#product-group-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
Grocy.FrontendHelpers.BeginUiBusy("product-group-form");
if (Grocy.EditMode === 'create') Grocy.Use("userfieldsform");
$('#save-product-group-button').on('click', function(e)
{ {
Grocy.Api.Post('objects/product_groups', jsonData, e.preventDefault();
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/productgroups"));
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("product-group-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/product_groups/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/productgroups"));
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("product-group-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$('#product-group-form input').keyup(function(event) if ($(".combobox-menu-visible").length)
{
Grocy.FrontendHelpers.ValidateForm('product-group-form');
});
$('#product-group-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('product-group-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return;
}
var jsonData = $('#product-group-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("product-group-form");
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/product_groups', jsonData,
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/productgroups"));
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("product-group-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
else else
{ {
$('#save-product-group-button').click(); Grocy.Api.Put('objects/product_groups/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/productgroups"));
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("product-group-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
} });
});
Grocy.Components.UserfieldsForm.Load(); $('#product-group-form input').keyup(function(event)
$('#name').focus(); {
Grocy.FrontendHelpers.ValidateForm('product-group-form'); Grocy.FrontendHelpers.ValidateForm('product-group-form');
});
$('#product-group-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('product-group-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-product-group-button').click();
}
}
});
Grocy.Components.UserfieldsForm.Load();
$('#name').focus();
Grocy.FrontendHelpers.ValidateForm('product-group-form');
}

View File

@ -1,27 +1,37 @@
var groupsTable = $('#productgroups-table').DataTable({ function productgroupsView(Grocy, scope = null)
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#productgroups-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(groupsTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete product group "%s"?',
'.product-group-delete-button',
'data-group-name',
'data-group-id',
'objects/product_groups/',
'/productgroups'
);
$(window).on("message", function(e)
{ {
var data = e.originalEvent.data; var $scope = $;
if (scope != null)
if (data.Message === "CloseAllModals")
{ {
window.location.reload(); $scope = $(scope).find;
} }
});
var groupsTable = $('#productgroups-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#productgroups-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(groupsTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete product group "%s"?',
'.product-group-delete-button',
'data-group-name',
'data-group-id',
'objects/product_groups/',
'/productgroups'
);
$(window).on("message", function(e)
{
var data = e.originalEvent.data;
if (data.Message === "CloseAllModals")
{
window.location.reload();
}
});
}

View File

@ -1,81 +1,91 @@
var productsTable = $('#products-table').DataTable({ function productsView(Grocy, scope = null)
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ 'visible': false, 'targets': 7 },
{ "type": "html-num-fmt", "targets": 3 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#products-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(productsTable, null, function()
{ {
$("#search").val(""); var $scope = $;
productsTable.search("").draw(); if (scope != null)
$("#show-disabled").prop('checked', false);
})
Grocy.FrontendHelpers.MakeFilterForColumn("#product-group-filter", 6, productsTable);
if (typeof GetUriParam("product-group") !== "undefined")
{
$("#product-group-filter").val(GetUriParam("product-group"));
$("#product-group-filter").trigger("change");
}
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
(objectId, objectName) =>
{ {
return __t('Are you sure to delete product "%s"?', objectName) + $scope = $(scope).find;
'<br><br>' +
__t('This also removes any stock amount, the journal and all other references of this product - consider disabling it instead, if you want to keep that and just hide the product.');
},
'.product-delete-button',
'data-product-name',
'data-product-id',
'objects/products/',
'/products'
);
$("#show-disabled").change(function()
{
if (this.checked)
{
window.location.href = U('/products?include_disabled');
} }
else
var productsTable = $('#products-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ 'visible': false, 'targets': 7 },
{ "type": "html-num-fmt", "targets": 3 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#products-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(productsTable, null, function()
{ {
window.location.href = U('/products'); $("#search").val("");
productsTable.search("").draw();
$("#show-disabled").prop('checked', false);
})
Grocy.FrontendHelpers.MakeFilterForColumn("#product-group-filter", 6, productsTable);
if (typeof GetUriParam("product-group") !== "undefined")
{
$("#product-group-filter").val(GetUriParam("product-group"));
$("#product-group-filter").trigger("change");
} }
});
if (GetUriParam('include_disabled')) Grocy.FrontendHelpers.MakeDeleteConfirmBox(
{ (objectId, objectName) =>
$("#show-disabled").prop('checked', true); {
} return __t('Are you sure to delete product "%s"?', objectName) +
'<br><br>' +
__t('This also removes any stock amount, the journal and all other references of this product - consider disabling it instead, if you want to keep that and just hide the product.');
},
'.product-delete-button',
'data-product-name',
'data-product-id',
'objects/products/',
'/products'
);
$("#show-disabled").change(function()
$(".merge-products-button").on("click", function(e) {
{ if (this.checked)
var productId = $(e.currentTarget).attr("data-product-id"); {
$("#merge-products-keep").val(productId); window.location.href = U('/products?include_disabled');
$("#merge-products-remove").val(""); }
$("#merge-products-modal").modal("show"); else
});
$("#merge-products-save-button").on("click", function()
{
var productIdToKeep = $("#merge-products-keep").val();
var productIdToRemove = $("#merge-products-remove").val();
Grocy.Api.Post("stock/products/" + productIdToKeep.toString() + "/merge/" + productIdToRemove.toString(), {},
function(result)
{ {
window.location.href = U('/products'); window.location.href = U('/products');
},
function(xhr)
{
Grocy.FrontendHelpers.ShowGenericError('Error while merging products', xhr.response);
} }
); });
});
if (GetUriParam('include_disabled'))
{
$("#show-disabled").prop('checked', true);
}
$(".merge-products-button").on("click", function(e)
{
var productId = $(e.currentTarget).attr("data-product-id");
$("#merge-products-keep").val(productId);
$("#merge-products-remove").val("");
$("#merge-products-modal").modal("show");
});
$("#merge-products-save-button").on("click", function()
{
var productIdToKeep = $("#merge-products-keep").val();
var productIdToRemove = $("#merge-products-remove").val();
Grocy.Api.Post("stock/products/" + productIdToKeep.toString() + "/merge/" + productIdToRemove.toString(), {},
function(result)
{
window.location.href = U('/products');
},
function(xhr)
{
Grocy.FrontendHelpers.ShowGenericError('Error while merging products', xhr.response);
}
);
});
}

File diff suppressed because it is too large Load Diff

View File

@ -1,73 +1,114 @@
import { WindowMessageBag } from '../helpers/messagebag'; function quantityunitconversionformView(Grocy, scope = null)
Grocy.Use("numberpicker");
Grocy.Use("userfieldsform");
$('#save-quconversion-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#quconversion-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
jsonData.from_qu_id = $("#from_qu_id").val();
Grocy.FrontendHelpers.BeginUiBusy("quconversion-form");
if ($("#create_inverse").is(":checked"))
{
var inverse_to_qu_id = $("#from_qu_id").val();
var inverse_from_qu_id = $("#to_qu_id").val();
}
if (Grocy.EditMode === 'create') Grocy.Use("numberpicker");
Grocy.Use("userfieldsform");
$('#save-quconversion-button').on('click', function(e)
{ {
Grocy.Api.Post('objects/quantity_unit_conversions', jsonData, e.preventDefault();
function(result)
{ if ($(".combobox-menu-visible").length)
Grocy.EditObjectId = result.created_object_id; {
Grocy.Components.UserfieldsForm.Save(function() return;
}
var jsonData = $('#quconversion-form').serializeJSON();
jsonData.from_qu_id = $("#from_qu_id").val();
Grocy.FrontendHelpers.BeginUiBusy("quconversion-form");
if ($("#create_inverse").is(":checked"))
{
var inverse_to_qu_id = $("#from_qu_id").val();
var inverse_from_qu_id = $("#to_qu_id").val();
}
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/quantity_unit_conversions', jsonData,
function(result)
{ {
if ($("#create_inverse").is(":checked")) Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{ {
jsonData.to_qu_id = inverse_to_qu_id; if ($("#create_inverse").is(":checked"))
jsonData.from_qu_id = inverse_from_qu_id; {
jsonData.factor = 1 / jsonData.factor; jsonData.to_qu_id = inverse_to_qu_id;
jsonData.from_qu_id = inverse_from_qu_id;
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)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{ {
if (typeof GetUriParam("qu-unit") !== "undefined") Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{ {
if (GetUriParam("embedded") !== undefined) if (typeof GetUriParam("qu-unit") !== "undefined")
{ {
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl); if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U("/quantityunit/" + GetUriParam("qu-unit"));
}
} }
else else
{ {
window.location.href = U("/quantityunit/" + GetUriParam("qu-unit")); window.parent.postMessage(WindowMessageBag("ProductQUConversionChanged"), U("/product/" + GetUriParam("product")));
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
} }
} });
else },
{ function(xhr)
window.parent.postMessage(WindowMessageBag("ProductQUConversionChanged"), U("/product/" + GetUriParam("product"))); {
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product"))); Grocy.FrontendHelpers.EndUiBusy("quconversion-form");
} Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}); }
}, );
function(xhr) }
else
{
if (typeof GetUriParam("qu-unit") !== "undefined")
{ {
Grocy.FrontendHelpers.EndUiBusy("quconversion-form"); if (GetUriParam("embedded") !== undefined)
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response) {
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U("/quantityunit/" + GetUriParam("qu-unit"));
}
} }
); else
} {
else window.parent.postMessage(WindowMessageBag("ProductQUConversionChanged"), U("/product/" + GetUriParam("product")));
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
}
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("quconversion-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/quantity_unit_conversions/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{ {
if (typeof GetUriParam("qu-unit") !== "undefined") if (typeof GetUriParam("qu-unit") !== "undefined")
{ {
@ -85,129 +126,98 @@ $('#save-quconversion-button').on('click', function(e)
window.parent.postMessage(WindowMessageBag("ProductQUConversionChanged"), U("/product/" + GetUriParam("product"))); window.parent.postMessage(WindowMessageBag("ProductQUConversionChanged"), U("/product/" + GetUriParam("product")));
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product"))); window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
} }
} });
}); },
}, function(xhr)
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("quconversion-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/quantity_unit_conversions/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{ {
if (typeof GetUriParam("qu-unit") !== "undefined") Grocy.FrontendHelpers.EndUiBusy("quconversion-form");
{ Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
if (GetUriParam("embedded") !== undefined) }
{ );
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl); }
} });
else
{
window.location.href = U("/quantityunit/" + GetUriParam("qu-unit"));
}
}
else
{
window.parent.postMessage(WindowMessageBag("ProductQUConversionChanged"), U("/product/" + GetUriParam("product")));
window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("quconversion-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$('#quconversion-form input').keyup(function(event) $('#quconversion-form input').keyup(function(event)
{
$('.input-group-qu').trigger('change');
Grocy.FrontendHelpers.ValidateForm('quconversion-form');
});
$('#quconversion-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{ {
event.preventDefault(); $('.input-group-qu').trigger('change');
Grocy.FrontendHelpers.ValidateForm('quconversion-form');
});
if (document.getElementById('quconversion-form').checkValidity() === false) //There is at least one validation error $('#quconversion-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{ {
return false; event.preventDefault();
if (document.getElementById('quconversion-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-quconversion-button').click();
}
}
});
$("#create_inverse").on("change", function()
{
var value = $(this).is(":checked");
if (value)
{
$('#qu-conversion-inverse-info').removeClass('d-none');
} }
else else
{ {
$('#save-quconversion-button').click(); $('#qu-conversion-inverse-info').addClass('d-none');
} }
} });
});
$("#create_inverse").on("change", function() $('.input-group-qu').on('change', function(e)
{
var value = $(this).is(":checked");
if (value)
{ {
$('#qu-conversion-inverse-info').removeClass('d-none'); var fromQuId = $("#from_qu_id").val();
} var toQuId = $("#to_qu_id").val();
else var factor = $('#factor').val();
{
$('#qu-conversion-inverse-info').addClass('d-none');
}
});
$('.input-group-qu').on('change', function(e) if (fromQuId == toQuId)
{
var fromQuId = $("#from_qu_id").val();
var toQuId = $("#to_qu_id").val();
var factor = $('#factor').val();
if (fromQuId == toQuId)
{
$("#to_qu_id").parent().find(".invalid-feedback").text(__t('This cannot be equal to %s', $("#from_qu_id option:selected").text()));
$("#to_qu_id")[0].setCustomValidity("error");
}
else
{
$("#to_qu_id")[0].setCustomValidity("");
}
if (fromQuId && toQuId)
{
$('#qu-conversion-info').text(__t('This means 1 %1$s is the same as %2$s %3$s', $("#from_qu_id option:selected").text(), parseFloat((1 * factor)).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }), __n((1 * factor).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }), $("#to_qu_id option:selected").text(), $("#to_qu_id option:selected").data("plural-form"))));
$('#qu-conversion-info').removeClass('d-none');
if (Grocy.EditMode === 'create')
{ {
$('#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")))); $("#to_qu_id").parent().find(".invalid-feedback").text(__t('This cannot be equal to %s', $("#from_qu_id option:selected").text()));
$('#qu-conversion-inverse-info').removeClass('d-none'); $("#to_qu_id")[0].setCustomValidity("error");
}
else
{
$("#to_qu_id")[0].setCustomValidity("");
} }
}
else
{
$('#qu-conversion-info').addClass('d-none');
$('#qu-conversion-inverse-info').addClass('d-none');
}
if (fromQuId && toQuId)
{
$('#qu-conversion-info').text(__t('This means 1 %1$s is the same as %2$s %3$s', $("#from_qu_id option:selected").text(), parseFloat((1 * factor)).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }), __n((1 * factor).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }), $("#to_qu_id option:selected").text(), $("#to_qu_id option:selected").data("plural-form"))));
$('#qu-conversion-info').removeClass('d-none');
if (Grocy.EditMode === 'create')
{
$('#qu-conversion-inverse-info').text(__t('This means 1 %1$s is the same as %2$s %3$s', $("#to_qu_id option:selected").text(), parseFloat((1 / factor)).toLocaleString({ minimumFractionDigits: 0, maximumFractionDigits: Grocy.UserSettings.stock_decimal_places_amounts }), __n((1 / factor).toString(), $("#from_qu_id option:selected").text(), $("#from_qu_id option:selected").data("plural-form"))));
$('#qu-conversion-inverse-info').removeClass('d-none');
}
}
else
{
$('#qu-conversion-info').addClass('d-none');
$('#qu-conversion-inverse-info').addClass('d-none');
}
Grocy.FrontendHelpers.ValidateForm('quconversion-form');
});
Grocy.Components.UserfieldsForm.Load();
$('.input-group-qu').trigger('change');
$('#from_qu_id').focus();
Grocy.FrontendHelpers.ValidateForm('quconversion-form'); Grocy.FrontendHelpers.ValidateForm('quconversion-form');
});
Grocy.Components.UserfieldsForm.Load(); if (GetUriParam("qu-unit") !== undefined)
$('.input-group-qu').trigger('change'); {
$('#from_qu_id').focus(); $("#from_qu_id").attr("disabled", "");
Grocy.FrontendHelpers.ValidateForm('quconversion-form'); }
if (GetUriParam("qu-unit") !== undefined)
{
$("#from_qu_id").attr("disabled", "");
} }

View File

@ -1,179 +1,189 @@
import { WindowMessageBag } from '../helpers/messagebag'; function quantityunitformView(Grocy, scope = null)
Grocy.Use("userfieldsform");
$('.save-quantityunit-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
var jsonData = $('#quantityunit-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("quantityunit-form");
var redirectDestination = U('/quantityunits');
if (Grocy.QuantityUnitEditFormRedirectUri !== undefined)
{ {
redirectDestination = Grocy.QuantityUnitEditFormRedirectUri; $scope = $(scope).find;
} }
if ($(e.currentTarget).attr('data-location') == "continue") import { WindowMessageBag } from '../helpers/messagebag';
{
redirectDestination = "reload";
}
if (Grocy.EditMode === 'create') Grocy.Use("userfieldsform");
{
Grocy.Api.Post('objects/quantity_units', jsonData,
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
if (redirectDestination == "reload") $('.save-quantityunit-button').on('click', function(e)
{
window.location.href = U("/quantityunit/" + result.created_object_id.toString());
}
else if (redirectDestination == "stay")
{
// Do nothing
}
else
{
window.location.href = redirectDestination.replace("editobjectid", Grocy.EditObjectId);
}
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("quantityunit-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{ {
Grocy.Api.Put('objects/quantity_units/' + Grocy.EditObjectId, jsonData, e.preventDefault();
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
if (redirectDestination == "reload") var jsonData = $('#quantityunit-form').serializeJSON();
{ Grocy.FrontendHelpers.BeginUiBusy("quantityunit-form");
window.location.reload();
}
else if (redirectDestination == "stay")
{
// Do nothing
}
else
{
window.location.href = redirectDestination.replace("editobjectid", Grocy.EditObjectId);
}
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("quantityunit-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$('#quantityunit-form input').keyup(function(event) var redirectDestination = U('/quantityunits');
{ if (Grocy.QuantityUnitEditFormRedirectUri !== undefined)
if (!$("#name").val().isEmpty())
{
$("#qu-conversion-headline-info").text(__t('1 %s is the same as...', $("#name").val()));
}
else
{
$("#qu-conversion-headline-info").text("");
}
if (document.getElementById('quantityunit-form').checkValidity() === false) //There is at least one validation error
{
$("#qu-conversion-add-button").addClass("disabled");
}
else
{
$("#qu-conversion-add-button").removeClass("disabled");
}
Grocy.FrontendHelpers.ValidateForm('quantityunit-form');
});
$('#quantityunit-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('quantityunit-form').checkValidity() === false) //There is at least one validation error
{ {
return false; redirectDestination = Grocy.QuantityUnitEditFormRedirectUri;
}
if ($(e.currentTarget).attr('data-location') == "continue")
{
redirectDestination = "reload";
}
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/quantity_units', jsonData,
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
if (redirectDestination == "reload")
{
window.location.href = U("/quantityunit/" + result.created_object_id.toString());
}
else if (redirectDestination == "stay")
{
// Do nothing
}
else
{
window.location.href = redirectDestination.replace("editobjectid", Grocy.EditObjectId);
}
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("quantityunit-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
else else
{ {
$('#save-quantityunit-button').click(); Grocy.Api.Put('objects/quantity_units/' + Grocy.EditObjectId, jsonData,
} function(result)
} {
}); Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
var quConversionsTable = $('#qu-conversions-table').DataTable({ if (redirectDestination == "reload")
'order': [[1, 'asc']], {
'columnDefs': [ window.location.reload();
{ 'orderable': false, 'targets': 0 }, }
{ 'searchable': false, "targets": 0 } else if (redirectDestination == "stay")
].concat($.fn.dataTable.defaults.columnDefs) {
}); // Do nothing
$('#qu-conversions-table tbody').removeClass("d-none"); }
quConversionsTable.columns.adjust().draw(); else
{
Grocy.Components.UserfieldsForm.Load(); window.location.href = redirectDestination.replace("editobjectid", Grocy.EditObjectId);
$("#name").trigger("keyup"); }
$('#name').focus(); }
Grocy.FrontendHelpers.ValidateForm('quantityunit-form'); });
},
Grocy.FrontendHelpers.MakeDeleteConfirmBox( function(xhr)
'Are you sure to remove this conversion?', {
'.qu-conversion-delete-button', Grocy.FrontendHelpers.EndUiBusy("quantityunit-form");
'data-qu-conversion-id', Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
'data-qu-conversion-id', }
'objects/quantity_unit_conversions/', );
() => window.location.reload(),
);
$("#test-quantityunit-plural-forms-button").on("click", function(e)
{
e.preventDefault();
Grocy.QuantityUnitEditFormRedirectUri = "stay";
$("#save-quantityunit-button").click();
bootbox.alert({
message: '<iframe height="400px" class="embed-responsive" src="' + U("/quantityunitpluraltesting?embedded&qu=") + Grocy.EditObjectId.toString() + '"></iframe>',
closeButton: false,
size: "large",
callback: function(result)
{
Grocy.QuantityUnitEditFormRedirectUri = undefined;
Grocy.FrontendHelpers.EndUiBusy("quantityunit-form");
} }
}); });
});
$('#quantityunit-form input').keyup(function(event)
{
if (!$("#name").val().isEmpty())
{
$("#qu-conversion-headline-info").text(__t('1 %s is the same as...', $("#name").val()));
}
else
{
$("#qu-conversion-headline-info").text("");
}
if (document.getElementById('quantityunit-form').checkValidity() === false) //There is at least one validation error
{
$("#qu-conversion-add-button").addClass("disabled");
}
else
{
$("#qu-conversion-add-button").removeClass("disabled");
}
Grocy.FrontendHelpers.ValidateForm('quantityunit-form');
});
$('#quantityunit-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('quantityunit-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-quantityunit-button').click();
}
}
});
var quConversionsTable = $('#qu-conversions-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#qu-conversions-table tbody').removeClass("d-none");
quConversionsTable.columns.adjust().draw();
Grocy.Components.UserfieldsForm.Load();
$("#name").trigger("keyup");
$('#name').focus();
Grocy.FrontendHelpers.ValidateForm('quantityunit-form');
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to remove this conversion?',
'.qu-conversion-delete-button',
'data-qu-conversion-id',
'data-qu-conversion-id',
'objects/quantity_unit_conversions/',
() => window.location.reload(),
);
$("#test-quantityunit-plural-forms-button").on("click", function(e)
{
e.preventDefault();
Grocy.QuantityUnitEditFormRedirectUri = "stay";
$("#save-quantityunit-button").click();
bootbox.alert({
message: '<iframe height="400px" class="embed-responsive" src="' + U("/quantityunitpluraltesting?embedded&qu=") + Grocy.EditObjectId.toString() + '"></iframe>',
closeButton: false,
size: "large",
callback: function(result)
{
Grocy.QuantityUnitEditFormRedirectUri = undefined;
Grocy.FrontendHelpers.EndUiBusy("quantityunit-form");
}
});
});
}

View File

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

View File

@ -1,17 +1,26 @@
var quantityUnitsTable = $('#quantityunits-table').DataTable({ function quantityunitsView(Grocy, scope = null)
'order': [[1, 'asc']], {
'columnDefs': [ var $scope = $;
{ 'orderable': false, 'targets': 0 }, if (scope != null)
{ 'searchable': false, "targets": 0 } {
].concat($.fn.dataTable.defaults.columnDefs) $scope = $(scope).find;
}); }
$('#quantityunits-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(quantityUnitsTable); var quantityUnitsTable = $('#quantityunits-table').DataTable({
Grocy.FrontendHelpers.MakeDeleteConfirmBox( 'order': [[1, 'asc']],
'Are you sure to delete quantity unit "%s"?', 'columnDefs': [
'.quantityunit-delete-button', { 'orderable': false, 'targets': 0 },
'data-quantityunit-name', { 'searchable': false, "targets": 0 }
'data-quantityunit-id', ].concat($.fn.dataTable.defaults.columnDefs)
'objects/quantity_units/', });
'/quantityunits' $('#quantityunits-table tbody').removeClass("d-none");
); Grocy.FrontendHelpers.InitDataTable(quantityUnitsTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete quantity unit "%s"?',
'.quantityunit-delete-button',
'data-quantityunit-name',
'data-quantityunit-id',
'objects/quantity_units/',
'/quantityunits'
);
}

View File

@ -1,336 +1,346 @@
import { WindowMessageBag } from '../helpers/messagebag'; function recipeformView(Grocy, scope = null)
Grocy.Use("numberpicker");
Grocy.Use("recipepicker");
Grocy.Use("userfieldsform");
function saveRecipePicture(result, location, jsonData)
{ {
var recipeId = Grocy.EditObjectId || result.created_object_id; var $scope = $;
Grocy.Components.UserfieldsForm.Save(() => if (scope != null)
{ {
if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteRecipePictureOnSave) $scope = $(scope).find;
}
import { WindowMessageBag } from '../helpers/messagebag';
Grocy.Use("numberpicker");
Grocy.Use("recipepicker");
Grocy.Use("userfieldsform");
function saveRecipePicture(result, location, jsonData)
{
var recipeId = Grocy.EditObjectId || result.created_object_id;
Grocy.Components.UserfieldsForm.Save(() =>
{ {
Grocy.Api.UploadFile($("#recipe-picture")[0].files[0], 'recipepictures', jsonData.picture_file_name, if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteRecipePictureOnSave)
(result) => {
Grocy.Api.UploadFile($("#recipe-picture")[0].files[0], 'recipepictures', jsonData.picture_file_name,
(result) =>
{
window.location.href = U(location + recipeId);
},
(xhr) =>
{
Grocy.FrontendHelpers.EndUiBusy("recipe-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
window.location.href = U(location + recipeId);
}
});
}
$('.save-recipe').on('click', function(e)
{
e.preventDefault();
var jsonData = $('#recipe-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("recipe-form");
if ($("#recipe-picture")[0].files.length > 0)
{
var someRandomStuff = Math.random().toString(36).substring(2, 100) + Math.random().toString(36).substring(2, 100);
jsonData.picture_file_name = someRandomStuff + $("#recipe-picture")[0].files[0].name;
}
const location = $(e.currentTarget).attr('data-location') == 'return' ? '/recipes?recipe=' : '/recipe/';
if (Grocy.EditMode == 'create')
{
Grocy.Api.Post('objects/recipes', jsonData,
(result) => saveRecipePicture(result, location, jsonData));
return;
}
if (Grocy.DeleteRecipePictureOnSave)
{
jsonData.picture_file_name = null;
Grocy.Api.DeleteFile(Grocy.RecipePictureFileName, 'recipepictures', {},
function(result)
{ {
window.location.href = U(location + recipeId); // Nothing to do
}, },
(xhr) => function(xhr)
{ {
Grocy.FrontendHelpers.EndUiBusy("recipe-form"); Grocy.FrontendHelpers.EndUiBusy("recipe-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response) Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
} }
); );
} }
else
{
window.location.href = U(location + recipeId);
}
});
}
$('.save-recipe').on('click', function(e) Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, jsonData,
{ (result) => saveRecipePicture(result, location, jsonData),
e.preventDefault();
var jsonData = $('#recipe-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("recipe-form");
if ($("#recipe-picture")[0].files.length > 0)
{
var someRandomStuff = Math.random().toString(36).substring(2, 100) + Math.random().toString(36).substring(2, 100);
jsonData.picture_file_name = someRandomStuff + $("#recipe-picture")[0].files[0].name;
}
const location = $(e.currentTarget).attr('data-location') == 'return' ? '/recipes?recipe=' : '/recipe/';
if (Grocy.EditMode == 'create')
{
Grocy.Api.Post('objects/recipes', jsonData,
(result) => saveRecipePicture(result, location, jsonData));
return;
}
if (Grocy.DeleteRecipePictureOnSave)
{
jsonData.picture_file_name = null;
Grocy.Api.DeleteFile(Grocy.RecipePictureFileName, 'recipepictures', {},
function(result)
{
// Nothing to do
},
function(xhr) function(xhr)
{ {
Grocy.FrontendHelpers.EndUiBusy("recipe-form"); Grocy.FrontendHelpers.EndUiBusy("recipe-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response) console.error(xhr);
} }
); );
} });
Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, jsonData, var recipesPosTables = $('#recipes-pos-table').DataTable({
(result) => saveRecipePicture(result, location, jsonData), 'order': [[1, 'asc']],
function(xhr) "orderFixed": [[4, 'asc']],
{ 'columnDefs': [
Grocy.FrontendHelpers.EndUiBusy("recipe-form"); { 'orderable': false, 'targets': 0 },
console.error(xhr); { 'searchable': false, "targets": 0 },
{ 'visible': false, 'targets': 4 }
].concat($.fn.dataTable.defaults.columnDefs),
'rowGroup': {
enable: true,
dataSrc: 4
} }
); });
}); $('#recipes-pos-table tbody').removeClass("d-none");
recipesPosTables.columns.adjust().draw();
var recipesPosTables = $('#recipes-pos-table').DataTable({ var recipesIncludesTables = $('#recipes-includes-table').DataTable({
'order': [[1, 'asc']], 'order': [[1, 'asc']],
"orderFixed": [[4, 'asc']], 'columnDefs': [
'columnDefs': [ { 'orderable': false, 'targets': 0 },
{ 'orderable': false, 'targets': 0 }, { 'searchable': false, "targets": 0 }
{ 'searchable': false, "targets": 0 }, ].concat($.fn.dataTable.defaults.columnDefs)
{ 'visible': false, 'targets': 4 } });
].concat($.fn.dataTable.defaults.columnDefs), $('#recipes-includes-table tbody').removeClass("d-none");
'rowGroup': { recipesIncludesTables.columns.adjust().draw();
enable: true,
dataSrc: 4
}
});
$('#recipes-pos-table tbody').removeClass("d-none");
recipesPosTables.columns.adjust().draw();
var recipesIncludesTables = $('#recipes-includes-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#recipes-includes-table tbody').removeClass("d-none");
recipesIncludesTables.columns.adjust().draw();
Grocy.FrontendHelpers.ValidateForm('recipe-form');
$("#name").focus();
$('#recipe-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('recipe-form'); Grocy.FrontendHelpers.ValidateForm('recipe-form');
}); $("#name").focus();
$('#recipe-form input').keydown(function(event) $('#recipe-form input').keyup(function(event)
{
if (event.keyCode === 13) //Enter
{ {
event.preventDefault(); Grocy.FrontendHelpers.ValidateForm('recipe-form');
});
if (document.getElementById('recipe-form').checkValidity() === false) //There is at least one validation error $('#recipe-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{ {
return false; event.preventDefault();
}
else
{
$('#save-recipe-button').click();
}
}
});
Grocy.FrontendHelpers.MakeDeleteConfirmBox( if (document.getElementById('recipe-form').checkValidity() === false) //There is at least one validation error
'Are you sure to delete recipe ingredient "%s"?', {
'.recipe-pos-delete-button', return false;
'data-recipe-pos-name', }
'data-recipe-pos-id', else
'objects/recipes_pos/', {
() => window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl) $('#save-recipe-button').click();
);
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to remove the included recipe "%s"?',
'.recipe-include-delete-button',
'data-recipe-include-name',
'data-recipe-include-id',
'objects/recipes_nesting/',
() => window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl)
);
$(document).on('click', '.recipe-pos-show-note-button', function(e)
{
var note = $(e.currentTarget).attr('data-recipe-pos-note');
bootbox.alert(note);
});
$(document).on('click', '.recipe-pos-edit-button', function(e)
{
e.preventDefault();
var productId = $(e.currentTarget).attr("data-product-id");
var recipePosId = $(e.currentTarget).attr('data-recipe-pos-id');
bootbox.dialog({
message: '<iframe height="650px" class="embed-responsive" src="' + U("/recipe/") + Grocy.EditObjectId.toString() + '/pos/' + recipePosId.toString() + '?embedded&product=' + productId.toString() + '"></iframe>',
size: 'large',
backdrop: true,
closeButton: false,
buttons: {
cancel: {
label: __t('Cancel'),
className: 'btn-secondary responsive-button',
callback: function()
{
bootbox.hideAll();
}
} }
} }
}); });
});
$(document).on('click', '.recipe-include-edit-button', function(e) Grocy.FrontendHelpers.MakeDeleteConfirmBox(
{ 'Are you sure to delete recipe ingredient "%s"?',
var id = $(e.currentTarget).attr('data-recipe-include-id'); '.recipe-pos-delete-button',
var recipeId = $(e.currentTarget).attr('data-recipe-included-recipe-id'); 'data-recipe-pos-name',
var recipeServings = $(e.currentTarget).attr('data-recipe-included-recipe-servings'); 'data-recipe-pos-id',
'objects/recipes_pos/',
Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(), () => window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl)
function(result)
{
$("#recipe-include-editform-title").text(__t("Edit included recipe"));
$("#recipe-include-form").data("edit-mode", "edit");
$("#recipe-include-form").data("recipe-nesting-id", id);
Grocy.Components.RecipePicker.SetId(recipeId);
$("#includes_servings").val(recipeServings);
$("#recipe-include-editform-modal").modal("show");
Grocy.FrontendHelpers.ValidateForm("recipe-include-form");
},
function(xhr)
{
console.error(xhr);
}
); );
});
$("#recipe-pos-add-button").on("click", function(e) Grocy.FrontendHelpers.MakeDeleteConfirmBox(
{ 'Are you sure to remove the included recipe "%s"?',
e.preventDefault(); '.recipe-include-delete-button',
'data-recipe-include-name',
'data-recipe-include-id',
'objects/recipes_nesting/',
() => window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl)
);
bootbox.dialog({ $(document).on('click', '.recipe-pos-show-note-button', function(e)
message: '<iframe height="650px" class="embed-responsive" src="' + U("/recipe/") + Grocy.EditObjectId + '/pos/new?embedded"></iframe>', {
size: 'large', var note = $(e.currentTarget).attr('data-recipe-pos-note');
backdrop: true,
closeButton: false, bootbox.alert(note);
buttons: { });
cancel: {
label: __t('Cancel'), $(document).on('click', '.recipe-pos-edit-button', function(e)
className: 'btn-secondary responsive-button', {
callback: function() e.preventDefault();
{
bootbox.hideAll(); var productId = $(e.currentTarget).attr("data-product-id");
var recipePosId = $(e.currentTarget).attr('data-recipe-pos-id');
bootbox.dialog({
message: '<iframe height="650px" class="embed-responsive" src="' + U("/recipe/") + Grocy.EditObjectId.toString() + '/pos/' + recipePosId.toString() + '?embedded&product=' + productId.toString() + '"></iframe>',
size: 'large',
backdrop: true,
closeButton: false,
buttons: {
cancel: {
label: __t('Cancel'),
className: 'btn-secondary responsive-button',
callback: function()
{
bootbox.hideAll();
}
} }
} }
} });
}); });
});
$("#recipe-include-add-button").on("click", function(e) $(document).on('click', '.recipe-include-edit-button', function(e)
{
Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(),
function(result)
{
$("#recipe-include-editform-title").text(__t("Add included recipe"));
$("#recipe-include-form").data("edit-mode", "create");
Grocy.Components.RecipePicker.Clear();
Grocy.Components.RecipePicker.GetInputElement().focus();
$("#recipe-include-editform-modal").modal("show");
Grocy.FrontendHelpers.ValidateForm("recipe-include-form");
},
function(xhr)
{
console.error(xhr);
}
);
});
$('#save-recipe-include-button').on('click', function(e)
{
e.preventDefault();
if ($(".combobox-menu-visible").length)
{ {
return; var id = $(e.currentTarget).attr('data-recipe-include-id');
} var recipeId = $(e.currentTarget).attr('data-recipe-included-recipe-id');
var recipeServings = $(e.currentTarget).attr('data-recipe-included-recipe-servings');
if (document.getElementById("recipe-include-form").checkValidity() === false) //There is at least one validation error
{
return false;
}
var nestingId = $("#recipe-include-form").data("recipe-nesting-id");
var editMode = $("#recipe-include-form").data("edit-mode");
var jsonData = {};
jsonData.includes_recipe_id = Grocy.Components.RecipePicker.GetValue();
jsonData.servings = $("#includes_servings").val();
jsonData.recipe_id = Grocy.EditObjectId;
if (editMode === 'create')
{
Grocy.Api.Post('objects/recipes_nestings', jsonData,
function(result)
{
window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
},
function(xhr)
{
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/recipes_nestings/' + nestingId, jsonData,
function(result)
{
window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
},
function(xhr)
{
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$("#recipe-picture").on("change", function(e)
{
$("#recipe-picture-label").removeClass("d-none");
$("#recipe-picture-label-none").addClass("d-none");
$("#delete-current-recipe-picture-on-save-hint").addClass("d-none");
$("#current-recipe-picture").addClass("d-none");
Grocy.DeleteRecipePictureOnSave = false;
});
Grocy.DeleteRecipePictureOnSave = false;
$("#delete-current-recipe-picture-button").on("click", function(e)
{
Grocy.DeleteRecipePictureOnSave = true;
$("#current-recipe-picture").addClass("d-none");
$("#delete-current-recipe-picture-on-save-hint").removeClass("d-none");
$("#recipe-picture-label").addClass("d-none");
$("#recipe-picture-label-none").removeClass("d-none");
});
Grocy.Components.UserfieldsForm.Load();
$(window).on("message", function(e)
{
var data = e.originalEvent.data;
if (data.Message === "IngredientsChanged")
{
Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(), Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(),
function(result) function(result)
{ {
window.location.href = U('/recipe/' + Grocy.EditObjectId); $("#recipe-include-editform-title").text(__t("Edit included recipe"));
$("#recipe-include-form").data("edit-mode", "edit");
$("#recipe-include-form").data("recipe-nesting-id", id);
Grocy.Components.RecipePicker.SetId(recipeId);
$("#includes_servings").val(recipeServings);
$("#recipe-include-editform-modal").modal("show");
Grocy.FrontendHelpers.ValidateForm("recipe-include-form");
}, },
function(xhr) function(xhr)
{ {
console.error(xhr); console.error(xhr);
} }
); );
} });
});
$("#recipe-pos-add-button").on("click", function(e)
{
e.preventDefault();
bootbox.dialog({
message: '<iframe height="650px" class="embed-responsive" src="' + U("/recipe/") + Grocy.EditObjectId + '/pos/new?embedded"></iframe>',
size: 'large',
backdrop: true,
closeButton: false,
buttons: {
cancel: {
label: __t('Cancel'),
className: 'btn-secondary responsive-button',
callback: function()
{
bootbox.hideAll();
}
}
}
});
});
$("#recipe-include-add-button").on("click", function(e)
{
Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(),
function(result)
{
$("#recipe-include-editform-title").text(__t("Add included recipe"));
$("#recipe-include-form").data("edit-mode", "create");
Grocy.Components.RecipePicker.Clear();
Grocy.Components.RecipePicker.GetInputElement().focus();
$("#recipe-include-editform-modal").modal("show");
Grocy.FrontendHelpers.ValidateForm("recipe-include-form");
},
function(xhr)
{
console.error(xhr);
}
);
});
$('#save-recipe-include-button').on('click', function(e)
{
e.preventDefault();
if ($(".combobox-menu-visible").length)
{
return;
}
if (document.getElementById("recipe-include-form").checkValidity() === false) //There is at least one validation error
{
return false;
}
var nestingId = $("#recipe-include-form").data("recipe-nesting-id");
var editMode = $("#recipe-include-form").data("edit-mode");
var jsonData = {};
jsonData.includes_recipe_id = Grocy.Components.RecipePicker.GetValue();
jsonData.servings = $("#includes_servings").val();
jsonData.recipe_id = Grocy.EditObjectId;
if (editMode === 'create')
{
Grocy.Api.Post('objects/recipes_nestings', jsonData,
function(result)
{
window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
},
function(xhr)
{
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/recipes_nestings/' + nestingId, jsonData,
function(result)
{
window.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
},
function(xhr)
{
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$("#recipe-picture").on("change", function(e)
{
$("#recipe-picture-label").removeClass("d-none");
$("#recipe-picture-label-none").addClass("d-none");
$("#delete-current-recipe-picture-on-save-hint").addClass("d-none");
$("#current-recipe-picture").addClass("d-none");
Grocy.DeleteRecipePictureOnSave = false;
});
Grocy.DeleteRecipePictureOnSave = false;
$("#delete-current-recipe-picture-button").on("click", function(e)
{
Grocy.DeleteRecipePictureOnSave = true;
$("#current-recipe-picture").addClass("d-none");
$("#delete-current-recipe-picture-on-save-hint").removeClass("d-none");
$("#recipe-picture-label").addClass("d-none");
$("#recipe-picture-label-none").removeClass("d-none");
});
Grocy.Components.UserfieldsForm.Load();
$(window).on("message", function(e)
{
var data = e.originalEvent.data;
if (data.Message === "IngredientsChanged")
{
Grocy.Api.Put('objects/recipes/' + Grocy.EditObjectId, $('#recipe-form').serializeJSON(),
function(result)
{
window.location.href = U('/recipe/' + Grocy.EditObjectId);
},
function(xhr)
{
console.error(xhr);
}
);
}
});
}

View File

@ -1,170 +1,180 @@
import { WindowMessageBag } from '../helpers/messagebag'; function recipeposformView(Grocy, scope = null)
Grocy.Use("numberpicker");
Grocy.Use("productamountpicker");
Grocy.Use("productcard");
Grocy.RecipePosFormInitialLoadDone = false;
$('#save-recipe-pos-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#recipe-pos-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
jsonData.recipe_id = Grocy.EditObjectParentId;
delete jsonData.display_amount;
Grocy.FrontendHelpers.BeginUiBusy("recipe-pos-form"); Grocy.Use("numberpicker");
Grocy.Use("productamountpicker");
Grocy.Use("productcard");
if (Grocy.EditMode === 'create') Grocy.RecipePosFormInitialLoadDone = false;
$('#save-recipe-pos-button').on('click', function(e)
{ {
Grocy.Api.Post('objects/recipes_pos', jsonData, e.preventDefault();
function(result)
{
window.parent.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("recipe-pos-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/recipes_pos/' + Grocy.EditObjectId, jsonData,
function(result)
{
window.parent.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("recipe-pos-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
Grocy.Components.ProductPicker.GetPicker().on('change', function(e) if ($(".combobox-menu-visible").length)
{
var productId = $(e.target).val();
if (productId)
{
Grocy.Components.ProductCard.Refresh(productId);
Grocy.Api.Get('stock/products/' + productId,
function(productDetails)
{
if (!Grocy.RecipePosFormInitialLoadDone)
{
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id, true);
}
else
{
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
}
if (Grocy.Mode == "create")
{
$("#not_check_stock_fulfillment").prop("checked", productDetails.product.not_check_stock_fulfillment_for_recipes == 1);
}
if (!$("#only_check_single_unit_in_stock").prop("checked") && Grocy.RecipePosFormInitialLoadDone)
{
Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.quantity_unit_stock.id);
}
$('#display_amount').focus();
Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
Grocy.RecipePosFormInitialLoadDone = true;
},
function(xhr)
{
console.error(xhr);
}
);
}
});
Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
if (Grocy.Components.ProductPicker.InProductAddWorkflow() === false)
{
Grocy.Components.ProductPicker.GetInputElement().focus();
}
Grocy.Components.ProductPicker.GetPicker().trigger('change');
if (Grocy.EditMode == "create")
{
Grocy.RecipePosFormInitialLoadDone = true;
}
$('#display_amount').on('focus', function(e)
{
if (Grocy.Components.ProductPicker.GetValue().length === 0)
{
Grocy.Components.ProductPicker.GetInputElement().focus();
}
else
{
$(this).select();
}
});
$('#recipe-pos-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
});
$('#qu_id').change(function(event)
{
Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
});
$('#recipe-pos-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('recipe-pos-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return;
}
var jsonData = $('#recipe-pos-form').serializeJSON();
jsonData.recipe_id = Grocy.EditObjectParentId;
delete jsonData.display_amount;
Grocy.FrontendHelpers.BeginUiBusy("recipe-pos-form");
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/recipes_pos', jsonData,
function(result)
{
window.parent.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("recipe-pos-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
else else
{ {
$('#save-recipe-pos-button').click(); Grocy.Api.Put('objects/recipes_pos/' + Grocy.EditObjectId, jsonData,
function(result)
{
window.parent.postMessage(WindowMessageBag("IngredientsChanged"), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("recipe-pos-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
} });
});
$("#only_check_single_unit_in_stock").on("change", function() Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{ {
if (this.checked) var productId = $(e.target).val();
if (productId)
{
Grocy.Components.ProductCard.Refresh(productId);
Grocy.Api.Get('stock/products/' + productId,
function(productDetails)
{
if (!Grocy.RecipePosFormInitialLoadDone)
{
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id, true);
}
else
{
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
}
if (Grocy.Mode == "create")
{
$("#not_check_stock_fulfillment").prop("checked", productDetails.product.not_check_stock_fulfillment_for_recipes == 1);
}
if (!$("#only_check_single_unit_in_stock").prop("checked") && Grocy.RecipePosFormInitialLoadDone)
{
Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.quantity_unit_stock.id);
}
$('#display_amount').focus();
Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
Grocy.RecipePosFormInitialLoadDone = true;
},
function(xhr)
{
console.error(xhr);
}
);
}
});
Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
if (Grocy.Components.ProductPicker.InProductAddWorkflow() === false)
{
Grocy.Components.ProductPicker.GetInputElement().focus();
}
Grocy.Components.ProductPicker.GetPicker().trigger('change');
if (Grocy.EditMode == "create")
{
Grocy.RecipePosFormInitialLoadDone = true;
}
$('#display_amount').on('focus', function(e)
{
if (Grocy.Components.ProductPicker.GetValue().length === 0)
{
Grocy.Components.ProductPicker.GetInputElement().focus();
}
else
{
$(this).select();
}
});
$('#recipe-pos-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
});
$('#qu_id').change(function(event)
{
Grocy.FrontendHelpers.ValidateForm('recipe-pos-form');
});
$('#recipe-pos-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('recipe-pos-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-recipe-pos-button').click();
}
}
});
$("#only_check_single_unit_in_stock").on("change", function()
{
if (this.checked)
{
$("#display_amount").attr("min", Grocy.DefaultMinAmount);
Grocy.Components.ProductAmountPicker.AllowAnyQu(true);
Grocy.FrontendHelpers.ValidateForm("recipe-pos-form");
}
else
{
$("#display_amount").attr("min", "0");
Grocy.Components.ProductPicker.GetPicker().trigger("change"); // Selects the default quantity unit of the selected product
Grocy.Components.ProductAmountPicker.AllowAnyQuEnabled = false;
Grocy.FrontendHelpers.ValidateForm("recipe-pos-form");
}
});
if ($("#only_check_single_unit_in_stock").prop("checked"))
{ {
$("#display_amount").attr("min", Grocy.DefaultMinAmount);
Grocy.Components.ProductAmountPicker.AllowAnyQu(true); Grocy.Components.ProductAmountPicker.AllowAnyQu(true);
Grocy.FrontendHelpers.ValidateForm("recipe-pos-form");
} }
else
{
$("#display_amount").attr("min", "0");
Grocy.Components.ProductPicker.GetPicker().trigger("change"); // Selects the default quantity unit of the selected product
Grocy.Components.ProductAmountPicker.AllowAnyQuEnabled = false;
Grocy.FrontendHelpers.ValidateForm("recipe-pos-form");
}
});
if ($("#only_check_single_unit_in_stock").prop("checked"))
{
Grocy.Components.ProductAmountPicker.AllowAnyQu(true);
} }

View File

@ -1,267 +1,277 @@
Grocy.Use("numberpicker"); function recipesView(Grocy, scope = null)
{
var recipesTables = $('#recipes-table').DataTable({ var $scope = $;
'order': [[1, 'asc']], if (scope != null)
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ "type": "html-num-fmt", "targets": 2 },
].concat($.fn.dataTable.defaults.columnDefs),
select: {
style: 'single',
selector: 'tr td:not(:first-child)'
},
'initComplete': function()
{ {
this.api().row({ order: 'current' }, 0).select(); $scope = $(scope).find;
} }
});
$('#recipes-table tbody').removeClass("d-none"); Grocy.Use("numberpicker");
Grocy.FrontendHelpers.InitDataTable(recipesTables,
function() var recipesTables = $('#recipes-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ "type": "html-num-fmt", "targets": 2 },
].concat($.fn.dataTable.defaults.columnDefs),
select: {
style: 'single',
selector: 'tr td:not(:first-child)'
},
'initComplete': function()
{
this.api().row({ order: 'current' }, 0).select();
}
});
$('#recipes-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(recipesTables,
function()
{
var value = $(this).val();
recipesTables.search(value).draw();
$(".recipe-gallery-item").removeClass("d-none");
$(".recipe-gallery-item .card-title:not(:contains_case_insensitive(" + value + "))").parent().parent().parent().addClass("d-none");
},
function() // custom status filter below
{
$("#search").val("");
$("#status-filter").val("all");
$("#search").trigger("keyup");
$("#status-filter").trigger("change");
})
if ((typeof GetUriParam("tab") !== "undefined" && GetUriParam("tab") === "gallery") || window.localStorage.getItem("recipes_last_tab_id") == "gallery-tab")
{
$(".nav-tabs a[href='#gallery']").tab("show");
}
var recipe = GetUriParam("recipe");
if (typeof recipe !== "undefined")
{
$("#recipes-table tr").removeClass("selected");
var rowId = "#recipe-row-" + recipe;
$(rowId).addClass("selected")
var cardId = "#RecipeGalleryCard-" + recipe;
$(cardId).addClass("border-primary");
if ($(window).width() < 768)
{
// Scroll to recipe card on mobile
$("#selectedRecipeCard")[0].scrollIntoView();
}
}
if (GetUriParam("search") !== undefined)
{
$("#search").val(GetUriParam("search"));
setTimeout(function()
{
$("#search").keyup();
}, 50);
}
$("a[data-toggle='tab']").on("shown.bs.tab", function(e)
{
var tabId = $(e.target).attr("id");
window.localStorage.setItem("recipes_last_tab_id", tabId);
});
$("#status-filter").on("change", function()
{ {
var value = $(this).val(); var value = $(this).val();
if (value === "all")
recipesTables.search(value).draw();
$(".recipe-gallery-item").removeClass("d-none");
$(".recipe-gallery-item .card-title:not(:contains_case_insensitive(" + value + "))").parent().parent().parent().addClass("d-none");
},
function() // custom status filter below
{
$("#search").val("");
$("#status-filter").val("all");
$("#search").trigger("keyup");
$("#status-filter").trigger("change");
})
if ((typeof GetUriParam("tab") !== "undefined" && GetUriParam("tab") === "gallery") || window.localStorage.getItem("recipes_last_tab_id") == "gallery-tab")
{
$(".nav-tabs a[href='#gallery']").tab("show");
}
var recipe = GetUriParam("recipe");
if (typeof recipe !== "undefined")
{
$("#recipes-table tr").removeClass("selected");
var rowId = "#recipe-row-" + recipe;
$(rowId).addClass("selected")
var cardId = "#RecipeGalleryCard-" + recipe;
$(cardId).addClass("border-primary");
if ($(window).width() < 768)
{
// Scroll to recipe card on mobile
$("#selectedRecipeCard")[0].scrollIntoView();
}
}
if (GetUriParam("search") !== undefined)
{
$("#search").val(GetUriParam("search"));
setTimeout(function()
{
$("#search").keyup();
}, 50);
}
$("a[data-toggle='tab']").on("shown.bs.tab", function(e)
{
var tabId = $(e.target).attr("id");
window.localStorage.setItem("recipes_last_tab_id", tabId);
});
$("#status-filter").on("change", function()
{
var value = $(this).val();
if (value === "all")
{
value = "";
}
recipesTables.column(5).search(value).draw();
$('.recipe-gallery-item').removeClass('d-none');
if (value !== "")
{
if (value === 'Xenoughinstock')
{ {
$('.recipe-gallery-item').not('.recipe-enoughinstock').addClass('d-none'); value = "";
} }
else if (value === 'enoughinstockwithshoppinglist')
{
$('.recipe-gallery-item').not('.recipe-enoughinstockwithshoppinglist').addClass('d-none');
}
if (value === 'notenoughinstock')
{
$('.recipe-gallery-item').not('.recipe-notenoughinstock').addClass('d-none');
}
}
});
Grocy.FrontendHelpers.MakeDeleteConfirmBox( recipesTables.column(5).search(value).draw();
'Are you sure to delete recipe "%s"?',
'.recipe-delete',
'data-recipe-name',
'data-recipe-id',
'objects/recipes/',
'/recipes'
);
Grocy.FrontendHelpers.MakeYesNoBox( $('.recipe-gallery-item').removeClass('d-none');
(e) => if (value !== "")
{
var objectName = $(e.currentTarget).attr('data-recipe-name');
return __t('Are you sure to put all missing ingredients for recipe "%s" on the shopping list?', objectName) +
"<br><br>" +
__t("Uncheck ingredients to not put them on the shopping list") +
":" +
$("#missing-recipe-pos-list")[0].outerHTML.replace("d-none", "");
},
'.recipe-shopping-list',
(result, e) =>
{
var objectId = $(e.currentTarget).attr('data-recipe-id');
if (result === true)
{ {
Grocy.FrontendHelpers.BeginUiBusy(); if (value === 'Xenoughinstock')
var excludedProductIds = new Array();
$(".missing-recipe-pos-product-checkbox:checkbox:not(:checked)").each(function()
{ {
excludedProductIds.push($(this).data("product-id")); $('.recipe-gallery-item').not('.recipe-enoughinstock').addClass('d-none');
}); }
else if (value === 'enoughinstockwithshoppinglist')
Grocy.Api.Post('recipes/' + objectId + '/add-not-fulfilled-products-to-shoppinglist', { "excludedProductIds": excludedProductIds }, {
function(result) $('.recipe-gallery-item').not('.recipe-enoughinstockwithshoppinglist').addClass('d-none');
{ }
window.location.href = U('/recipes'); if (value === 'notenoughinstock')
}, {
function(xhr) $('.recipe-gallery-item').not('.recipe-notenoughinstock').addClass('d-none');
{ }
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
} }
} });
);
Grocy.FrontendHelpers.MakeYesNoBox( Grocy.FrontendHelpers.MakeDeleteConfirmBox(
(e) => 'Are you sure to delete recipe "%s"?',
{ '.recipe-delete',
var objectName = $(e.currentTarget).attr('data-recipe-name'); 'data-recipe-name',
return __t('Are you sure to consume all ingredients needed by recipe "%s" (ingredients marked with "only check if any amount is in stock" will be ignored)?', objectName); 'data-recipe-id',
}, 'objects/recipes/',
'.recipe-consume', '/recipes'
(result, e) => );
{
var target = $(e.currentTarget); Grocy.FrontendHelpers.MakeYesNoBox(
var objectName = target.attr('data-recipe-name'); (e) =>
var objectId = target.attr('data-recipe-id');
if (result === true)
{ {
Grocy.FrontendHelpers.BeginUiBusy(); var objectName = $(e.currentTarget).attr('data-recipe-name');
return __t('Are you sure to put all missing ingredients for recipe "%s" on the shopping list?', objectName) +
Grocy.Api.Post('recipes/' + objectId + '/consume', {}, "<br><br>" +
function(result) __t("Uncheck ingredients to not put them on the shopping list") +
{ ":" +
Grocy.FrontendHelpers.EndUiBusy(); $("#missing-recipe-pos-list")[0].outerHTML.replace("d-none", "");
toastr.success(__t('Removed all ingredients of recipe "%s" from stock', objectName));
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
toastr.warning(__t('Not all ingredients of recipe "%s" are in stock, nothing removed', objectName));
console.error(xhr);
}
);
}
}
);
recipesTables.on('select', function(e, dt, type, indexes)
{
if (type === 'row')
{
var selectedRecipeId = $(recipesTables.row(indexes[0]).node()).data("recipe-id");
var currentRecipeId = window.location.search.split('recipe=')[1];
if (selectedRecipeId.toString() !== currentRecipeId)
{
window.location.href = U('/recipes?recipe=' + selectedRecipeId.toString());
}
}
});
$(".recipe-gallery-item").on("click", function(e)
{
e.preventDefault();
window.location.href = U('/recipes?tab=gallery&recipe=' + $(this).data("recipe-id"));
});
$(".recipe-fullscreen").on('click', function(e)
{
e.preventDefault();
$("#selectedRecipeCard").toggleClass("fullscreen");
$("body").toggleClass("fullscreen-card");
$("#selectedRecipeCard .card-header").toggleClass("fixed-top");
$("#selectedRecipeCard .card-body").toggleClass("mt-5");
if ($("body").hasClass("fullscreen-card"))
{
window.location.hash = "#fullscreen";
}
else
{
window.history.replaceState(null, null, " ");
}
});
$(".recipe-print").on('click', function(e)
{
e.preventDefault();
$("#selectedRecipeCard").removeClass("fullscreen");
$("body").removeClass("fullscreen-card");
$("#selectedRecipeCard .card-header").removeClass("fixed-top");
$("#selectedRecipeCard .card-body").removeClass("mt-5");
window.history.replaceState(null, null, " ");
window.print();
});
$('#servings-scale').keyup(function(event)
{
var data = {};
data.desired_servings = $(this).val();
Grocy.Api.Put('objects/recipes/' + $(this).data("recipe-id"), data,
function(result)
{
window.location.reload();
}, },
function(xhr) '.recipe-shopping-list',
(result, e) =>
{ {
console.error(xhr); var objectId = $(e.currentTarget).attr('data-recipe-id');
if (result === true)
{
Grocy.FrontendHelpers.BeginUiBusy();
var excludedProductIds = new Array();
$(".missing-recipe-pos-product-checkbox:checkbox:not(:checked)").each(function()
{
excludedProductIds.push($(this).data("product-id"));
});
Grocy.Api.Post('recipes/' + objectId + '/add-not-fulfilled-products-to-shoppinglist', { "excludedProductIds": excludedProductIds },
function(result)
{
window.location.href = U('/recipes');
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
}
} }
); );
});
$(document).on("click", ".missing-recipe-pos-select-button", function(e) Grocy.FrontendHelpers.MakeYesNoBox(
{ (e) =>
e.preventDefault(); {
var objectName = $(e.currentTarget).attr('data-recipe-name');
return __t('Are you sure to consume all ingredients needed by recipe "%s" (ingredients marked with "only check if any amount is in stock" will be ignored)?', objectName);
},
'.recipe-consume',
(result, e) =>
{
var target = $(e.currentTarget);
var objectName = target.attr('data-recipe-name');
var objectId = target.attr('data-recipe-id');
if (result === true)
{
Grocy.FrontendHelpers.BeginUiBusy();
var checkbox = $(this).find(".form-check-input"); Grocy.Api.Post('recipes/' + objectId + '/consume', {},
checkbox.prop("checked", !checkbox.prop("checked")); function(result)
{
Grocy.FrontendHelpers.EndUiBusy();
toastr.success(__t('Removed all ingredients of recipe "%s" from stock', objectName));
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
toastr.warning(__t('Not all ingredients of recipe "%s" are in stock, nothing removed', objectName));
console.error(xhr);
}
);
}
}
);
$(this).toggleClass("list-group-item-primary"); recipesTables.on('select', function(e, dt, type, indexes)
}); {
if (type === 'row')
{
var selectedRecipeId = $(recipesTables.row(indexes[0]).node()).data("recipe-id");
var currentRecipeId = window.location.search.split('recipe=')[1];
if (selectedRecipeId.toString() !== currentRecipeId)
{
window.location.href = U('/recipes?recipe=' + selectedRecipeId.toString());
}
}
});
$(".recipe-gallery-item").on("click", function(e)
{
e.preventDefault();
window.location.href = U('/recipes?tab=gallery&recipe=' + $(this).data("recipe-id"));
});
$(".recipe-fullscreen").on('click', function(e)
{
e.preventDefault();
$("#selectedRecipeCard").toggleClass("fullscreen");
$("body").toggleClass("fullscreen-card");
$("#selectedRecipeCard .card-header").toggleClass("fixed-top");
$("#selectedRecipeCard .card-body").toggleClass("mt-5");
if ($("body").hasClass("fullscreen-card"))
{
window.location.hash = "#fullscreen";
}
else
{
window.history.replaceState(null, null, " ");
}
});
$(".recipe-print").on('click', function(e)
{
e.preventDefault();
$("#selectedRecipeCard").removeClass("fullscreen");
$("body").removeClass("fullscreen-card");
$("#selectedRecipeCard .card-header").removeClass("fixed-top");
$("#selectedRecipeCard .card-body").removeClass("mt-5");
window.history.replaceState(null, null, " ");
window.print();
});
$('#servings-scale').keyup(function(event)
{
var data = {};
data.desired_servings = $(this).val();
Grocy.Api.Put('objects/recipes/' + $(this).data("recipe-id"), data,
function(result)
{
window.location.reload();
},
function(xhr)
{
console.error(xhr);
}
);
});
$(document).on("click", ".missing-recipe-pos-select-button", function(e)
{
e.preventDefault();
var checkbox = $(this).find(".form-check-input");
checkbox.prop("checked", !checkbox.prop("checked"));
$(this).toggleClass("list-group-item-primary");
});
if (window.location.hash === "#fullscreen")
{
$("#selectedRecipeToggleFullscreenButton").click();
}
if (window.location.hash === "#fullscreen")
{
$("#selectedRecipeToggleFullscreenButton").click();
} }

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -1,49 +1,39 @@
import { WindowMessageBag } from '../helpers/messagebag'; function shoppinglistformView(Grocy, scope = null)
Grocy.Use("userfieldsform");
$('#save-shopping-list-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#shopping-list-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
Grocy.FrontendHelpers.BeginUiBusy("shopping-list-form");
if (Grocy.EditMode === 'create') Grocy.Use("userfieldsform");
$('#save-shopping-list-button').on('click', function(e)
{ {
Grocy.Api.Post('objects/shopping_lists', jsonData, e.preventDefault();
function(result)
{ if ($(".combobox-menu-visible").length)
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
window.parent.postMessage(WindowMessageBag("ShoppingListChanged", result.created_object_id), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("Ready"), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("shopping-list-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
}
);
}
else
{
Grocy.Components.UserfieldsForm.Save(function()
{ {
Grocy.Api.Put('objects/shopping_lists/' + Grocy.EditObjectId, jsonData, return;
}
var jsonData = $('#shopping-list-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("shopping-list-form");
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/shopping_lists', jsonData,
function(result) function(result)
{ {
window.parent.postMessage(WindowMessageBag("ShoppingListChanged", Grocy.EditObjectId), Grocy.BaseUrl); Grocy.EditObjectId = result.created_object_id;
window.parent.postMessage(WindowMessageBag("Ready"), Grocy.BaseUrl); Grocy.Components.UserfieldsForm.Save(function()
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl); {
window.parent.postMessage(WindowMessageBag("ShoppingListChanged", result.created_object_id), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("Ready"), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
});
}, },
function(xhr) function(xhr)
{ {
@ -51,32 +41,52 @@ $('#save-shopping-list-button').on('click', function(e)
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response); Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
} }
); );
});
}
});
$('#shopping-list-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('shopping-list-form');
});
$('#shopping-list-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('shopping-list-form').checkValidity() === false) //There is at least one validation error
{
return false;
} }
else else
{ {
$('#save-shopping-list-button').click(); Grocy.Components.UserfieldsForm.Save(function()
{
Grocy.Api.Put('objects/shopping_lists/' + Grocy.EditObjectId, jsonData,
function(result)
{
window.parent.postMessage(WindowMessageBag("ShoppingListChanged", Grocy.EditObjectId), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("Ready"), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("shopping-list-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
}
);
});
} }
} });
});
Grocy.Components.UserfieldsForm.Load(); $('#shopping-list-form input').keyup(function(event)
$('#name').focus(); {
Grocy.FrontendHelpers.ValidateForm('shopping-list-form'); Grocy.FrontendHelpers.ValidateForm('shopping-list-form');
});
$('#shopping-list-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('shopping-list-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-shopping-list-button').click();
}
}
});
Grocy.Components.UserfieldsForm.Load();
$('#name').focus();
Grocy.FrontendHelpers.ValidateForm('shopping-list-form');
}

View File

@ -1,271 +1,281 @@
import { WindowMessageBag } from '../helpers/messagebag'; function shoppinglistitemformView(Grocy, scope = null)
Grocy.Use("productamountpicker");
Grocy.Use("userfieldsform");
Grocy.ShoppingListItemFormInitialLoadDone = false;
$('#save-shoppinglist-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#shoppinglist-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
if (!jsonData.product_id)
Grocy.Use("productamountpicker");
Grocy.Use("userfieldsform");
Grocy.ShoppingListItemFormInitialLoadDone = false;
$('#save-shoppinglist-button').on('click', function(e)
{ {
jsonData.amount = jsonData.display_amount; e.preventDefault();
}
delete jsonData.display_amount;
Grocy.FrontendHelpers.BeginUiBusy("shoppinglist-form"); if ($(".combobox-menu-visible").length)
{
return;
}
if (GetUriParam("updateexistingproduct") !== undefined) var jsonData = $('#shoppinglist-form').serializeJSON();
{ if (!jsonData.product_id)
jsonData.product_amount = jsonData.amount; {
delete jsonData.amount; jsonData.amount = jsonData.display_amount;
}
delete jsonData.display_amount;
Grocy.Api.Post('stock/shoppinglist/add-product', jsonData, Grocy.FrontendHelpers.BeginUiBusy("shoppinglist-form");
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save();
if (GetUriParam("embedded") !== undefined) if (GetUriParam("updateexistingproduct") !== undefined)
{
jsonData.product_amount = jsonData.amount;
delete jsonData.amount;
Grocy.Api.Post('stock/shoppinglist/add-product', jsonData,
function(result)
{ {
Grocy.Api.Get('stock/products/' + jsonData.product_id, Grocy.EditObjectId = result.created_object_id;
function(productDetails) Grocy.Components.UserfieldsForm.Save();
if (GetUriParam("embedded") !== undefined)
{
Grocy.Api.Get('stock/products/' + jsonData.product_id,
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("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
},
function(xhr)
{
console.error(xhr);
}
);
}
else
{
window.location.href = U('/shoppinglist?list=' + $("#shopping_list_id").val().toString());
}
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("shoppinglist-form");
console.error(xhr);
}
);
}
else if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/shopping_list', jsonData,
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save();
if (GetUriParam("embedded") !== undefined)
{
if (jsonData.product_id)
{
Grocy.Api.Get('stock/products/' + jsonData.product_id,
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("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
},
function(xhr)
{
console.error(xhr);
}
);
}
else
{ {
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("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl); window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
},
function(xhr)
{
console.error(xhr);
} }
);
}
else
{
window.location.href = U('/shoppinglist?list=' + $("#shopping_list_id").val().toString());
}
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("shoppinglist-form");
console.error(xhr);
}
);
}
else if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/shopping_list', jsonData,
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save();
if (GetUriParam("embedded") !== undefined)
{
if (jsonData.product_id)
{
Grocy.Api.Get('stock/products/' + jsonData.product_id,
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("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
},
function(xhr)
{
console.error(xhr);
}
);
} }
else else
{ {
window.parent.postMessage(WindowMessageBag("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl); window.location.href = U('/shoppinglist?list=' + $("#shopping_list_id").val().toString());
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
} }
} },
else function(xhr)
{ {
window.location.href = U('/shoppinglist?list=' + $("#shopping_list_id").val().toString()); Grocy.FrontendHelpers.EndUiBusy("shoppinglist-form");
console.error(xhr);
} }
}, );
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("shoppinglist-form");
console.error(xhr);
}
);
}
else
{
Grocy.Api.Put('objects/shopping_list/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save();
if (GetUriParam("embedded") !== undefined)
{
if (jsonData.product_id)
{
Grocy.Api.Get('stock/products/' + jsonData.product_id,
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("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
},
function(xhr)
{
console.error(xhr);
}
);
}
else
{
window.parent.postMessage(WindowMessageBag("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
}
}
else
{
window.location.href = U('/shoppinglist?list=' + $("#shopping_list_id").val().toString());
}
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("shoppinglist-form");
console.error(xhr);
}
);
}
});
Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{
var productId = $(e.target).val();
if (productId)
{
Grocy.Api.Get('stock/products/' + productId,
function(productDetails)
{
if (!Grocy.ShoppingListItemFormInitialLoadDone)
{
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id, true);
}
else
{
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.default_quantity_unit_purchase.id);
}
if ($("#display_amount").val().toString().isEmpty())
{
$("#display_amount").val(1);
$("#display_amount").trigger("change");
}
$('#display_amount').focus();
Grocy.FrontendHelpers.ValidateForm('shoppinglist-form');
Grocy.ShoppingListItemFormInitialLoadDone = true;
},
function(xhr)
{
console.error(xhr);
}
);
}
$("#note").trigger("input");
$("#product_id").trigger("input");
});
Grocy.FrontendHelpers.ValidateForm('shoppinglist-form');
Grocy.Components.ProductPicker.GetInputElement().focus();
if (Grocy.EditMode === "edit")
{
Grocy.Components.ProductPicker.GetPicker().trigger('change');
}
if (Grocy.EditMode == "create")
{
Grocy.ShoppingListItemFormInitialLoadDone = true;
}
$('#display_amount').on('focus', function(e)
{
$(this).select();
});
$('#shoppinglist-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('shoppinglist-form');
});
$('#shoppinglist-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('shoppinglist-form').checkValidity() === false) //There is at least one validation error
{
return false;
} }
else else
{ {
$('#save-shoppinglist-button').click(); Grocy.Api.Put('objects/shopping_list/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save();
if (GetUriParam("embedded") !== undefined)
{
if (jsonData.product_id)
{
Grocy.Api.Get('stock/products/' + jsonData.product_id,
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("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
},
function(xhr)
{
console.error(xhr);
}
);
}
else
{
window.parent.postMessage(WindowMessageBag("ShoppingListChanged", $("#shopping_list_id").val().toString()), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
}
}
else
{
window.location.href = U('/shoppinglist?list=' + $("#shopping_list_id").val().toString());
}
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("shoppinglist-form");
console.error(xhr);
}
);
} }
} });
});
if (GetUriParam("list") !== undefined) Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{ {
$("#shopping_list_id").val(GetUriParam("list")); var productId = $(e.target).val();
}
if (productId)
{
Grocy.Api.Get('stock/products/' + productId,
function(productDetails)
{
if (!Grocy.ShoppingListItemFormInitialLoadDone)
{
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id, true);
}
else
{
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.default_quantity_unit_purchase.id);
}
if ($("#display_amount").val().toString().isEmpty())
{
$("#display_amount").val(1);
$("#display_amount").trigger("change");
}
$('#display_amount').focus();
Grocy.FrontendHelpers.ValidateForm('shoppinglist-form');
Grocy.ShoppingListItemFormInitialLoadDone = true;
},
function(xhr)
{
console.error(xhr);
}
);
}
$("#note").trigger("input");
$("#product_id").trigger("input");
});
if (GetUriParam("amount") !== undefined)
{
$("#display_amount").val(parseFloat(GetUriParam("amount")));
RefreshLocaleNumberInput();
$(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('shoppinglist-form'); Grocy.FrontendHelpers.ValidateForm('shoppinglist-form');
} Grocy.Components.ProductPicker.GetInputElement().focus();
if (GetUriParam("embedded") !== undefined) if (Grocy.EditMode === "edit")
{
if (GetUriParam("product") !== undefined)
{ {
Grocy.Components.ProductPicker.GetPicker().trigger('change'); Grocy.Components.ProductPicker.GetPicker().trigger('change');
$("#display_amount").focus();
} }
else
if (Grocy.EditMode == "create")
{ {
Grocy.Components.ProductPicker.GetInputElement().focus(); Grocy.ShoppingListItemFormInitialLoadDone = true;
} }
$('#display_amount').on('focus', function(e)
{
$(this).select();
});
$('#shoppinglist-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('shoppinglist-form');
});
$('#shoppinglist-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('shoppinglist-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-shoppinglist-button').click();
}
}
});
if (GetUriParam("list") !== undefined)
{
$("#shopping_list_id").val(GetUriParam("list"));
}
if (GetUriParam("amount") !== undefined)
{
$("#display_amount").val(parseFloat(GetUriParam("amount")));
RefreshLocaleNumberInput();
$(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('shoppinglist-form');
}
if (GetUriParam("embedded") !== undefined)
{
if (GetUriParam("product") !== undefined)
{
Grocy.Components.ProductPicker.GetPicker().trigger('change');
$("#display_amount").focus();
}
else
{
Grocy.Components.ProductPicker.GetInputElement().focus();
}
}
var eitherRequiredFields = $("#product_id,#product_id_text_input,#note");
eitherRequiredFields.prop('required', "");
eitherRequiredFields.on('input', function()
{
eitherRequiredFields.not(this).prop('required', !$(this).val().length);
Grocy.FrontendHelpers.ValidateForm('shoppinglist-form');
});
if (GetUriParam("product-name") != null)
{
Grocy.Components.ProductPicker.GetPicker().trigger('change');
}
Grocy.Components.UserfieldsForm.Load();
} }
var eitherRequiredFields = $("#product_id,#product_id_text_input,#note");
eitherRequiredFields.prop('required', "");
eitherRequiredFields.on('input', function()
{
eitherRequiredFields.not(this).prop('required', !$(this).val().length);
Grocy.FrontendHelpers.ValidateForm('shoppinglist-form');
});
if (GetUriParam("product-name") != null)
{
Grocy.Components.ProductPicker.GetPicker().trigger('change');
}
Grocy.Components.UserfieldsForm.Load();

View File

@ -1,13 +1,23 @@
import { BoolVal } from '../helpers/extensions'; function shoppinglistsettingsView(Grocy, scope = null)
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); var $scope = $;
} if (scope != null)
{
$scope = $(scope).find;
}
if (BoolVal(Grocy.UserSettings.shopping_list_show_calendar)) import { BoolVal } from '../helpers/extensions';
{
$("#shopping-list-show-calendar").prop("checked", true);
}
RefreshLocaleNumberInput(); 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);
}
if (BoolVal(Grocy.UserSettings.shopping_list_show_calendar))
{
$("#shopping-list-show-calendar").prop("checked", true);
}
RefreshLocaleNumberInput();
}

View File

@ -1,92 +1,102 @@
import { WindowMessageBag } from '../helpers/messagebag'; function shoppinglocationformView(Grocy, scope = null)
Grocy.Use("userfieldsform");
$('#save-shopping-location-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#shoppinglocation-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
Grocy.FrontendHelpers.BeginUiBusy("shoppinglocation-form");
if (Grocy.EditMode === 'create') Grocy.Use("userfieldsform");
$('#save-shopping-location-button').on('click', function(e)
{ {
Grocy.Api.Post('objects/shopping_locations', jsonData, e.preventDefault();
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/shoppinglocations');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("shoppinglocation-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/shopping_locations/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/shoppinglocations');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("shoppinglocation-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$('#shoppinglocation-form input').keyup(function(event) if ($(".combobox-menu-visible").length)
{
Grocy.FrontendHelpers.ValidateForm('shoppinglocation-form');
});
$('#shoppinglocation-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('shoppinglocation-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return;
}
var jsonData = $('#shoppinglocation-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("shoppinglocation-form");
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/shopping_locations', jsonData,
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/shoppinglocations');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("shoppinglocation-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
else else
{ {
$('#save-shopping-location-button').click(); Grocy.Api.Put('objects/shopping_locations/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/shoppinglocations');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("shoppinglocation-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
} });
});
Grocy.Components.UserfieldsForm.Load(); $('#shoppinglocation-form input').keyup(function(event)
$('#name').focus(); {
Grocy.FrontendHelpers.ValidateForm('shoppinglocation-form'); Grocy.FrontendHelpers.ValidateForm('shoppinglocation-form');
});
$('#shoppinglocation-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('shoppinglocation-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-shopping-location-button').click();
}
}
});
Grocy.Components.UserfieldsForm.Load();
$('#name').focus();
Grocy.FrontendHelpers.ValidateForm('shoppinglocation-form');
}

View File

@ -1,18 +1,27 @@
var locationsTable = $('#shoppinglocations-table').DataTable({ function shoppinglocationsView(Grocy, scope = null)
'order': [[1, 'asc']], {
'columnDefs': [ var $scope = $;
{ 'orderable': false, 'targets': 0 }, if (scope != null)
{ 'searchable': false, "targets": 0 } {
].concat($.fn.dataTable.defaults.columnDefs) $scope = $(scope).find;
}); }
$('#shoppinglocations-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(locationsTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox( var locationsTable = $('#shoppinglocations-table').DataTable({
'Are you sure to delete store "%s"?', 'order': [[1, 'asc']],
'.shoppinglocation-delete-button', 'columnDefs': [
'data-shoppinglocation-name', { 'orderable': false, 'targets': 0 },
'data-shoppinglocation-id', { 'searchable': false, "targets": 0 }
'objects/shopping_locations/', ].concat($.fn.dataTable.defaults.columnDefs)
'/shoppinglocations' });
); $('#shoppinglocations-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(locationsTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete store "%s"?',
'.shoppinglocation-delete-button',
'data-shoppinglocation-name',
'data-shoppinglocation-id',
'objects/shopping_locations/',
'/shoppinglocations'
);
}

View File

@ -1,276 +1,286 @@
Grocy.Use("productcard"); function stockentriesView(Grocy, scope = null)
Grocy.Use("productpicker");
var stockEntriesTable = $('#stockentries-table').DataTable({
'order': [[2, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#stockentries-table tbody').removeClass("d-none");
stockEntriesTable.columns.adjust().draw();
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex)
{ {
var productId = Grocy.Components.ProductPicker.GetValue(); var $scope = $;
if (scope != null)
if ((isNaN(productId) || productId == "" || productId == data[1]))
{ {
return true; $scope = $(scope).find;
} }
return false; Grocy.Use("productcard");
}); Grocy.Use("productpicker");
$("#clear-filter-button").on("click", function() var stockEntriesTable = $('#stockentries-table').DataTable({
{ 'order': [[2, 'asc']],
Grocy.Components.ProductPicker.Clear(); 'columnDefs': [
stockEntriesTable.draw(); { 'orderable': false, 'targets': 0 },
}); { 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{
stockEntriesTable.draw();
});
Grocy.Components.ProductPicker.GetInputElement().on('keyup', function(e)
{
stockEntriesTable.draw();
});
$(document).on('click', '.stock-consume-button', function(e)
{
e.preventDefault();
// Remove the focus from the current button
// to prevent that the tooltip stays until clicked anywhere else
document.activeElement.blur();
Grocy.FrontendHelpers.BeginUiBusy();
var productId = $(e.currentTarget).attr('data-product-id');
var locationId = $(e.currentTarget).attr('data-location-id');
var specificStockEntryId = $(e.currentTarget).attr('data-stock-id');
var stockRowId = $(e.currentTarget).attr('data-stockrow-id');
var consumeAmount = $(e.currentTarget).attr('data-consume-amount');
var wasSpoiled = $(e.currentTarget).hasClass("stock-consume-button-spoiled");
Grocy.Api.Post('stock/products/' + productId + '/consume', { 'amount': consumeAmount, 'spoiled': wasSpoiled, 'location_id': locationId, 'stock_entry_id': specificStockEntryId, 'exact_amount': true },
function(bookingResponse)
{
Grocy.Api.Get('stock/products/' + productId,
function(result)
{
var 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.UndoStockBookingEntry(' + bookingResponse.id + ',' + stockRowId + ')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>';
if (wasSpoiled)
{
toastMessage += " (" + __t("Spoiled") + ")";
}
Grocy.FrontendHelpers.EndUiBusy();
RefreshStockEntryRow(stockRowId);
toastr.success(toastMessage);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
$(document).on('click', '.product-open-button', function(e)
{
e.preventDefault();
// Remove the focus from the current button
// to prevent that the tooltip stays until clicked anywhere else
document.activeElement.blur();
Grocy.FrontendHelpers.BeginUiBusy();
var productId = $(e.currentTarget).attr('data-product-id');
var productName = $(e.currentTarget).attr('data-product-name');
var productQuName = $(e.currentTarget).attr('data-product-qu-name');
var specificStockEntryId = $(e.currentTarget).attr('data-stock-id');
var stockRowId = $(e.currentTarget).attr('data-stockrow-id');
var button = $(e.currentTarget);
Grocy.Api.Post('stock/products/' + productId + '/open', { 'amount': 1, 'stock_entry_id': specificStockEntryId },
function(bookingResponse)
{
button.addClass("disabled");
Grocy.FrontendHelpers.EndUiBusy();
toastr.success(__t('Marked %1$s of %2$s as opened', 1 + " " + productQuName, productName) + '<br><a class="btn btn-secondary btn-sm mt-2" href="#" onclick="Grocy.UndoStockBookingEntry(' + bookingResponse.id + ',' + stockRowId + ')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>');
RefreshStockEntryRow(stockRowId);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
$(document).on("click", ".stock-name-cell", function(e)
{
Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-stock-id"));
$("#stockentry-productcard-modal").modal("show");
});
$(document).on('click', '.stockentry-grocycode-stockentry-label-print', function(e)
{
e.preventDefault();
document.activeElement.blur();
var stockId = $(e.currentTarget).attr('data-stock-id');
Grocy.Api.Get('stock/entry/' + stockId + '/printlabel', function(labelData)
{
if (Grocy.Webhooks.labelprinter !== undefined)
{
Grocy.FrontendHelpers.RunWebhook(Grocy.Webhooks.labelprinter, labelData);
}
}); });
}); $('#stockentries-table tbody').removeClass("d-none");
stockEntriesTable.columns.adjust().draw();
function RefreshStockEntryRow(stockRowId) $.fn.dataTable.ext.search.push(function(settings, data, dataIndex)
{ {
Grocy.Api.Get("stock/entry/" + stockRowId, var productId = Grocy.Components.ProductPicker.GetValue();
function(result)
if ((isNaN(productId) || productId == "" || productId == data[1]))
{ {
var stockRow = $('#stock-' + stockRowId + '-row'); return true;
}
// 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 return false;
if (!stockRow.length || stockRow.hasClass("d-none")) });
$("#clear-filter-button").on("click", function()
{
Grocy.Components.ProductPicker.Clear();
stockEntriesTable.draw();
});
Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{
stockEntriesTable.draw();
});
Grocy.Components.ProductPicker.GetInputElement().on('keyup', function(e)
{
stockEntriesTable.draw();
});
$(document).on('click', '.stock-consume-button', function(e)
{
e.preventDefault();
// Remove the focus from the current button
// to prevent that the tooltip stays until clicked anywhere else
document.activeElement.blur();
Grocy.FrontendHelpers.BeginUiBusy();
var productId = $(e.currentTarget).attr('data-product-id');
var locationId = $(e.currentTarget).attr('data-location-id');
var specificStockEntryId = $(e.currentTarget).attr('data-stock-id');
var stockRowId = $(e.currentTarget).attr('data-stockrow-id');
var consumeAmount = $(e.currentTarget).attr('data-consume-amount');
var wasSpoiled = $(e.currentTarget).hasClass("stock-consume-button-spoiled");
Grocy.Api.Post('stock/products/' + productId + '/consume', { 'amount': consumeAmount, 'spoiled': wasSpoiled, 'location_id': locationId, 'stock_entry_id': specificStockEntryId, 'exact_amount': true },
function(bookingResponse)
{ {
window.location.reload(); Grocy.Api.Get('stock/products/' + productId,
} function(result)
if (result == null || result.amount == 0)
{
animateCSS("#stock-" + stockRowId + "-row", "fadeOut", function()
{
$("#stock-" + stockRowId + "-row").addClass("d-none");
});
}
else
{
var dueThreshold = moment().add(Grocy.UserSettings.stock_due_soon_days, "days");
var now = moment();
var bestBeforeDate = moment(result.best_before_date);
stockRow.removeClass("table-warning");
stockRow.removeClass("table-danger");
stockRow.removeClass("table-info");
stockRow.removeClass("d-none");
stockRow.removeAttr("style");
if (now.isAfter(bestBeforeDate))
{
if (stockRow.attr("data-due-type") == 1)
{ {
stockRow.addClass("table-secondary"); var 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.UndoStockBookingEntry(' + bookingResponse.id + ',' + stockRowId + ')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>';
} if (wasSpoiled)
else {
{ toastMessage += " (" + __t("Spoiled") + ")";
stockRow.addClass("table-danger"); }
}
}
else if (bestBeforeDate.isBefore(dueThreshold))
{
stockRow.addClass("table-warning");
}
animateCSS("#stock-" + stockRowId + "-row td:not(:first)", "shake"); Grocy.FrontendHelpers.EndUiBusy();
RefreshStockEntryRow(stockRowId);
$('#stock-' + stockRowId + '-amount').text(result.amount); toastr.success(toastMessage);
$('#stock-' + stockRowId + '-due-date').text(result.best_before_date);
$('#stock-' + stockRowId + '-due-date-timeago').attr('datetime', result.best_before_date + ' 23:59:59');
$(".stock-consume-button").attr('data-location-id', result.location_id);
var locationName = "";
Grocy.Api.Get("objects/locations/" + result.location_id,
function(locationResult)
{
locationName = locationResult.name;
$('#stock-' + stockRowId + '-location').attr('data-location-id', result.location_id);
$('#stock-' + stockRowId + '-location').text(locationName);
}, },
function(xhr) function(xhr)
{ {
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr); console.error(xhr);
} }
); );
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
$('#stock-' + stockRowId + '-price').text(result.price); $(document).on('click', '.product-open-button', function(e)
$('#stock-' + stockRowId + '-purchased-date').text(result.purchased_date); {
$('#stock-' + stockRowId + '-purchased-date-timeago').attr('datetime', result.purchased_date + ' 23:59:59'); e.preventDefault();
var shoppingLocationName = ""; // Remove the focus from the current button
Grocy.Api.Get("objects/shopping_locations/" + result.shopping_location_id, // to prevent that the tooltip stays until clicked anywhere else
function(shoppingLocationResult) document.activeElement.blur();
{
shoppingLocationName = shoppingLocationResult.name;
$('#stock-' + stockRowId + '-shopping-location').attr('data-shopping-location-id', result.location_id); Grocy.FrontendHelpers.BeginUiBusy();
$('#stock-' + stockRowId + '-shopping-location').text(shoppingLocationName);
},
function(xhr)
{
console.error(xhr);
}
);
if (result.open == 1) var productId = $(e.currentTarget).attr('data-product-id');
var productName = $(e.currentTarget).attr('data-product-name');
var productQuName = $(e.currentTarget).attr('data-product-qu-name');
var specificStockEntryId = $(e.currentTarget).attr('data-stock-id');
var stockRowId = $(e.currentTarget).attr('data-stockrow-id');
var button = $(e.currentTarget);
Grocy.Api.Post('stock/products/' + productId + '/open', { 'amount': 1, 'stock_entry_id': specificStockEntryId },
function(bookingResponse)
{
button.addClass("disabled");
Grocy.FrontendHelpers.EndUiBusy();
toastr.success(__t('Marked %1$s of %2$s as opened', 1 + " " + productQuName, productName) + '<br><a class="btn btn-secondary btn-sm mt-2" href="#" onclick="Grocy.UndoStockBookingEntry(' + bookingResponse.id + ',' + stockRowId + ')"><i class="fas fa-undo"></i> ' + __t("Undo") + '</a>');
RefreshStockEntryRow(stockRowId);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
$(document).on("click", ".stock-name-cell", function(e)
{
Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-stock-id"));
$("#stockentry-productcard-modal").modal("show");
});
$(document).on('click', '.stockentry-grocycode-stockentry-label-print', function(e)
{
e.preventDefault();
document.activeElement.blur();
var stockId = $(e.currentTarget).attr('data-stock-id');
Grocy.Api.Get('stock/entry/' + stockId + '/printlabel', function(labelData)
{
if (Grocy.Webhooks.labelprinter !== undefined)
{
Grocy.FrontendHelpers.RunWebhook(Grocy.Webhooks.labelprinter, labelData);
}
});
});
function RefreshStockEntryRow(stockRowId)
{
Grocy.Api.Get("stock/entry/" + stockRowId,
function(result)
{
var stockRow = $('#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 (!stockRow.length || stockRow.hasClass("d-none"))
{ {
$('#stock-' + stockRowId + '-opened-amount').text(__t('Opened')); window.location.reload();
}
if (result == null || result.amount == 0)
{
animateCSS("#stock-" + stockRowId + "-row", "fadeOut", function()
{
$("#stock-" + stockRowId + "-row").addClass("d-none");
});
} }
else else
{ {
$('#stock-' + stockRowId + '-opened-amount').text(""); var dueThreshold = moment().add(Grocy.UserSettings.stock_due_soon_days, "days");
$(".product-open-button[data-stockrow-id='" + stockRowId + "']").removeClass("disabled"); var now = moment();
var bestBeforeDate = moment(result.best_before_date);
stockRow.removeClass("table-warning");
stockRow.removeClass("table-danger");
stockRow.removeClass("table-info");
stockRow.removeClass("d-none");
stockRow.removeAttr("style");
if (now.isAfter(bestBeforeDate))
{
if (stockRow.attr("data-due-type") == 1)
{
stockRow.addClass("table-secondary");
}
else
{
stockRow.addClass("table-danger");
}
}
else if (bestBeforeDate.isBefore(dueThreshold))
{
stockRow.addClass("table-warning");
}
animateCSS("#stock-" + stockRowId + "-row td:not(:first)", "shake");
$('#stock-' + stockRowId + '-amount').text(result.amount);
$('#stock-' + stockRowId + '-due-date').text(result.best_before_date);
$('#stock-' + stockRowId + '-due-date-timeago').attr('datetime', result.best_before_date + ' 23:59:59');
$(".stock-consume-button").attr('data-location-id', result.location_id);
var locationName = "";
Grocy.Api.Get("objects/locations/" + result.location_id,
function(locationResult)
{
locationName = locationResult.name;
$('#stock-' + stockRowId + '-location').attr('data-location-id', result.location_id);
$('#stock-' + stockRowId + '-location').text(locationName);
},
function(xhr)
{
console.error(xhr);
}
);
$('#stock-' + stockRowId + '-price').text(result.price);
$('#stock-' + stockRowId + '-purchased-date').text(result.purchased_date);
$('#stock-' + stockRowId + '-purchased-date-timeago').attr('datetime', result.purchased_date + ' 23:59:59');
var shoppingLocationName = "";
Grocy.Api.Get("objects/shopping_locations/" + result.shopping_location_id,
function(shoppingLocationResult)
{
shoppingLocationName = shoppingLocationResult.name;
$('#stock-' + stockRowId + '-shopping-location').attr('data-shopping-location-id', result.location_id);
$('#stock-' + stockRowId + '-shopping-location').text(shoppingLocationName);
},
function(xhr)
{
console.error(xhr);
}
);
if (result.open == 1)
{
$('#stock-' + stockRowId + '-opened-amount').text(__t('Opened'));
}
else
{
$('#stock-' + stockRowId + '-opened-amount').text("");
$(".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()
{
RefreshContextualTimeago("#stock-" + stockRowId + "-row");
RefreshLocaleNumberDisplay("#stock-" + stockRowId + "-row");
}, 600);
},
function(xhr)
{ {
RefreshContextualTimeago("#stock-" + stockRowId + "-row"); Grocy.FrontendHelpers.EndUiBusy();
RefreshLocaleNumberDisplay("#stock-" + stockRowId + "-row"); console.error(xhr);
}, 600); }
}, );
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
}
$(window).on("message", function(e)
{
var data = e.originalEvent.data;
if (data.Message === "StockEntryChanged")
{
RefreshStockEntryRow(data.Payload);
} }
});
Grocy.Components.ProductPicker.GetPicker().trigger('change'); $(window).on("message", function(e)
{
var data = e.originalEvent.data;
$(document).on("click", ".product-name-cell", function(e) if (data.Message === "StockEntryChanged")
{ {
Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-product-id")); RefreshStockEntryRow(data.Payload);
$("#productcard-modal").modal("show"); }
}); });
Grocy.Components.ProductPicker.GetPicker().trigger('change');
$(document).on("click", ".product-name-cell", function(e)
{
Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-product-id"));
$("#productcard-modal").modal("show");
});
}

View File

@ -1,123 +1,133 @@
import { WindowMessageBag } from '../helpers/messagebag'; function stockentryformView(Grocy, scope = null)
Grocy.Use("datetimepicker");
Grocy.Use("datetimepicker2");
Grocy.Use("locationpicker");
Grocy.Use("numberpicker");
Grocy.Use("shoppinglocationpicker");
$('#save-stockentry-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonForm = $('#stockentry-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
Grocy.FrontendHelpers.BeginUiBusy("stockentry-form");
if (!jsonForm.price.toString().isEmpty()) Grocy.Use("datetimepicker");
{ Grocy.Use("datetimepicker2");
jsonData.price = parseFloat(jsonForm.price).toFixed(Grocy.UserSettings.stock_decimal_places_prices); Grocy.Use("locationpicker");
} Grocy.Use("numberpicker");
Grocy.Use("shoppinglocationpicker");
var jsonData = {}; $('#save-stockentry-button').on('click', function(e)
jsonData.amount = jsonForm.amount;
jsonData.best_before_date = Grocy.Components.DateTimePicker.GetValue();
jsonData.purchased_date = Grocy.Components.DateTimePicker2.GetValue();
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{ {
jsonData.shopping_location_id = Grocy.Components.ShoppingLocationPicker.GetValue(); e.preventDefault();
}
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{
jsonData.location_id = Grocy.Components.LocationPicker.GetValue();
}
else
{
jsonData.location_id = 1;
}
jsonData.open = $("#open").is(":checked"); if ($(".combobox-menu-visible").length)
Grocy.Api.Put("stock/entry/" + Grocy.EditObjectId, jsonData,
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>'; return;
window.parent.postMessage(WindowMessageBag("StockEntryChanged", Grocy.EditObjectId), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", successMessage), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("Ready"), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("stockentry-form");
console.error(xhr);
} }
);
});
Grocy.FrontendHelpers.ValidateForm('stockentry-form'); var jsonForm = $('#stockentry-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("stockentry-form");
$('#stockentry-form input').keyup(function(event) if (!jsonForm.price.toString().isEmpty())
{
Grocy.FrontendHelpers.ValidateForm('stockentry-form');
});
$('#stockentry-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('stockentry-form').checkValidity() === false) //There is at least one validation error
{ {
return false; jsonData.price = parseFloat(jsonForm.price).toFixed(Grocy.UserSettings.stock_decimal_places_prices);
}
var jsonData = {};
jsonData.amount = jsonForm.amount;
jsonData.best_before_date = Grocy.Components.DateTimePicker.GetValue();
jsonData.purchased_date = Grocy.Components.DateTimePicker2.GetValue();
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{
jsonData.shopping_location_id = Grocy.Components.ShoppingLocationPicker.GetValue();
}
if (Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_LOCATION_TRACKING)
{
jsonData.location_id = Grocy.Components.LocationPicker.GetValue();
} }
else else
{ {
$('#save-stockentry-button').click(); jsonData.location_id = 1;
} }
}
});
Grocy.Components.DateTimePicker.GetInputElement().on('change', function(e) jsonData.open = $("#open").is(":checked");
{
Grocy.Api.Put("stock/entry/" + Grocy.EditObjectId, jsonData,
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>';
window.parent.postMessage(WindowMessageBag("StockEntryChanged", Grocy.EditObjectId), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", successMessage), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("Ready"), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("stockentry-form");
console.error(xhr);
}
);
});
Grocy.FrontendHelpers.ValidateForm('stockentry-form'); Grocy.FrontendHelpers.ValidateForm('stockentry-form');
});
Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e) $('#stockentry-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('stockentry-form');
});
Grocy.Components.DateTimePicker2.GetInputElement().on('change', function(e)
{
Grocy.FrontendHelpers.ValidateForm('stockentry-form');
});
Grocy.Components.DateTimePicker2.GetInputElement().on('keypress', function(e)
{
Grocy.FrontendHelpers.ValidateForm('stockentry-form');
});
Grocy.Api.Get('stock/products/' + Grocy.EditObjectProductId,
function(productDetails)
{ {
$('#amount_qu_unit').text(productDetails.quantity_unit_stock.name); Grocy.FrontendHelpers.ValidateForm('stockentry-form');
}, });
function(xhr)
{
console.error(xhr);
}
);
$("#amount").on("focus", function(e) $('#stockentry-form input').keydown(function(event)
{ {
$(this).select(); if (event.keyCode === 13) //Enter
}); {
$("#amount").focus(); event.preventDefault();
Grocy.FrontendHelpers.ValidateForm("stockentry-form");
if (document.getElementById('stockentry-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-stockentry-button').click();
}
}
});
Grocy.Components.DateTimePicker.GetInputElement().on('change', function(e)
{
Grocy.FrontendHelpers.ValidateForm('stockentry-form');
});
Grocy.Components.DateTimePicker.GetInputElement().on('keypress', function(e)
{
Grocy.FrontendHelpers.ValidateForm('stockentry-form');
});
Grocy.Components.DateTimePicker2.GetInputElement().on('change', function(e)
{
Grocy.FrontendHelpers.ValidateForm('stockentry-form');
});
Grocy.Components.DateTimePicker2.GetInputElement().on('keypress', function(e)
{
Grocy.FrontendHelpers.ValidateForm('stockentry-form');
});
Grocy.Api.Get('stock/products/' + Grocy.EditObjectProductId,
function(productDetails)
{
$('#amount_qu_unit').text(productDetails.quantity_unit_stock.name);
},
function(xhr)
{
console.error(xhr);
}
);
$("#amount").on("focus", function(e)
{
$(this).select();
});
$("#amount").focus();
Grocy.FrontendHelpers.ValidateForm("stockentry-form");
}

View File

@ -1,51 +1,61 @@
var stockJournalTable = $('#stock-journal-table').DataTable({ function stockjournalView(Grocy, scope = null)
'paginate': true,
'order': [[3, 'desc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#stock-journal-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(stockJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#product-filter", 1, stockJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#transaction-type-filter", 4, stockJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#location-filter", 5, stockJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#user-filter", 6, stockJournalTable);
if (typeof GetUriParam("product") !== "undefined")
{ {
$("#product-filter").val(GetUriParam("product")); var $scope = $;
$("#product-filter").trigger("change"); if (scope != null)
}
$(document).on('click', '.undo-stock-booking-button', function(e)
{
e.preventDefault();
var bookingId = $(e.currentTarget).attr('data-booking-id');
var correlationId = $("#stock-booking-" + bookingId + "-row").attr("data-correlation-id");
var correspondingBookingsRoot = $("#stock-booking-" + bookingId + "-row");
if (!correlationId.isEmpty())
{ {
correspondingBookingsRoot = $(".stock-booking-correlation-" + correlationId); $scope = $(scope).find;
} }
Grocy.Api.Post('stock/bookings/' + bookingId.toString() + '/undo', {}, var stockJournalTable = $('#stock-journal-table').DataTable({
function(result) 'paginate': true,
'order': [[3, 'desc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#stock-journal-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(stockJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#product-filter", 1, stockJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#transaction-type-filter", 4, stockJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#location-filter", 5, stockJournalTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#user-filter", 6, stockJournalTable);
if (typeof GetUriParam("product") !== "undefined")
{
$("#product-filter").val(GetUriParam("product"));
$("#product-filter").trigger("change");
}
$(document).on('click', '.undo-stock-booking-button', function(e)
{
e.preventDefault();
var bookingId = $(e.currentTarget).attr('data-booking-id');
var correlationId = $("#stock-booking-" + bookingId + "-row").attr("data-correlation-id");
var correspondingBookingsRoot = $("#stock-booking-" + bookingId + "-row");
if (!correlationId.isEmpty())
{ {
correspondingBookingsRoot.addClass("text-muted"); correspondingBookingsRoot = $(".stock-booking-correlation-" + correlationId);
correspondingBookingsRoot.find("span.name-anchor").addClass("text-strike-through").after("<br>" + __t("Undone on") + " " + moment().format("YYYY-MM-DD HH:mm:ss") + " <time class='timeago timeago-contextual' datetime='" + moment().format("YYYY-MM-DD HH:mm:ss") + "'></time>");
correspondingBookingsRoot.find(".undo-stock-booking-button").addClass("disabled");
RefreshContextualTimeago("#stock-booking-" + bookingId + "-row");
toastr.success(__t("Booking successfully undone"));
},
function(xhr)
{
console.error(xhr);
toastr.error(__t(JSON.parse(xhr.response).error_message));
} }
);
}); Grocy.Api.Post('stock/bookings/' + bookingId.toString() + '/undo', {},
function(result)
{
correspondingBookingsRoot.addClass("text-muted");
correspondingBookingsRoot.find("span.name-anchor").addClass("text-strike-through").after("<br>" + __t("Undone on") + " " + moment().format("YYYY-MM-DD HH:mm:ss") + " <time class='timeago timeago-contextual' datetime='" + moment().format("YYYY-MM-DD HH:mm:ss") + "'></time>");
correspondingBookingsRoot.find(".undo-stock-booking-button").addClass("disabled");
RefreshContextualTimeago("#stock-booking-" + bookingId + "-row");
toastr.success(__t("Booking successfully undone"));
},
function(xhr)
{
console.error(xhr);
toastr.error(__t(JSON.parse(xhr.response).error_message));
}
);
});
}

View File

@ -1,15 +1,24 @@
var journalSummaryTable = $('#stock-journal-summary-table').DataTable({ function stockjournalsummaryView(Grocy, scope = null)
'paginate': true, {
'order': [[1, 'asc']], var $scope = $;
'columnDefs': [ if (scope != null)
{ 'orderable': false, 'targets': 0 }, {
{ 'searchable': false, "targets": 0 } $scope = $(scope).find;
].concat($.fn.dataTable.defaults.columnDefs) }
});
$('#stock-journal-summary-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(journalSummaryTable); var journalSummaryTable = $('#stock-journal-summary-table').DataTable({
'paginate': true,
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#stock-journal-summary-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.MakeFilterForColumn("#product-filter", 1, journalSummaryTable); Grocy.FrontendHelpers.InitDataTable(journalSummaryTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#transaction-type-filter", 2, journalSummaryTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#user-filter", 3, journalSummaryTable); Grocy.FrontendHelpers.MakeFilterForColumn("#product-filter", 1, journalSummaryTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#transaction-type-filter", 2, journalSummaryTable);
Grocy.FrontendHelpers.MakeFilterForColumn("#user-filter", 3, journalSummaryTable);
}

View File

@ -1,329 +1,339 @@
Grocy.Use("productcard"); function stockoverviewView(Grocy, scope = null)
var stockOverviewTable = $('#stock-overview-table').DataTable({
'order': [[5, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ 'searchable': false, "targets": 0 },
{ 'visible': false, 'targets': 6 },
{ 'visible': false, 'targets': 7 },
{ 'visible': false, 'targets': 8 },
{ 'visible': false, 'targets': 2 },
{ 'visible': false, 'targets': 4 },
{ 'visible': false, 'targets': 9 },
{ 'visible': false, 'targets': 10 },
{ 'visible': false, 'targets': 11 },
{ 'visible': false, 'targets': 12 },
{ 'visible': false, 'targets': 13 },
{ "type": "num", "targets": 3 },
{ "type": "html-num-fmt", "targets": 9 },
{ "type": "html-num-fmt", "targets": 10 },
{ "type": "html", "targets": 5 },
{ "type": "html", "targets": 11 },
{ "type": "html-num-fmt", "targets": 12 },
{ "type": "num", "targets": 13 }
].concat($.fn.dataTable.defaults.columnDefs)
});
$('#stock-overview-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(stockOverviewTable);
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.MakeStatusFilter(stockOverviewTable, 7);
$(document).on('click', '.stockentry-grocycode-product-label-print', function(e)
{ {
e.preventDefault(); var $scope = $;
document.activeElement.blur(); if (scope != null)
var productId = $(e.currentTarget).attr('data-product-id');
Grocy.Api.Get('stock/products/' + productId + '/printlabel', function(labelData)
{ {
if (Grocy.Webhooks.labelprinter !== undefined) $scope = $(scope).find;
{ }
Grocy.FrontendHelpers.RunWebhook(Grocy.Webhooks.labelprinter, labelData);
} Grocy.Use("productcard");
var stockOverviewTable = $('#stock-overview-table').DataTable({
'order': [[5, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 },
{ 'searchable': false, "targets": 0 },
{ 'visible': false, 'targets': 6 },
{ 'visible': false, 'targets': 7 },
{ 'visible': false, 'targets': 8 },
{ 'visible': false, 'targets': 2 },
{ 'visible': false, 'targets': 4 },
{ 'visible': false, 'targets': 9 },
{ 'visible': false, 'targets': 10 },
{ 'visible': false, 'targets': 11 },
{ 'visible': false, 'targets': 12 },
{ 'visible': false, 'targets': 13 },
{ "type": "num", "targets": 3 },
{ "type": "html-num-fmt", "targets": 9 },
{ "type": "html-num-fmt", "targets": 10 },
{ "type": "html", "targets": 5 },
{ "type": "html", "targets": 11 },
{ "type": "html-num-fmt", "targets": 12 },
{ "type": "num", "targets": 13 }
].concat($.fn.dataTable.defaults.columnDefs)
}); });
});
$(document).on('click', '.product-consume-button', function(e) $('#stock-overview-table tbody').removeClass("d-none");
{ Grocy.FrontendHelpers.InitDataTable(stockOverviewTable);
e.preventDefault(); 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.MakeStatusFilter(stockOverviewTable, 7);
// Remove the focus from the current button $(document).on('click', '.stockentry-grocycode-product-label-print', function(e)
// to prevent that the tooltip stays until clicked anywhere else {
document.activeElement.blur(); e.preventDefault();
document.activeElement.blur();
Grocy.FrontendHelpers.BeginUiBusy(); var productId = $(e.currentTarget).attr('data-product-id');
Grocy.Api.Get('stock/products/' + productId + '/printlabel', function(labelData)
var target = $(e.currentTarget);
var productId = target.attr('data-product-id');
var consumeAmount = target.attr('data-consume-amount');
var originalTotalStockAmount = target.attr('data-original-total-stock-amount');
var wasSpoiled = target.hasClass("product-consume-button-spoiled");
Grocy.Api.Post('stock/products/' + productId + '/consume', { 'amount': consumeAmount, 'spoiled': wasSpoiled, 'allow_subproduct_substitution': true },
function(bookingResponse)
{ {
Grocy.Api.Get('stock/products/' + productId, if (Grocy.Webhooks.labelprinter !== undefined)
function(result)
{
var toastMessage = "";
if (result.product.enable_tare_weight_handling == 1)
{
toastMessage = __t('Removed %1$s of %2$s from stock', parseFloat(originalTotalStockAmount).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>';
}
else
{
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)
{
toastMessage += " (" + __t("Spoiled") + ")";
}
Grocy.FrontendHelpers.EndUiBusy();
toastr.success(toastMessage);
RefreshStatistics();
RefreshProductRow(productId);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
$(document).on('click', '.product-open-button', function(e)
{
e.preventDefault();
// Remove the focus from the current button
// to prevent that the tooltip stays until clicked anywhere else
document.activeElement.blur();
Grocy.FrontendHelpers.BeginUiBusy();
var button = $(e.currentTarget);
var productId = button.attr('data-product-id');
var productName = button.attr('data-product-name');
var productQuName = button.attr('data-product-qu-name');
var amount = button.attr('data-open-amount');
Grocy.Api.Post('stock/products/' + productId + '/open', { 'amount': amount, 'allow_subproduct_substitution': true },
function(bookingResponse)
{
Grocy.Api.Get('stock/products/' + productId,
function(result)
{
if (result.stock_amount == result.stock_amount_opened)
{
button.addClass("disabled");
}
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>');
RefreshStatistics();
RefreshProductRow(productId);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
$(document).on("click", ".product-name-cell", function(e)
{
Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-product-id"));
$("#stockoverview-productcard-modal").modal("show");
});
function RefreshStatistics()
{
Grocy.Api.Get('stock',
function(result)
{
if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{ {
$("#info-current-stock").text(__n(result.length, '%s Product', '%s Products')); Grocy.FrontendHelpers.RunWebhook(Grocy.Webhooks.labelprinter, labelData);
} }
else });
});
$(document).on('click', '.product-consume-button', function(e)
{
e.preventDefault();
// Remove the focus from the current button
// to prevent that the tooltip stays until clicked anywhere else
document.activeElement.blur();
Grocy.FrontendHelpers.BeginUiBusy();
var target = $(e.currentTarget);
var productId = target.attr('data-product-id');
var consumeAmount = target.attr('data-consume-amount');
var originalTotalStockAmount = target.attr('data-original-total-stock-amount');
var wasSpoiled = target.hasClass("product-consume-button-spoiled");
Grocy.Api.Post('stock/products/' + productId + '/consume', { 'amount': consumeAmount, 'spoiled': wasSpoiled, 'allow_subproduct_substitution': true },
function(bookingResponse)
{ {
var valueSum = 0; Grocy.Api.Get('stock/products/' + productId,
result.forEach(element => function(result)
{ {
valueSum += parseFloat(element.value); var toastMessage = "";
}); if (result.product.enable_tare_weight_handling == 1)
$("#info-current-stock").text(__n(result.length, '%s Product', '%s Products') + ", " + __t('%s total value', valueSum.toLocaleString(undefined, { style: "currency", currency: Grocy.Currency }))); {
toastMessage = __t('Removed %1$s of %2$s from stock', parseFloat(originalTotalStockAmount).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>';
}
else
{
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)
{
toastMessage += " (" + __t("Spoiled") + ")";
}
Grocy.FrontendHelpers.EndUiBusy();
toastr.success(toastMessage);
RefreshStatistics();
RefreshProductRow(productId);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
} }
}, );
function(xhr) });
{
console.error(xhr);
}
);
var nextXDays = $("#info-duesoon-products").data("next-x-days"); $(document).on('click', '.product-open-button', function(e)
Grocy.Api.Get('stock/volatile?due_soon_days=' + nextXDays, {
function(result) e.preventDefault();
{
$("#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>');
$("#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>');
},
function(xhr)
{
console.error(xhr);
}
);
}
RefreshStatistics();
function RefreshProductRow(productId) // Remove the focus from the current button
{ // to prevent that the tooltip stays until clicked anywhere else
productId = productId.toString(); document.activeElement.blur();
Grocy.Api.Get('stock/products/' + productId, Grocy.FrontendHelpers.BeginUiBusy();
function(result)
{ var button = $(e.currentTarget);
// Also refresh the parent product, if any
if (result.product.parent_product_id !== null && !result.product.parent_product_id.toString().isEmpty()) var productId = button.attr('data-product-id');
var productName = button.attr('data-product-name');
var productQuName = button.attr('data-product-qu-name');
var amount = button.attr('data-open-amount');
Grocy.Api.Post('stock/products/' + productId + '/open', { 'amount': amount, 'allow_subproduct_substitution': true },
function(bookingResponse)
{ {
RefreshProductRow(result.product.parent_product_id); Grocy.Api.Get('stock/products/' + productId,
function(result)
{
if (result.stock_amount == result.stock_amount_opened)
{
button.addClass("disabled");
}
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>');
RefreshStatistics();
RefreshProductRow(productId);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
} }
);
});
var productRow = $('#product-' + productId + '-row'); $(document).on("click", ".product-name-cell", function(e)
var dueSoonThreshold = moment().add($("#info-duesoon-products").data("next-x-days"), "days"); {
var now = moment(); Grocy.Components.ProductCard.Refresh($(e.currentTarget).attr("data-product-id"));
var nextDueDate = moment(result.next_due_date); $("#stockoverview-productcard-modal").modal("show");
});
productRow.removeClass("table-warning"); function RefreshStatistics()
productRow.removeClass("table-danger"); {
productRow.removeClass("table-secondary"); Grocy.Api.Get('stock',
productRow.removeClass("table-info"); function(result)
productRow.removeClass("d-none");
productRow.removeAttr("style");
if (now.isAfter(nextDueDate))
{ {
if (result.product.due_type == 1) if (!Grocy.FeatureFlags.GROCY_FEATURE_FLAG_STOCK_PRICE_TRACKING)
{ {
productRow.addClass("table-secondary"); $("#info-current-stock").text(__n(result.length, '%s Product', '%s Products'));
} }
else else
{ {
productRow.addClass("table-danger"); var valueSum = 0;
result.forEach(element =>
{
valueSum += parseFloat(element.value);
});
$("#info-current-stock").text(__n(result.length, '%s Product', '%s Products') + ", " + __t('%s total value', valueSum.toLocaleString(undefined, { style: "currency", currency: Grocy.Currency })));
} }
} },
else if (nextDueDate.isBefore(dueSoonThreshold)) function(xhr)
{ {
productRow.addClass("table-warning"); console.error(xhr);
} }
);
if (result.stock_amount == 0 && result.stock_amount_aggregated == 0 && result.product.min_stock_amount == 0) var nextXDays = $("#info-duesoon-products").data("next-x-days");
Grocy.Api.Get('stock/volatile?due_soon_days=' + nextXDays,
function(result)
{ {
animateCSS("#product-" + productId + "-row", "fadeOut", function() $("#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>');
$("#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>');
},
function(xhr)
{
console.error(xhr);
}
);
}
RefreshStatistics();
function RefreshProductRow(productId)
{
productId = productId.toString();
Grocy.Api.Get('stock/products/' + productId,
function(result)
{
// Also refresh the parent product, if any
if (result.product.parent_product_id !== null && !result.product.parent_product_id.toString().isEmpty())
{ {
$("#product-" + productId + "-row").tooltip("hide"); RefreshProductRow(result.product.parent_product_id);
$("#product-" + productId + "-row").addClass("d-none"); }
});
} var productRow = $('#product-' + productId + '-row');
else var dueSoonThreshold = moment().add($("#info-duesoon-products").data("next-x-days"), "days");
{ var now = moment();
animateCSS("#product-" + productId + "-row td:not(:first)", "shake"); var nextDueDate = moment(result.next_due_date);
productRow.removeClass("table-warning");
productRow.removeClass("table-danger");
productRow.removeClass("table-secondary");
productRow.removeClass("table-info");
productRow.removeClass("d-none");
productRow.removeAttr("style");
if (now.isAfter(nextDueDate))
{
if (result.product.due_type == 1)
{
productRow.addClass("table-secondary");
}
else
{
productRow.addClass("table-danger");
}
}
else if (nextDueDate.isBefore(dueSoonThreshold))
{
productRow.addClass("table-warning");
}
if (result.stock_amount == 0 && result.stock_amount_aggregated == 0 && result.product.min_stock_amount == 0)
{
animateCSS("#product-" + productId + "-row", "fadeOut", function()
{
$("#product-" + productId + "-row").tooltip("hide");
$("#product-" + productId + "-row").addClass("d-none");
});
}
else
{
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));
$('#product-' + productId + '-amount').text(result.stock_amount);
$('#product-' + productId + '-consume-all-button').attr('data-consume-amount', result.stock_amount);
$('#product-' + productId + '-value').text(result.stock_value);
$('#product-' + productId + '-next-due-date').text(result.next_due_date);
$('#product-' + productId + '-next-due-date-timeago').attr('datetime', result.next_due_date);
var openedAmount = result.stock_amount_opened || 0;
if (openedAmount > 0)
{
$('#product-' + productId + '-opened-amount').text(__t('%s opened', openedAmount));
}
else
{
$('#product-' + productId + '-opened-amount').text("");
}
if (result.stock_amount == 0 && result.product.min_stock_amount > 0)
{
productRow.addClass("table-info");
}
}
$('#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);
$('#product-' + productId + '-consume-all-button').attr('data-consume-amount', result.stock_amount);
$('#product-' + productId + '-value').text(result.stock_value);
$('#product-' + productId + '-next-due-date').text(result.next_due_date); $('#product-' + productId + '-next-due-date').text(result.next_due_date);
$('#product-' + productId + '-next-due-date-timeago').attr('datetime', result.next_due_date); $('#product-' + productId + '-next-due-date-timeago').attr('datetime', result.next_due_date + ' 23:59:59');
var openedAmount = result.stock_amount_opened || 0; if (result.stock_amount_opened > 0)
if (openedAmount > 0)
{ {
$('#product-' + productId + '-opened-amount').text(__t('%s opened', openedAmount)); $('#product-' + productId + '-opened-amount').text(__t('%s opened', result.stock_amount_opened));
} }
else else
{ {
$('#product-' + productId + '-opened-amount').text(""); $('#product-' + productId + '-opened-amount').text("");
} }
if (result.stock_amount == 0 && result.product.min_stock_amount > 0) if (parseInt(result.is_aggregated_amount) === 1)
{ {
productRow.addClass("table-info"); $('#product-' + productId + '-amount-aggregated').text(result.stock_amount_aggregated);
if (result.stock_amount_opened_aggregated > 0)
{
$('#product-' + productId + '-opened-amount-aggregated').text(__t('%s opened', result.stock_amount_opened_aggregated));
}
else
{
$('#product-' + productId + '-opened-amount-aggregated').text("");
}
} }
}
$('#product-' + productId + '-next-due-date').text(result.next_due_date); // Needs to be delayed because of the animation above the date-text would be wrong if fired immediately...
$('#product-' + productId + '-next-due-date-timeago').attr('datetime', result.next_due_date + ' 23:59:59'); setTimeout(function()
if (result.stock_amount_opened > 0)
{
$('#product-' + productId + '-opened-amount').text(__t('%s opened', result.stock_amount_opened));
}
else
{
$('#product-' + productId + '-opened-amount').text("");
}
if (parseInt(result.is_aggregated_amount) === 1)
{
$('#product-' + productId + '-amount-aggregated').text(result.stock_amount_aggregated);
if (result.stock_amount_opened_aggregated > 0)
{ {
$('#product-' + productId + '-opened-amount-aggregated').text(__t('%s opened', result.stock_amount_opened_aggregated)); RefreshContextualTimeago("#product-" + productId + "-row");
} RefreshLocaleNumberDisplay("#product-" + productId + "-row");
else }, 600);
{ },
$('#product-' + productId + '-opened-amount-aggregated').text(""); function(xhr)
}
}
// Needs to be delayed because of the animation above the date-text would be wrong if fired immediately...
setTimeout(function()
{ {
RefreshContextualTimeago("#product-" + productId + "-row"); Grocy.FrontendHelpers.EndUiBusy();
RefreshLocaleNumberDisplay("#product-" + productId + "-row"); console.error(xhr);
}, 600); }
}, );
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
}
$(window).on("message", function(e)
{
var data = e.originalEvent.data;
if (data.Message === "ProductChanged")
{
RefreshProductRow(data.Payload);
RefreshStatistics();
} }
});
$(window).on("message", function(e)
{
var data = e.originalEvent.data;
if (data.Message === "ProductChanged")
{
RefreshProductRow(data.Payload);
RefreshStatistics();
}
});
}

View File

@ -1,46 +1,56 @@
import { BoolVal } from '../helpers/extensions'; function stocksettingsView(Grocy, scope = null)
Grocy.Use("numberpicker");
$("#product_presets_location_id").val(Grocy.UserSettings.product_presets_location_id);
$("#product_presets_product_group_id").val(Grocy.UserSettings.product_presets_product_group_id);
$("#product_presets_qu_id").val(Grocy.UserSettings.product_presets_qu_id);
$("#stock_due_soon_days").val(Grocy.UserSettings.stock_due_soon_days);
$("#stock_default_purchase_amount").val(Grocy.UserSettings.stock_default_purchase_amount);
$("#stock_default_consume_amount").val(Grocy.UserSettings.stock_default_consume_amount);
$("#stock_decimal_places_amounts").val(Grocy.UserSettings.stock_decimal_places_amounts);
$("#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))
{ {
$("#show_icon_on_stock_overview_page_when_product_is_on_shopping_list").prop("checked", true); var $scope = $;
} if (scope != null)
if (BoolVal(Grocy.UserSettings.show_purchased_date_on_purchase))
{
$("#show_purchased_date_on_purchase").prop("checked", true);
}
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);
}
if (BoolVal(Grocy.UserSettings.stock_default_consume_amount_use_quick_consume_amount))
{
$("#stock_default_consume_amount_use_quick_consume_amount").prop("checked", true);
$("#stock_default_consume_amount").attr("disabled", "");
}
RefreshLocaleNumberInput();
$("#stock_default_consume_amount_use_quick_consume_amount").on("click", function()
{
if (this.checked)
{ {
$scope = $(scope).find;
}
import { BoolVal } from '../helpers/extensions';
Grocy.Use("numberpicker");
$("#product_presets_location_id").val(Grocy.UserSettings.product_presets_location_id);
$("#product_presets_product_group_id").val(Grocy.UserSettings.product_presets_product_group_id);
$("#product_presets_qu_id").val(Grocy.UserSettings.product_presets_qu_id);
$("#stock_due_soon_days").val(Grocy.UserSettings.stock_due_soon_days);
$("#stock_default_purchase_amount").val(Grocy.UserSettings.stock_default_purchase_amount);
$("#stock_default_consume_amount").val(Grocy.UserSettings.stock_default_consume_amount);
$("#stock_decimal_places_amounts").val(Grocy.UserSettings.stock_decimal_places_amounts);
$("#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))
{
$("#show_icon_on_stock_overview_page_when_product_is_on_shopping_list").prop("checked", true);
}
if (BoolVal(Grocy.UserSettings.show_purchased_date_on_purchase))
{
$("#show_purchased_date_on_purchase").prop("checked", true);
}
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);
}
if (BoolVal(Grocy.UserSettings.stock_default_consume_amount_use_quick_consume_amount))
{
$("#stock_default_consume_amount_use_quick_consume_amount").prop("checked", true);
$("#stock_default_consume_amount").attr("disabled", ""); $("#stock_default_consume_amount").attr("disabled", "");
} }
else
RefreshLocaleNumberInput();
$("#stock_default_consume_amount_use_quick_consume_amount").on("click", function()
{ {
$("#stock_default_consume_amount").removeAttr("disabled"); if (this.checked)
} {
}); $("#stock_default_consume_amount").attr("disabled", "");
}
else
{
$("#stock_default_consume_amount").removeAttr("disabled");
}
});
}

View File

@ -1,18 +1,27 @@
var categoriesTable = $('#taskcategories-table').DataTable({ function taskcategoriesView(Grocy, scope = null)
'order': [[1, 'asc']], {
'columnDefs': [ var $scope = $;
{ 'orderable': false, 'targets': 0 }, if (scope != null)
{ 'searchable': false, "targets": 0 } {
].concat($.fn.dataTable.defaults.columnDefs) $scope = $(scope).find;
}); }
$('#taskcategories-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(categoriesTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox( var categoriesTable = $('#taskcategories-table').DataTable({
'Are you sure to delete task category "%s"?', 'order': [[1, 'asc']],
'.task-category-delete-button', 'columnDefs': [
'data-category-name', { 'orderable': false, 'targets': 0 },
'data-category-id', { 'searchable': false, "targets": 0 }
'objects/task_categories/', ].concat($.fn.dataTable.defaults.columnDefs)
'/taskcategories' });
); $('#taskcategories-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(categoriesTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete task category "%s"?',
'.task-category-delete-button',
'data-category-name',
'data-category-id',
'objects/task_categories/',
'/taskcategories'
);
}

View File

@ -1,90 +1,100 @@
import { WindowMessageBag } from '../helpers/messagebag'; function taskcategoryformView(Grocy, scope = null)
$('#save-task-category-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#task-category-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
Grocy.FrontendHelpers.BeginUiBusy("task-category-form");
if (Grocy.EditMode === 'create') $('#save-task-category-button').on('click', function(e)
{ {
Grocy.Api.Post('objects/task_categories', jsonData, e.preventDefault();
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/taskcategories');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("task-category-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/task_categories/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/taskcategories');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("task-category-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$('#task-category-form input').keyup(function(event) if ($(".combobox-menu-visible").length)
{
Grocy.FrontendHelpers.ValidateForm('task-category-form');
});
$('#task-category-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('task-category-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return;
}
var jsonData = $('#task-category-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("task-category-form");
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/task_categories', jsonData,
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/taskcategories');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("task-category-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
else else
{ {
$('#save-task-category-button').click(); Grocy.Api.Put('objects/task_categories/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/taskcategories');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("task-category-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
} });
});
Grocy.Components.UserfieldsForm.Load(); $('#task-category-form input').keyup(function(event)
$('#name').focus(); {
Grocy.FrontendHelpers.ValidateForm('task-category-form'); Grocy.FrontendHelpers.ValidateForm('task-category-form');
});
$('#task-category-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('task-category-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-task-category-button').click();
}
}
});
Grocy.Components.UserfieldsForm.Load();
$('#name').focus();
Grocy.FrontendHelpers.ValidateForm('task-category-form');
}

View File

@ -1,98 +1,108 @@
import { WindowMessageBag } from '../helpers/messagebag'; function taskformView(Grocy, scope = null)
Grocy.Use("datetimepicker");
Grocy.Use("userfieldsform");
$('#save-task-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#task-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
jsonData.assigned_to_user_id = jsonData.user_id;
delete jsonData.user_id;
jsonData.due_date = Grocy.Components.DateTimePicker.GetValue();
Grocy.FrontendHelpers.BeginUiBusy("task-form"); Grocy.Use("datetimepicker");
Grocy.Use("userfieldsform");
if (Grocy.EditMode === 'create') $('#save-task-button').on('click', function(e)
{ {
Grocy.Api.Post('objects/tasks', jsonData, e.preventDefault();
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/tasks');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("task-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/tasks/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/tasks');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("task-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$('#task-form input').keyup(function(event) if ($(".combobox-menu-visible").length)
{
Grocy.FrontendHelpers.ValidateForm('task-form');
});
$('#task-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('task-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return;
}
var jsonData = $('#task-form').serializeJSON();
jsonData.assigned_to_user_id = jsonData.user_id;
delete jsonData.user_id;
jsonData.due_date = Grocy.Components.DateTimePicker.GetValue();
Grocy.FrontendHelpers.BeginUiBusy("task-form");
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/tasks', jsonData,
function(result)
{
Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/tasks');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("task-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
else else
{ {
$('#save-task-button').click(); Grocy.Api.Put('objects/tasks/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = U('/tasks');
}
});
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("task-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
} });
});
Grocy.Components.UserfieldsForm.Load(); $('#task-form input').keyup(function(event)
$('#name').focus(); {
Grocy.Components.DateTimePicker.GetInputElement().trigger('input'); Grocy.FrontendHelpers.ValidateForm('task-form');
Grocy.FrontendHelpers.ValidateForm('task-form'); });
$('#task-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('task-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-task-button').click();
}
}
});
Grocy.Components.UserfieldsForm.Load();
$('#name').focus();
Grocy.Components.DateTimePicker.GetInputElement().trigger('input');
Grocy.FrontendHelpers.ValidateForm('task-form');
}

View File

@ -1,161 +1,171 @@
Grocy.Use("userpicker"); function tasksView(Grocy, scope = null)
{
var tasksTable = $('#tasks-table').DataTable({ var $scope = $;
'order': [[2, 'asc']], if (scope != null)
'columnDefs': [ {
{ 'orderable': false, 'targets': 0 }, $scope = $(scope).find;
{ 'searchable': false, "targets": 0 },
{ 'visible': false, 'targets': 3 },
{ "type": "html", "targets": 2 }
].concat($.fn.dataTable.defaults.columnDefs),
'rowGroup': {
enable: true,
dataSrc: 3
} }
});
$('#tasks-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(tasksTable, null, function()
{
$("#search").val("");
$("#search").trigger("keyup");
$("#show-done-tasks").trigger('checked', false);
});
Grocy.FrontendHelpers.MakeStatusFilter(tasksTable, 5);
$(document).on('click', '.do-task-button', function(e) Grocy.Use("userpicker");
{
e.preventDefault();
// Remove the focus from the current button var tasksTable = $('#tasks-table').DataTable({
// to prevent that the tooltip stays until clicked anywhere else 'order': [[2, 'asc']],
document.activeElement.blur(); 'columnDefs': [
{ 'orderable': false, 'targets': 0 },
Grocy.FrontendHelpers.BeginUiBusy(); { 'searchable': false, "targets": 0 },
{ 'visible': false, 'targets': 3 },
var taskId = $(e.currentTarget).attr('data-task-id'); { "type": "html", "targets": 2 }
var taskName = $(e.currentTarget).attr('data-task-name'); ].concat($.fn.dataTable.defaults.columnDefs),
var doneTime = moment().format('YYYY-MM-DD HH:mm:ss'); 'rowGroup': {
enable: true,
Grocy.Api.Post('tasks/' + taskId + '/complete', { 'done_time': doneTime }, dataSrc: 3
function()
{
if (!$("#show-done-tasks").is(":checked"))
{
animateCSS("#task-" + taskId + "-row", "fadeOut", function()
{
$("#task-" + taskId + "-row").tooltip("hide");
$("#task-" + taskId + "-row").remove();
});
}
else
{
$('#task-' + taskId + '-row').addClass("text-muted");
$('#task-' + taskId + '-name').addClass("text-strike-through");
$('.do-task-button[data-task-id="' + taskId + '"]').addClass("disabled");
}
Grocy.FrontendHelpers.EndUiBusy();
toastr.success(__t('Marked task %s as completed on %s', taskName, doneTime));
RefreshContextualTimeago("#task-" + taskId + "-row");
RefreshStatistics();
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
} }
); });
}); $('#tasks-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(tasksTable, null, function()
$(document).on('click', '.undo-task-button', function(e)
{
e.preventDefault();
// Remove the focus from the current button
// to prevent that the tooltip stays until clicked anywhere else
document.activeElement.blur();
Grocy.FrontendHelpers.BeginUiBusy();
var taskId = $(e.currentTarget).attr('data-task-id');
Grocy.Api.Post('tasks/' + taskId + '/undo', {},
function()
{
window.location.reload();
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete task "%s"?',
'.delete-task-button',
'data-task-name',
'data-task-id',
'objects/tasks/',
(result, objectId, objectName) =>
{ {
animateCSS("#task-" + objectId + "-row", "fadeOut", function() $("#search").val("");
{ $("#search").trigger("keyup");
$("#task-" + objectId + "-row").tooltip("hide"); $("#show-done-tasks").trigger('checked', false);
$("#task-" + objectId + "-row").remove(); });
}); Grocy.FrontendHelpers.MakeStatusFilter(tasksTable, 5);
}
);
$("#show-done-tasks").change(function() $(document).on('click', '.do-task-button', function(e)
{
if (this.checked)
{ {
window.location.href = U('/tasks?include_done'); e.preventDefault();
}
else
{
window.location.href = U('/tasks');
}
});
if (GetUriParam('include_done')) // Remove the focus from the current button
{ // to prevent that the tooltip stays until clicked anywhere else
$("#show-done-tasks").prop('checked', true); document.activeElement.blur();
}
function RefreshStatistics() Grocy.FrontendHelpers.BeginUiBusy();
{
var nextXDays = $("#info-due-tasks").data("next-x-days"); var taskId = $(e.currentTarget).attr('data-task-id');
Grocy.Api.Get('tasks', var taskName = $(e.currentTarget).attr('data-task-name');
function(result) var doneTime = moment().format('YYYY-MM-DD HH:mm:ss');
{
var dueCount = 0; Grocy.Api.Post('tasks/' + taskId + '/complete', { 'done_time': doneTime },
var overdueCount = 0; function()
var now = moment();
var nextXDaysThreshold = moment().add(nextXDays, "days");
result.forEach(element =>
{ {
var date = moment(element.due_date); if (!$("#show-done-tasks").is(":checked"))
if (date.isBefore(now))
{ {
overdueCount++; animateCSS("#task-" + taskId + "-row", "fadeOut", function()
{
$("#task-" + taskId + "-row").tooltip("hide");
$("#task-" + taskId + "-row").remove();
});
} }
else if (date.isBefore(nextXDaysThreshold)) else
{ {
dueCount++; $('#task-' + taskId + '-row').addClass("text-muted");
$('#task-' + taskId + '-name').addClass("text-strike-through");
$('.do-task-button[data-task-id="' + taskId + '"]').addClass("disabled");
} }
Grocy.FrontendHelpers.EndUiBusy();
toastr.success(__t('Marked task %s as completed on %s', taskName, doneTime));
RefreshContextualTimeago("#task-" + taskId + "-row");
RefreshStatistics();
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
$(document).on('click', '.undo-task-button', function(e)
{
e.preventDefault();
// Remove the focus from the current button
// to prevent that the tooltip stays until clicked anywhere else
document.activeElement.blur();
Grocy.FrontendHelpers.BeginUiBusy();
var taskId = $(e.currentTarget).attr('data-task-id');
Grocy.Api.Post('tasks/' + taskId + '/undo', {},
function()
{
window.location.reload();
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy();
console.error(xhr);
}
);
});
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete task "%s"?',
'.delete-task-button',
'data-task-name',
'data-task-id',
'objects/tasks/',
(result, objectId, objectName) =>
{
animateCSS("#task-" + objectId + "-row", "fadeOut", function()
{
$("#task-" + objectId + "-row").tooltip("hide");
$("#task-" + objectId + "-row").remove();
}); });
$("#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'));
},
function(xhr)
{
console.error(xhr);
} }
); );
}
RefreshStatistics(); $("#show-done-tasks").change(function()
{
if (this.checked)
{
window.location.href = U('/tasks?include_done');
}
else
{
window.location.href = U('/tasks');
}
});
if (GetUriParam('include_done'))
{
$("#show-done-tasks").prop('checked', true);
}
function RefreshStatistics()
{
var nextXDays = $("#info-due-tasks").data("next-x-days");
Grocy.Api.Get('tasks',
function(result)
{
var dueCount = 0;
var overdueCount = 0;
var now = moment();
var nextXDaysThreshold = moment().add(nextXDays, "days");
result.forEach(element =>
{
var date = moment(element.due_date);
if (date.isBefore(now))
{
overdueCount++;
}
else if (date.isBefore(nextXDaysThreshold))
{
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'));
$("#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)
{
console.error(xhr);
}
);
}
RefreshStatistics();
}

View File

@ -1,5 +1,15 @@
Grocy.Use("numberpicker"); function taskssettingsView(Grocy, scope = null)
{
var $scope = $;
if (scope != null)
{
$scope = $(scope).find;
}
$("#tasks_due_soon_days").val(Grocy.UserSettings.tasks_due_soon_days); Grocy.Use("numberpicker");
RefreshLocaleNumberInput(); $("#tasks_due_soon_days").val(Grocy.UserSettings.tasks_due_soon_days);
RefreshLocaleNumberInput();
}

View File

@ -1,252 +1,226 @@
import { WindowMessageBag } from '../helpers/messagebag'; function transferView(Grocy, scope = null)
Grocy.Use("productpicker");
Grocy.Use("productamountpicker");
Grocy.Use("productcard");
$('#save-transfer-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonForm = $('#transfer-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
Grocy.FrontendHelpers.BeginUiBusy("transfer-form");
var apiUrl = 'stock/products/' + jsonForm.product_id + '/transfer'; Grocy.Use("productpicker");
Grocy.Use("productamountpicker");
Grocy.Use("productcard");
var jsonData = {}; $('#save-transfer-button').on('click', function(e)
jsonData.amount = jsonForm.amount;
jsonData.location_id_to = $("#location_id_to").val();
jsonData.location_id_from = $("#location_id_from").val();
if ($("#use_specific_stock_entry").is(":checked"))
{ {
jsonData.stock_entry_id = jsonForm.specific_stock_entry; e.preventDefault();
}
var bookingResponse = null; if ($(".combobox-menu-visible").length)
Grocy.Api.Get('stock/products/' + jsonForm.product_id,
function(productDetails)
{ {
Grocy.Api.Post(apiUrl, jsonData, return;
function(result)
{
bookingResponse = result;
if (GetUriParam("flow") === "InplaceAddBarcodeToExistingProduct")
{
var jsonDataBarcode = {};
jsonDataBarcode.barcode = GetUriParam("barcode");
jsonDataBarcode.product_id = jsonForm.product_id;
Grocy.Api.Post('objects/product_barcodes', jsonDataBarcode,
function(result)
{
$("#flow-info-InplaceAddBarcodeToExistingProduct").addClass("d-none");
$('#barcode-lookup-disabled-hint').addClass('d-none');
$('#barcode-lookup-hint').removeClass('d-none');
window.history.replaceState({}, document.title, U("/transfer"));
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("transfer-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
}
);
}
var amount = "";
if (productDetails.product.enable_tare_weight_handling == 1)
{
amount = Math.abs(jsonForm.amount - parseFloat(productDetails.product.tare_weight)).toString();
}
else
{
amount = Math.abs(jsonForm.amount).toString()
}
amount += " " +
__n(jsonForm.amount,
productDetails.quantity_unit_stock.name,
productDetails.quantity_unit_stock.name_plural
);
var successMessage = __t('Transfered %1$s of %2$s from %3$s to %4$s',
amount,
productDetails.product.name,
$('option:selected', "#location_id_from").text(),
$('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>';
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("ProductChanged", jsonForm.product_id), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", successMessage), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
}
else
{
Grocy.FrontendHelpers.EndUiBusy("transfer-form");
toastr.success(successMessage);
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
{
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
{
toastr.info('<span>' + __t("Thawed") + "</span> <i class='fas fa-fire-alt'></i>");
}
$("#specific_stock_entry").find("option").remove().end().append("<option></option>");
$("#specific_stock_entry").attr("disabled", "");
$("#specific_stock_entry").removeAttr("required");
if ($("#use_specific_stock_entry").is(":checked"))
{
$("#use_specific_stock_entry").click();
}
Grocy.Components.ProductAmountPicker.Reset();
$("#location_id_from").find("option").remove().end().append("<option></option>");
$("#display_amount").attr("min", Grocy.DefaultMinAmount);
$("#display_amount").removeAttr("max");
$('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_transfer_amount));
RefreshLocaleNumberInput();
$(".input-group-productamountpicker").trigger("change");
$("#tare-weight-handling-info").addClass("d-none");
Grocy.Components.ProductPicker.Clear();
$("#location_id_to").val("");
$("#location_id_from").val("");
Grocy.Components.ProductPicker.GetInputElement().focus();
Grocy.Components.ProductCard.Refresh(jsonForm.product_id);
Grocy.FrontendHelpers.ValidateForm('transfer-form');
}
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("transfer-form");
console.error(xhr);
}
);
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("transfer-form");
console.error(xhr);
} }
);
});
Grocy.Components.ProductPicker.GetPicker().on('change', function(e) var jsonForm = $('#transfer-form').serializeJSON();
{ Grocy.FrontendHelpers.BeginUiBusy("transfer-form");
$("#specific_stock_entry").find("option").remove().end().append("<option></option>");
if ($("#use_specific_stock_entry").is(":checked") && GetUriParam("stockId") == null)
{
$("#use_specific_stock_entry").click();
}
$("#location_id_to").val("");
if (GetUriParam("stockId") == null)
{
$("#location_id_from").val("");
}
var productId = $(e.target).val(); var apiUrl = 'stock/products/' + jsonForm.product_id + '/transfer';
if (productId) var jsonData = {};
{ jsonData.amount = jsonForm.amount;
Grocy.Components.ProductCard.Refresh(productId); jsonData.location_id_to = $("#location_id_to").val();
jsonData.location_id_from = $("#location_id_from").val();
Grocy.Api.Get('stock/products/' + productId, if ($("#use_specific_stock_entry").is(":checked"))
{
jsonData.stock_entry_id = jsonForm.specific_stock_entry;
}
var bookingResponse = null;
Grocy.Api.Get('stock/products/' + jsonForm.product_id,
function(productDetails) function(productDetails)
{ {
Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id); Grocy.Api.Post(apiUrl, jsonData,
Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.quantity_unit_stock.id); function(result)
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.Clear();
return;
}
$("#location_id_from").find("option").remove().end().append("<option></option>");
Grocy.Api.Get("stock/products/" + productId + '/locations',
function(stockLocations)
{ {
var setDefault = 0; bookingResponse = result;
stockLocations.forEach(stockLocation =>
if (GetUriParam("flow") === "InplaceAddBarcodeToExistingProduct")
{ {
if (productDetails.location.id == stockLocation.location_id) var jsonDataBarcode = {};
jsonDataBarcode.barcode = GetUriParam("barcode");
jsonDataBarcode.product_id = jsonForm.product_id;
Grocy.Api.Post('objects/product_barcodes', jsonDataBarcode,
function(result)
{
$("#flow-info-InplaceAddBarcodeToExistingProduct").addClass("d-none");
$('#barcode-lookup-disabled-hint').addClass('d-none');
$('#barcode-lookup-hint').removeClass('d-none');
window.history.replaceState({}, document.title, U("/transfer"));
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("transfer-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
}
);
}
var amount = "";
if (productDetails.product.enable_tare_weight_handling == 1)
{
amount = Math.abs(jsonForm.amount - parseFloat(productDetails.product.tare_weight)).toString();
}
else
{
amount = Math.abs(jsonForm.amount).toString()
}
amount += " " +
__n(jsonForm.amount,
productDetails.quantity_unit_stock.name,
productDetails.quantity_unit_stock.name_plural
);
var successMessage = __t('Transfered %1$s of %2$s from %3$s to %4$s',
amount,
productDetails.product.name,
$('option:selected', "#location_id_from").text(),
$('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>';
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("ProductChanged", jsonForm.product_id), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("ShowSuccessMessage", successMessage), Grocy.BaseUrl);
window.parent.postMessage(WindowMessageBag("CloseAllModals"), Grocy.BaseUrl);
}
else
{
Grocy.FrontendHelpers.EndUiBusy("transfer-form");
toastr.success(successMessage);
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
{ {
$("#location_id_from").append($("<option>", { toastr.info('<span>' + __t("Frozen") + "</span> <i class='fas fa-snowflake'></i>");
value: stockLocation.location_id,
text: stockLocation.location_name + " (" + __t("Default location") + ")",
"data-is-freezer": stockLocation.location_is_freezer
}));
$("#location_id_from").val(productDetails.location.id);
$("#location_id_from").trigger('change');
setDefault = 1;
} }
else if (parseInt($("#location_id_from option:selected").attr("data-is-freezer")) === 1 && parseInt($("#location_id_to option:selected").attr("data-is-freezer")) === 0) // Thawed
{ {
$("#location_id_from").append($("<option>", { toastr.info('<span>' + __t("Thawed") + "</span> <i class='fas fa-fire-alt'></i>");
value: stockLocation.location_id,
text: stockLocation.location_name,
"data-is-freezer": stockLocation.location_is_freezer
}));
} }
if (setDefault == 0) $("#specific_stock_entry").find("option").remove().end().append("<option></option>");
$("#specific_stock_entry").attr("disabled", "");
$("#specific_stock_entry").removeAttr("required");
if ($("#use_specific_stock_entry").is(":checked"))
{ {
$("#location_id_from").val(stockLocation.location_id); $("#use_specific_stock_entry").click();
$("#location_id_from").trigger('change');
} }
});
if (GetUriParam("locationId") != null) Grocy.Components.ProductAmountPicker.Reset();
{ $("#location_id_from").find("option").remove().end().append("<option></option>");
$("#location_id_from").val(GetUriParam("locationId")); $("#display_amount").attr("min", Grocy.DefaultMinAmount);
$("#location_id_from").trigger("change"); $("#display_amount").removeAttr("max");
$('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_transfer_amount));
RefreshLocaleNumberInput();
$(".input-group-productamountpicker").trigger("change");
$("#tare-weight-handling-info").addClass("d-none");
Grocy.Components.ProductPicker.Clear();
$("#location_id_to").val("");
$("#location_id_from").val("");
Grocy.Components.ProductPicker.GetInputElement().focus();
Grocy.Components.ProductCard.Refresh(jsonForm.product_id);
Grocy.FrontendHelpers.ValidateForm('transfer-form');
} }
}, },
function(xhr) function(xhr)
{ {
Grocy.FrontendHelpers.EndUiBusy("transfer-form");
console.error(xhr); console.error(xhr);
} }
); );
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("transfer-form");
console.error(xhr);
}
);
});
if (document.getElementById("product_id").getAttribute("barcode") != "null") Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
{
$("#specific_stock_entry").find("option").remove().end().append("<option></option>");
if ($("#use_specific_stock_entry").is(":checked") && GetUriParam("stockId") == null)
{
$("#use_specific_stock_entry").click();
}
$("#location_id_to").val("");
if (GetUriParam("stockId") == null)
{
$("#location_id_from").val("");
}
var productId = $(e.target).val();
if (productId)
{
Grocy.Components.ProductCard.Refresh(productId);
Grocy.Api.Get('stock/products/' + productId,
function(productDetails)
{ {
Grocy.Api.Get('objects/product_barcodes?query[]=barcode=' + document.getElementById("product_id").getAttribute("barcode"), Grocy.Components.ProductAmountPicker.Reload(productDetails.product.id, productDetails.quantity_unit_stock.id);
function(barcodeResult) Grocy.Components.ProductAmountPicker.SetQuantityUnit(productDetails.quantity_unit_stock.id);
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.Clear();
return;
}
$("#location_id_from").find("option").remove().end().append("<option></option>");
Grocy.Api.Get("stock/products/" + productId + '/locations',
function(stockLocations)
{ {
if (barcodeResult != null) var setDefault = 0;
stockLocations.forEach(stockLocation =>
{ {
var barcode = barcodeResult[0]; if (productDetails.location.id == stockLocation.location_id)
if (barcode != null)
{ {
if (barcode.amount != null && !barcode.amount.isEmpty()) $("#location_id_from").append($("<option>", {
{ value: stockLocation.location_id,
$("#display_amount").val(barcode.amount); text: stockLocation.location_name + " (" + __t("Default location") + ")",
$("#display_amount").select(); "data-is-freezer": stockLocation.location_is_freezer
} }));
$("#location_id_from").val(productDetails.location.id);
if (barcode.qu_id != null) $("#location_id_from").trigger('change');
{ setDefault = 1;
Grocy.Components.ProductAmountPicker.SetQuantityUnit(barcode.qu_id);
}
$(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('transfer-form');
RefreshLocaleNumberInput();
} }
else
{
$("#location_id_from").append($("<option>", {
value: stockLocation.location_id,
text: stockLocation.location_name,
"data-is-freezer": stockLocation.location_is_freezer
}));
}
if (setDefault == 0)
{
$("#location_id_from").val(stockLocation.location_id);
$("#location_id_from").trigger('change');
}
});
if (GetUriParam("locationId") != null)
{
$("#location_id_from").val(GetUriParam("locationId"));
$("#location_id_from").trigger("change");
} }
}, },
function(xhr) function(xhr)
@ -254,232 +228,268 @@ Grocy.Components.ProductPicker.GetPicker().on('change', function(e)
console.error(xhr); console.error(xhr);
} }
); );
}
if (productDetails.product.enable_tare_weight_handling == 1) if (document.getElementById("product_id").getAttribute("barcode") != "null")
{
$("#display_amount").attr("min", productDetails.product.tare_weight);
$("#tare-weight-handling-info").removeClass("d-none");
}
else
{
$("#display_amount").attr("min", Grocy.DefaultMinAmount);
$("#tare-weight-handling-info").addClass("d-none");
}
$('#display_amount').attr("data-stock-amount", productDetails.stock_amount);
if ((parseFloat(productDetails.stock_amount) || 0) === 0)
{
Grocy.Components.ProductPicker.Clear();
Grocy.FrontendHelpers.ValidateForm('transfer-form');
Grocy.Components.ProductPicker.ShowCustomError(__t('This product is not in stock'));
Grocy.Components.ProductPicker.GetInputElement().focus();
}
else
{
Grocy.Components.ProductPicker.HideCustomError();
Grocy.FrontendHelpers.ValidateForm('transfer-form');
$('#display_amount').focus();
}
},
function(xhr)
{
console.error(xhr);
}
);
}
});
$('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_transfer_amount));
$(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('transfer-form');
RefreshLocaleNumberInput();
$("#location_id_from").on('change', function(e)
{
var locationId = $(e.target).val();
var sumValue = 0;
var stockId = null;
if (locationId == $("#location_id_to").val())
{
$("#location_id_to").val("");
}
if (GetUriParam("embedded") !== undefined)
{
stockId = GetUriParam('stockId');
}
$("#specific_stock_entry").find("option").remove().end().append("<option></option>");
if ($("#use_specific_stock_entry").is(":checked") && GetUriParam("stockId") == null)
{
$("#use_specific_stock_entry").click();
}
if (locationId)
{
Grocy.Api.Get("stock/products/" + Grocy.Components.ProductPicker.GetValue() + '/entries',
function(stockEntries)
{
stockEntries.forEach(stockEntry =>
{
var openTxt = __t("Not opened");
if (stockEntry.open == 1)
{ {
openTxt = __t("Opened"); Grocy.Api.Get('objects/product_barcodes?query[]=barcode=' + document.getElementById("product_id").getAttribute("barcode"),
function(barcodeResult)
{
if (barcodeResult != null)
{
var barcode = barcodeResult[0];
if (barcode != null)
{
if (barcode.amount != null && !barcode.amount.isEmpty())
{
$("#display_amount").val(barcode.amount);
$("#display_amount").select();
}
if (barcode.qu_id != null)
{
Grocy.Components.ProductAmountPicker.SetQuantityUnit(barcode.qu_id);
}
$(".input-group-productamountpicker").trigger("change");
Grocy.FrontendHelpers.ValidateForm('transfer-form');
RefreshLocaleNumberInput();
}
}
},
function(xhr)
{
console.error(xhr);
}
);
} }
if (stockEntry.location_id == locationId) if (productDetails.product.enable_tare_weight_handling == 1)
{ {
$("#specific_stock_entry").append($("<option>", { $("#display_amount").attr("min", productDetails.product.tare_weight);
value: stockEntry.stock_id, $("#tare-weight-handling-info").removeClass("d-none");
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
}));
if (stockEntry.stock_id == stockId)
{
$("#specific_stock_entry").val(stockId);
}
sumValue = sumValue + parseFloat(stockEntry.amount);
} }
}); else
$("#display_amount").attr("max", sumValue * $("#qu_id option:selected").attr("data-qu-factor")); {
if (sumValue == 0) $("#display_amount").attr("min", Grocy.DefaultMinAmount);
$("#tare-weight-handling-info").addClass("d-none");
}
$('#display_amount').attr("data-stock-amount", productDetails.stock_amount);
if ((parseFloat(productDetails.stock_amount) || 0) === 0)
{
Grocy.Components.ProductPicker.Clear();
Grocy.FrontendHelpers.ValidateForm('transfer-form');
Grocy.Components.ProductPicker.ShowCustomError(__t('This product is not in stock'));
Grocy.Components.ProductPicker.GetInputElement().focus();
}
else
{
Grocy.Components.ProductPicker.HideCustomError();
Grocy.FrontendHelpers.ValidateForm('transfer-form');
$('#display_amount').focus();
}
},
function(xhr)
{ {
$("#display_amount").parent().find(".invalid-feedback").text(__t('There are no units available at this location')); console.error(xhr);
} }
}, );
function(xhr) }
{ });
console.error(xhr);
}
);
}
});
$("#location_id_to").on('change', function(e) $('#display_amount').val(parseFloat(Grocy.UserSettings.stock_default_transfer_amount));
{ $(".input-group-productamountpicker").trigger("change");
var locationId = $(e.target).val();
if (locationId == $("#location_id_from").val())
{
$("#location_id_to").parent().find(".invalid-feedback").text(__t('This cannot be the same as the "From" location'));
$("#location_id_to").val("");
}
});
$("#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"));
});
$('#display_amount').on('focus', function(e)
{
$(this).select();
});
$('#transfer-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('transfer-form'); Grocy.FrontendHelpers.ValidateForm('transfer-form');
}); RefreshLocaleNumberInput();
$('#transfer-form select').change(function(event) $("#location_id_from").on('change', function(e)
{
Grocy.FrontendHelpers.ValidateForm('transfer-form');
});
$('#transfer-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{ {
event.preventDefault(); var locationId = $(e.target).val();
var sumValue = 0;
var stockId = null;
if (document.getElementById('transfer-form').checkValidity() === false) //There is at least one validation error if (locationId == $("#location_id_to").val())
{ {
return false; $("#location_id_to").val("");
}
if (GetUriParam("embedded") !== undefined)
{
stockId = GetUriParam('stockId');
}
$("#specific_stock_entry").find("option").remove().end().append("<option></option>");
if ($("#use_specific_stock_entry").is(":checked") && GetUriParam("stockId") == null)
{
$("#use_specific_stock_entry").click();
}
if (locationId)
{
Grocy.Api.Get("stock/products/" + Grocy.Components.ProductPicker.GetValue() + '/entries',
function(stockEntries)
{
stockEntries.forEach(stockEntry =>
{
var openTxt = __t("Not opened");
if (stockEntry.open == 1)
{
openTxt = __t("Opened");
}
if (stockEntry.location_id == locationId)
{
$("#specific_stock_entry").append($("<option>", {
value: stockEntry.stock_id,
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
}));
if (stockEntry.stock_id == stockId)
{
$("#specific_stock_entry").val(stockId);
}
sumValue = sumValue + parseFloat(stockEntry.amount);
}
});
$("#display_amount").attr("max", sumValue * $("#qu_id option:selected").attr("data-qu-factor"));
if (sumValue == 0)
{
$("#display_amount").parent().find(".invalid-feedback").text(__t('There are no units available at this location'));
}
},
function(xhr)
{
console.error(xhr);
}
);
}
});
$("#location_id_to").on('change', function(e)
{
var locationId = $(e.target).val();
if (locationId == $("#location_id_from").val())
{
$("#location_id_to").parent().find(".invalid-feedback").text(__t('This cannot be the same as the "From" location'));
$("#location_id_to").val("");
}
});
$("#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"));
});
$('#display_amount').on('focus', function(e)
{
$(this).select();
});
$('#transfer-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('transfer-form');
});
$('#transfer-form select').change(function(event)
{
Grocy.FrontendHelpers.ValidateForm('transfer-form');
});
$('#transfer-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('transfer-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-transfer-button').click();
}
}
});
$("#specific_stock_entry").on("change", function(e)
{
if ($(e.target).val() == "")
{
var sumValue = 0;
Grocy.Api.Get("stock/products/" + Grocy.Components.ProductPicker.GetValue() + '/entries',
function(stockEntries)
{
stockEntries.forEach(stockEntry =>
{
if (stockEntry.location_id == $("#location_id_from").val() || stockEntry.location_id == "")
{
sumValue = sumValue + parseFloat(stockEntry.amount);
}
});
$("#display_amount").attr("max", sumValue * $("#qu_id option:selected").attr("data-qu-factor"));
if (sumValue == 0)
{
$("#display_amount").parent().find(".invalid-feedback").text(__t('There are no units available at this location'));
}
},
function(xhr)
{
console.error(xhr);
}
);
} }
else else
{ {
$('#save-transfer-button').click(); $("#display_amount").attr("max", $('option:selected', this).attr('amount'));
}
});
$("#use_specific_stock_entry").on("change", function()
{
var value = $(this).is(":checked");
if (value)
{
$("#specific_stock_entry").removeAttr("disabled");
$("#specific_stock_entry").attr("required", "");
}
else
{
$("#specific_stock_entry").attr("disabled", "");
$("#specific_stock_entry").removeAttr("required");
$("#specific_stock_entry").val("");
$("#location_id_from").trigger('change');
}
Grocy.FrontendHelpers.ValidateForm("transfer-form");
});
if (GetUriParam("embedded") !== undefined)
{
var locationId = GetUriParam('locationId');
if (typeof locationId === 'undefined')
{
Grocy.Components.ProductPicker.GetPicker().trigger('change');
Grocy.Components.ProductPicker.GetInputElement().focus();
}
else
{
$("#location_id_from").val(locationId);
$("#location_id_from").trigger('change');
$("#use_specific_stock_entry").click();
$("#use_specific_stock_entry").trigger('change');
Grocy.Components.ProductPicker.GetPicker().trigger('change');
} }
} }
});
$("#specific_stock_entry").on("change", function(e) // Default input field
{ Grocy.Components.ProductPicker.GetInputElement().focus();
if ($(e.target).val() == "")
{
var sumValue = 0;
Grocy.Api.Get("stock/products/" + Grocy.Components.ProductPicker.GetValue() + '/entries',
function(stockEntries)
{
stockEntries.forEach(stockEntry =>
{
if (stockEntry.location_id == $("#location_id_from").val() || stockEntry.location_id == "")
{
sumValue = sumValue + parseFloat(stockEntry.amount);
}
});
$("#display_amount").attr("max", sumValue * $("#qu_id option:selected").attr("data-qu-factor"));
if (sumValue == 0)
{
$("#display_amount").parent().find(".invalid-feedback").text(__t('There are no units available at this location'));
}
},
function(xhr)
{
console.error(xhr);
}
);
}
else
{
$("#display_amount").attr("max", $('option:selected', this).attr('amount'));
}
});
$("#use_specific_stock_entry").on("change", function()
{
var value = $(this).is(":checked");
if (value)
{
$("#specific_stock_entry").removeAttr("disabled");
$("#specific_stock_entry").attr("required", "");
}
else
{
$("#specific_stock_entry").attr("disabled", "");
$("#specific_stock_entry").removeAttr("required");
$("#specific_stock_entry").val("");
$("#location_id_from").trigger('change');
}
Grocy.FrontendHelpers.ValidateForm("transfer-form");
});
if (GetUriParam("embedded") !== undefined)
{
var locationId = GetUriParam('locationId');
if (typeof locationId === 'undefined')
{
Grocy.Components.ProductPicker.GetPicker().trigger('change');
Grocy.Components.ProductPicker.GetInputElement().focus();
}
else
{
$("#location_id_from").val(locationId);
$("#location_id_from").trigger('change');
$("#use_specific_stock_entry").click();
$("#use_specific_stock_entry").trigger('change');
Grocy.Components.ProductPicker.GetPicker().trigger('change');
}
} }
// Default input field
Grocy.Components.ProductPicker.GetInputElement().focus();

View File

@ -1,18 +1,27 @@
var userentitiesTable = $('#userentities-table').DataTable({ function userentitiesView(Grocy, scope = null)
'order': [[1, 'asc']], {
'columnDefs': [ var $scope = $;
{ 'orderable': false, 'targets': 0 }, if (scope != null)
{ 'searchable': false, "targets": 0 } {
].concat($.fn.dataTable.defaults.columnDefs) $scope = $(scope).find;
}); }
$('#userentities-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(userentitiesTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox( var userentitiesTable = $('#userentities-table').DataTable({
'Are you sure to delete userentity "%s"?', 'order': [[1, 'asc']],
'.userentity-delete-button', 'columnDefs': [
'data-userentity-name', { 'orderable': false, 'targets': 0 },
'data-userentity-id', { 'searchable': false, "targets": 0 }
'objects/userentities/', ].concat($.fn.dataTable.defaults.columnDefs)
'/userentities' });
); $('#userentities-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(userentitiesTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete userentity "%s"?',
'.userentity-delete-button',
'data-userentity-name',
'data-userentity-id',
'objects/userentities/',
'/userentities'
);
}

View File

@ -1,105 +1,115 @@
import { WindowMessageBag } from '../helpers/messagebag'; function userentityformView(Grocy, scope = null)
$('#save-userentity-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#userentity-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
Grocy.FrontendHelpers.BeginUiBusy("userentity-form");
var redirectUrl = U("/userentities"); $('#save-userentity-button').on('click', function(e)
if (Grocy.EditMode === 'create')
{ {
Grocy.Api.Post('objects/userentities', jsonData, e.preventDefault();
function(result)
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = redirectUrl;
}
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("userentity-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/userentities/' + Grocy.EditObjectId, jsonData,
function(result)
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = redirectUrl;
}
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("userentity-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$('#userentity-form input').keyup(function(event) if ($(".combobox-menu-visible").length)
{
Grocy.FrontendHelpers.ValidateForm('userentity-form');
});
$('#userentity-form select').change(function(event)
{
Grocy.FrontendHelpers.ValidateForm('userentity-form');
});
$('#userentity-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('userentity-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return;
}
var jsonData = $('#userentity-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("userentity-form");
var redirectUrl = U("/userentities");
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/userentities', jsonData,
function(result)
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = redirectUrl;
}
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("userentity-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
else else
{ {
$('#save-userentity-button').click(); Grocy.Api.Put('objects/userentities/' + Grocy.EditObjectId, jsonData,
function(result)
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = redirectUrl;
}
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("userentity-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
} });
});
$("#show_in_sidebar_menu").on("click", function() $('#userentity-form input').keyup(function(event)
{
if (this.checked)
{ {
$("#icon_css_class").removeAttr("disabled"); Grocy.FrontendHelpers.ValidateForm('userentity-form');
} });
else
$('#userentity-form select').change(function(event)
{ {
$("#icon_css_class").attr("disabled", ""); Grocy.FrontendHelpers.ValidateForm('userentity-form');
} });
});
$('#name').focus(); $('#userentity-form input').keydown(function(event)
Grocy.FrontendHelpers.ValidateForm('userentity-form'); {
if (event.keyCode === 13) //Enter
{
event.preventDefault();
// Click twice to trigger on-click but not change the actual checked state if (document.getElementById('userentity-form').checkValidity() === false) //There is at least one validation error
$("#show_in_sidebar_menu").click(); {
$("#show_in_sidebar_menu").click(); return false;
}
else
{
$('#save-userentity-button').click();
}
}
});
$("#show_in_sidebar_menu").on("click", function()
{
if (this.checked)
{
$("#icon_css_class").removeAttr("disabled");
}
else
{
$("#icon_css_class").attr("disabled", "");
}
});
$('#name').focus();
Grocy.FrontendHelpers.ValidateForm('userentity-form');
// Click twice to trigger on-click but not change the actual checked state
$("#show_in_sidebar_menu").click();
$("#show_in_sidebar_menu").click();
}

View File

@ -1,120 +1,130 @@
import { WindowMessageBag } from '../helpers/messagebag'; function userfieldformView(Grocy, scope = null)
Grocy.Use("numberpicker");
$('#save-userfield-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = $('#userfield-form').serializeJSON(); import { WindowMessageBag } from '../helpers/messagebag';
Grocy.FrontendHelpers.BeginUiBusy("userfield-form");
var redirectUrl = U("/userfields"); Grocy.Use("numberpicker");
if (typeof GetUriParam("entity") !== "undefined" && !GetUriParam("entity").isEmpty())
$('#save-userfield-button').on('click', function(e)
{ {
redirectUrl = U("/userfields?entity=" + GetUriParam("entity")); e.preventDefault();
}
if (Grocy.EditMode === 'create') if ($(".combobox-menu-visible").length)
{
Grocy.Api.Post('objects/userfields', jsonData,
function(result)
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = redirectUrl;
}
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("userfield-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/userfields/' + Grocy.EditObjectId, jsonData,
function(result)
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = redirectUrl;
}
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("userfield-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$('#userfield-form input').keyup(function(event)
{
Grocy.FrontendHelpers.ValidateForm('userfield-form');
});
$('#userfield-form select').change(function(event)
{
Grocy.FrontendHelpers.ValidateForm('userfield-form');
});
$('#userfield-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('userfield-form').checkValidity() === false) //There is at least one validation error
{ {
return false; return;
}
var jsonData = $('#userfield-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("userfield-form");
var redirectUrl = U("/userfields");
if (typeof GetUriParam("entity") !== "undefined" && !GetUriParam("entity").isEmpty())
{
redirectUrl = U("/userfields?entity=" + GetUriParam("entity"));
}
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/userfields', jsonData,
function(result)
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = redirectUrl;
}
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("userfield-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
else else
{ {
$('#save-userfield-button').click(); Grocy.Api.Put('objects/userfields/' + Grocy.EditObjectId, jsonData,
function(result)
{
if (GetUriParam("embedded") !== undefined)
{
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
}
else
{
window.location.href = redirectUrl;
}
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("userfield-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
} });
});
$("#type").on("change", function(e) $('#userfield-form input').keyup(function(event)
{
var value = $(this).val();
if (value === "preset-list" || value === "preset-checklist")
{ {
$("#config").parent().removeClass("d-none"); Grocy.FrontendHelpers.ValidateForm('userfield-form');
$("#config-hint").text(__t("A predefined list of values, one per line")); });
}
else $('#userfield-form select').change(function(event)
{ {
$("#config").parent().addClass("d-none"); Grocy.FrontendHelpers.ValidateForm('userfield-form');
$("#config-hint").text(""); });
$('#userfield-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('userfield-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-userfield-button').click();
}
}
});
$("#type").on("change", function(e)
{
var value = $(this).val();
if (value === "preset-list" || value === "preset-checklist")
{
$("#config").parent().removeClass("d-none");
$("#config-hint").text(__t("A predefined list of values, one per line"));
}
else
{
$("#config").parent().addClass("d-none");
$("#config-hint").text("");
}
});
$('#entity').focus();
if (typeof GetUriParam("entity") !== "undefined" && !GetUriParam("entity").isEmpty())
{
$("#entity").val(GetUriParam("entity"));
$("#entity").trigger("change");
$('#name').focus();
} }
});
$('#entity').focus(); $("#type").trigger("change");
Grocy.FrontendHelpers.ValidateForm('userfield-form');
if (typeof GetUriParam("entity") !== "undefined" && !GetUriParam("entity").isEmpty())
{
$("#entity").val(GetUriParam("entity"));
$("#entity").trigger("change");
$('#name').focus();
} }
$("#type").trigger("change");
Grocy.FrontendHelpers.ValidateForm('userfield-form');

View File

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

View File

@ -1,148 +1,158 @@
Grocy.Use("userfieldsform"); function userformView(Grocy, scope = null)
function SaveUserPicture(result, jsonData)
{ {
Grocy.Components.UserfieldsForm.Save(() => var $scope = $;
if (scope != null)
{ {
if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteUserPictureOnSave) $scope = $(scope).find;
{
Grocy.Api.UploadFile($("#user-picture")[0].files[0], 'userpictures', jsonData.picture_file_name,
(result) =>
{
window.location.href = U('/users');
},
(xhr) =>
{
Grocy.FrontendHelpers.EndUiBusy("user-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
window.location.href = U('/users');
}
});
}
$('#save-user-button').on('click', function(e)
{
e.preventDefault();
if ($(".combobox-menu-visible").length)
{
return;
} }
var jsonData = $('#user-form').serializeJSON(); Grocy.Use("userfieldsform");
Grocy.FrontendHelpers.BeginUiBusy("user-form");
if ($("#user-picture")[0].files.length > 0) function SaveUserPicture(result, jsonData)
{ {
var someRandomStuff = Math.random().toString(36).substring(2, 100) + Math.random().toString(36).substring(2, 100); Grocy.Components.UserfieldsForm.Save(() =>
jsonData.picture_file_name = someRandomStuff + $("#user-picture")[0].files[0].name; {
} if (Object.prototype.hasOwnProperty.call(jsonData, "picture_file_name") && !Grocy.DeleteUserPictureOnSave)
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('users', jsonData,
(result) => SaveUserPicture(result, jsonData),
function(xhr)
{ {
Grocy.FrontendHelpers.EndUiBusy("user-form"); Grocy.Api.UploadFile($("#user-picture")[0].files[0], 'userpictures', jsonData.picture_file_name,
console.error(xhr); (result) =>
{
window.location.href = U('/users');
},
(xhr) =>
{
Grocy.FrontendHelpers.EndUiBusy("user-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
} }
); else
{
window.location.href = U('/users');
}
});
} }
else
{
if (Grocy.DeleteUserPictureOnSave)
{
jsonData.picture_file_name = null;
Grocy.Api.DeleteFile(Grocy.UserPictureFileName, 'userpictures', {}, $('#save-user-button').on('click', function(e)
function(result) {
{ e.preventDefault();
// Nothing to do
}, if ($(".combobox-menu-visible").length)
{
return;
}
var jsonData = $('#user-form').serializeJSON();
Grocy.FrontendHelpers.BeginUiBusy("user-form");
if ($("#user-picture")[0].files.length > 0)
{
var someRandomStuff = Math.random().toString(36).substring(2, 100) + Math.random().toString(36).substring(2, 100);
jsonData.picture_file_name = someRandomStuff + $("#user-picture")[0].files[0].name;
}
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('users', jsonData,
(result) => SaveUserPicture(result, jsonData),
function(xhr) function(xhr)
{ {
Grocy.FrontendHelpers.EndUiBusy("user-form"); Grocy.FrontendHelpers.EndUiBusy("user-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response) console.error(xhr);
} }
); );
} }
else
Grocy.Api.Put('users/' + Grocy.EditObjectId, jsonData,
(result) => SaveUserPicture(result, jsonData),
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("user-form");
console.error(xhr);
}
);
}
});
$('#user-form input').keyup(function(event)
{
var element = document.getElementById("password_confirm");
if ($("#password").val() !== $("#password_confirm").val())
{
element.setCustomValidity("error");
}
else
{
element.setCustomValidity("");
}
Grocy.FrontendHelpers.ValidateForm('user-form');
});
$('#user-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('user-form').checkValidity() === false) //There is at least one validation error
{ {
return false; if (Grocy.DeleteUserPictureOnSave)
{
jsonData.picture_file_name = null;
Grocy.Api.DeleteFile(Grocy.UserPictureFileName, 'userpictures', {},
function(result)
{
// Nothing to do
},
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("user-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
Grocy.Api.Put('users/' + Grocy.EditObjectId, jsonData,
(result) => SaveUserPicture(result, jsonData),
function(xhr)
{
Grocy.FrontendHelpers.EndUiBusy("user-form");
console.error(xhr);
}
);
}
});
$('#user-form input').keyup(function(event)
{
var element = document.getElementById("password_confirm");
if ($("#password").val() !== $("#password_confirm").val())
{
element.setCustomValidity("error");
} }
else else
{ {
$('#save-user-button').click(); element.setCustomValidity("");
} }
Grocy.FrontendHelpers.ValidateForm('user-form');
});
$('#user-form input').keydown(function(event)
{
if (event.keyCode === 13) //Enter
{
event.preventDefault();
if (document.getElementById('user-form').checkValidity() === false) //There is at least one validation error
{
return false;
}
else
{
$('#save-user-button').click();
}
}
});
if (GetUriParam("changepw") === "true")
{
$('#password').focus();
}
else
{
$('#username').focus();
} }
});
if (GetUriParam("changepw") === "true") $("#user-picture").on("change", function(e)
{ {
$('#password').focus(); $("#user-picture-label").removeClass("d-none");
$("#user-picture-label-none").addClass("d-none");
$("#delete-current-user-picture-on-save-hint").addClass("d-none");
$("#current-user-picture").addClass("d-none");
Grocy.DeleteUserePictureOnSave = false;
});
Grocy.DeleteUserPictureOnSave = false;
$("#delete-current-user-picture-button").on("click", function(e)
{
Grocy.DeleteUserPictureOnSave = true;
$("#current-user-picture").addClass("d-none");
$("#delete-current-user-picture-on-save-hint").removeClass("d-none");
$("#user-picture-label").addClass("d-none");
$("#user-picture-label-none").removeClass("d-none");
});
Grocy.Components.UserfieldsForm.Load();
Grocy.FrontendHelpers.ValidateForm('user-form');
} }
else
{
$('#username').focus();
}
$("#user-picture").on("change", function(e)
{
$("#user-picture-label").removeClass("d-none");
$("#user-picture-label-none").addClass("d-none");
$("#delete-current-user-picture-on-save-hint").addClass("d-none");
$("#current-user-picture").addClass("d-none");
Grocy.DeleteUserePictureOnSave = false;
});
Grocy.DeleteUserPictureOnSave = false;
$("#delete-current-user-picture-button").on("click", function(e)
{
Grocy.DeleteUserPictureOnSave = true;
$("#current-user-picture").addClass("d-none");
$("#delete-current-user-picture-on-save-hint").removeClass("d-none");
$("#user-picture-label").addClass("d-none");
$("#user-picture-label-none").removeClass("d-none");
});
Grocy.Components.UserfieldsForm.Load();
Grocy.FrontendHelpers.ValidateForm('user-form');

View File

@ -1,71 +1,81 @@
import { WindowMessageBag } from '../helpers/messagebag'; function userobjectformView(Grocy, scope = null)
Grocy.Use("userfieldsform");
$('#save-userobject-button').on('click', function(e)
{ {
e.preventDefault(); var $scope = $;
if (scope != null)
if ($(".combobox-menu-visible").length)
{ {
return; $scope = $(scope).find;
} }
var jsonData = {}; import { WindowMessageBag } from '../helpers/messagebag';
jsonData.userentity_id = Grocy.EditObjectParentId;
Grocy.FrontendHelpers.BeginUiBusy("userobject-form"); Grocy.Use("userfieldsform");
if (Grocy.EditMode === 'create') $('#save-userobject-button').on('click', function(e)
{ {
Grocy.Api.Post('objects/userobjects', jsonData, e.preventDefault();
function(result)
{ if ($(".combobox-menu-visible").length)
Grocy.EditObjectId = result.created_object_id; {
Grocy.Components.UserfieldsForm.Save(function() return;
}
var jsonData = {};
jsonData.userentity_id = Grocy.EditObjectParentId;
Grocy.FrontendHelpers.BeginUiBusy("userobject-form");
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('objects/userobjects', jsonData,
function(result)
{ {
if (GetUriParam("embedded") !== undefined) Grocy.EditObjectId = result.created_object_id;
Grocy.Components.UserfieldsForm.Save(function()
{ {
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl); if (GetUriParam("embedded") !== undefined)
} {
else window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
{ }
window.location.href = U('/userobjects/' + Grocy.EditObjectParentName); else
} {
}); window.location.href = U('/userobjects/' + Grocy.EditObjectParentName);
}, }
function(xhr) });
{ },
Grocy.FrontendHelpers.EndUiBusy("userobject-form"); function(xhr)
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/userobjects/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{ {
if (GetUriParam("embedded") !== undefined) Grocy.FrontendHelpers.EndUiBusy("userobject-form");
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Put('objects/userobjects/' + Grocy.EditObjectId, jsonData,
function(result)
{
Grocy.Components.UserfieldsForm.Save(function()
{ {
window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl); if (GetUriParam("embedded") !== undefined)
} {
else window.parent.postMessage(WindowMessageBag("Reload"), Grocy.BaseUrl);
{ }
window.location.href = U('/userobjects/' + Grocy.EditObjectParentName); else
} {
}); window.location.href = U('/userobjects/' + Grocy.EditObjectParentName);
}, }
function(xhr) });
{ },
Grocy.FrontendHelpers.EndUiBusy("userobject-form"); function(xhr)
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response) {
} Grocy.FrontendHelpers.EndUiBusy("userobject-form");
); Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
} }
}); );
}
});
Grocy.Components.UserfieldsForm.Load(); Grocy.Components.UserfieldsForm.Load();
$("#userfields-form").removeClass("border").removeClass("border-info").removeClass("p-2").find("h2").addClass("d-none"); $("#userfields-form").removeClass("border").removeClass("border-info").removeClass("p-2").find("h2").addClass("d-none");
}

View File

@ -1,18 +1,27 @@
var userobjectsTable = $('#userobjects-table').DataTable({ function userobjectsView(Grocy, scope = null)
'order': [[1, 'asc']], {
'columnDefs': [ var $scope = $;
{ 'orderable': false, 'targets': 0 }, if (scope != null)
{ 'searchable': false, "targets": 0 } {
].concat($.fn.dataTable.defaults.columnDefs) $scope = $(scope).find;
}); }
$('#userobjects-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(userobjectsTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox( var userobjectsTable = $('#userobjects-table').DataTable({
'Are you sure to delete this userobject?', 'order': [[1, 'asc']],
'.userobject-delete-button', 'columnDefs': [
'data-userobject-id', { 'orderable': false, 'targets': 0 },
'data-userobject-id', { 'searchable': false, "targets": 0 }
'objects/userobjects/', ].concat($.fn.dataTable.defaults.columnDefs)
() => window.location.reload() });
); $('#userobjects-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(userobjectsTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete this userobject?',
'.userobject-delete-button',
'data-userobject-id',
'data-userobject-id',
'objects/userobjects/',
() => window.location.reload()
);
}

View File

@ -1,73 +1,83 @@
$('input.permission-cb').click( function userpermissionsView(Grocy, scope = null)
function()
{
check_hierachy(this.checked, this.name);
}
);
function check_hierachy(checked, name)
{ {
var disabled = checked; var $scope = $;
$('#permission-sub-' + name).find('input.permission-cb') if (scope != null)
.prop('checked', disabled)
.attr('disabled', disabled);
}
$('#permission-save').click(
function()
{ {
var permission_list = $('input.permission-cb') $scope = $(scope).find;
.filter(function()
{
return $(this).prop('checked') && !$(this).attr('disabled');
}).map(function()
{
return $(this).data('perm-id');
}).toArray();
Grocy.Api.Put('users/' + Grocy.EditObjectId + '/permissions', { 'permissions': permission_list },
function(result)
{
toastr.success(__t("Permissions saved"));
},
function(xhr)
{
toastr.error(JSON.parse(xhr.response).error_message);
}
);
} }
);
if (Grocy.EditObjectId == Grocy.UserId) $('input.permission-cb').click(
{ function()
$('input.permission-cb[name=ADMIN]').click(function()
{
var element = this;
if (!element.checked)
{ {
bootbox.confirm({ check_hierachy(this.checked, this.name);
message: __t('Are you sure you want to remove full permissions for yourself?'),
closeButton: false,
buttons: {
confirm: {
label: __t('Yes'),
className: 'btn-success'
},
cancel: {
label: __t('No'),
className: 'btn-danger'
}
},
callback: function(result)
{
if (result == false)
{
element.checked = true;
check_hierachy(element.checked, element.name);
}
}
});
} }
}) );
function check_hierachy(checked, name)
{
var disabled = checked;
$('#permission-sub-' + name).find('input.permission-cb')
.prop('checked', disabled)
.attr('disabled', disabled);
}
$('#permission-save').click(
function()
{
var permission_list = $('input.permission-cb')
.filter(function()
{
return $(this).prop('checked') && !$(this).attr('disabled');
}).map(function()
{
return $(this).data('perm-id');
}).toArray();
Grocy.Api.Put('users/' + Grocy.EditObjectId + '/permissions', { 'permissions': permission_list },
function(result)
{
toastr.success(__t("Permissions saved"));
},
function(xhr)
{
toastr.error(JSON.parse(xhr.response).error_message);
}
);
}
);
if (Grocy.EditObjectId == Grocy.UserId)
{
$('input.permission-cb[name=ADMIN]').click(function()
{
var element = this;
if (!element.checked)
{
bootbox.confirm({
message: __t('Are you sure you want to remove full permissions for yourself?'),
closeButton: false,
buttons: {
confirm: {
label: __t('Yes'),
className: 'btn-success'
},
cancel: {
label: __t('No'),
className: 'btn-danger'
}
},
callback: function(result)
{
if (result == false)
{
element.checked = true;
check_hierachy(element.checked, element.name);
}
}
});
}
})
}
} }

View File

@ -1,18 +1,27 @@
var usersTable = $('#users-table').DataTable({ function usersView(Grocy, scope = null)
'order': [[1, 'asc']], {
'columnDefs': [ var $scope = $;
{ 'orderable': false, 'targets': 0 }, if (scope != null)
{ 'searchable': false, "targets": 0 } {
].concat($.fn.dataTable.defaults.columnDefs) $scope = $(scope).find;
}); }
$('#users-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(usersTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox( var usersTable = $('#users-table').DataTable({
'Are you sure to delete user "%s"?', 'order': [[1, 'asc']],
'.user-delete-button', 'columnDefs': [
'data-user-username', { 'orderable': false, 'targets': 0 },
'data-user-id', { 'searchable': false, "targets": 0 }
'users/', ].concat($.fn.dataTable.defaults.columnDefs)
'/users' });
); $('#users-table tbody').removeClass("d-none");
Grocy.FrontendHelpers.InitDataTable(usersTable);
Grocy.FrontendHelpers.MakeDeleteConfirmBox(
'Are you sure to delete user "%s"?',
'.user-delete-button',
'data-user-username',
'data-user-id',
'users/',
'/users'
);
}

View File

@ -1,3 +1,13 @@
$("#locale").val(Grocy.UserSettings.locale); function usersettingsView(Grocy, scope = null)
{
var $scope = $;
if (scope != null)
{
$scope = $(scope).find;
}
RefreshLocaleNumberInput(); $("#locale").val(Grocy.UserSettings.locale);
RefreshLocaleNumberInput();
}