Unverified Commit c2889195 by Paul B

[AUTO] apply automatic fixes from eslint rules

parent 5753246a
var shelfs_table = null
var shelfs_table = null;
function init_datatable() {
return $('#lists').DataTable( {
return $('#lists').DataTable({
data: lists, // data passed at page loading
rowId: 'id',
columns:[
......@@ -10,7 +10,7 @@ function init_datatable() {
data:"datetime_created",
title:"Liste",
render: function (data, type, full, meta) {
return "Liste du " + data
return "Liste du " + data;
}
},
{data:"p_nb", title:"Nombre de réfs", width: "10%", className:"dt-body-center"},
......@@ -21,42 +21,47 @@ function init_datatable() {
width: "15%",
render: function (data, type, full, meta) {
if (data == '')
return "<button class='btn--primary do_inventory'>Inventaire en rayon</button>"
return "<button class='btn--primary do_inventory'>Inventaire en rayon</button>";
else
return "<button class='btn--success do_inventory'>Inventaire en réserve</button>"
return "<button class='btn--success do_inventory'>Inventaire en réserve</button>";
}
}
],
dom: 'rtip',
order: [[ 1, "asc" ]],
order: [
[
1,
"asc"
]
],
iDisplayLength: 25,
language: {url : '/static/js/datatables/french.json'}
})
});
}
function go_to_inventory() {
openModal()
openModal();
var clicked = $(this)
var row_data = shelfs_table.row(clicked.parents('tr')).data()
var clicked = $(this);
var row_data = shelfs_table.row(clicked.parents('tr')).data();
// Use local storage to pass data to next page
if (Modernizr.localstorage) {
var stored_list = JSON.parse(localStorage.getItem('custom_list_' + row_data.id))
var stored_list = JSON.parse(localStorage.getItem('custom_list_' + row_data.id));
// Set local storage if key doesn't exist
if (stored_list == null) {
localStorage.setItem("custom_list_" + row_data.id , JSON.stringify(row_data))
localStorage.setItem("custom_list_" + row_data.id, JSON.stringify(row_data));
}
}
document.location.href = "custom_list_inventory/" + row_data.id
document.location.href = "custom_list_inventory/" + row_data.id;
}
$(document).ready(function() {
console.log(lists)
shelfs_table = init_datatable()
console.log(lists);
shelfs_table = init_datatable();
$(document).on('click', 'button.do_inventory', go_to_inventory)
})
$(document).on('click', 'button.do_inventory', go_to_inventory);
});
var coop_page = $('#coop_page');
function show_checks_nb() {
$('#coop_validation_form').find('[name="checks_nb"]').show();
$('#coop_validation_form').find('[id="checks_nb_label"]').show();
$('#coop_validation_form').find('[name="checks_nb"]')
.show();
$('#coop_validation_form').find('[id="checks_nb_label"]')
.show();
}
function hide_checks_nb() {
$('#coop_validation_form').find('[name="checks_nb"]').hide();
$('#coop_validation_form').find('[name="checks_nb"]').val(0);
$('#coop_validation_form').find('[id="checks_nb_label"]').hide();
$('#coop_validation_form').find('[name="checks_nb"]')
.hide();
$('#coop_validation_form').find('[name="checks_nb"]')
.val(0);
$('#coop_validation_form').find('[id="checks_nb_label"]')
.hide();
}
function open_shift_choice() {
......@@ -22,20 +27,21 @@ function display_current_coop_form() {
chgt_shift_btn = $('#change_shift_template');
var ftop_shift = $('#choosen_shift [name="ftop"]'),
m_barcode = form.find('[name="m_barcode"]'),
sex = $('#sex')
sex = $('#sex');
let street2_input = form.find('[name="street2"]'),
phone_input = form.find('[name="phone"]')
phone_input = form.find('[name="phone"]');
chgt_shift_btn.hide();
chgt_shift_btn.off('click',open_shift_choice);
chgt_shift_btn.off('click', open_shift_choice);
form.find('[name="firstname"]').val(current_coop.firstname);
form.find('[name="lastname"]').val(current_coop.lastname);
if (m_barcode.length > 0 && typeof current_coop.m_barcode != "undefined") {
m_barcode.val(current_coop.m_barcode)
m_barcode.val(current_coop.m_barcode);
}
//console.log(current_coop)
if (sex.length > 0 && typeof current_coop.sex != "undefined") {
$("#" + current_coop.sex + "_sex").prop('checked', true)
$("#" + current_coop.sex + "_sex").prop('checked', true);
}
// form.find('[name="barcode_base"]').val(current_coop.barcode_base);
......@@ -64,16 +70,17 @@ function display_current_coop_form() {
form.find('[name="payment_meaning"]').val(current_coop.payment_meaning || '');
form.find('[name="checks_nb"]').val(current_coop.checks_nb || 0);
if (street2_input.length > 0) {
street2_input.val(current_coop.street2 || '')
street2_input.val(current_coop.street2 || '');
}
if (phone_input.length > 0) {
phone_input.val(current_coop.phone || '')
phone_input.val(current_coop.phone || '');
}
// Checks
form.find('[name="checks_nb"]').hide();
form.find('[id="checks_nb_label"]').hide();
$('#checks').hide();
var check_details = $('#checks').find('.check_details');
$(check_details).html('');
// Display checks number if paid by checks
if (current_coop.payment_meaning == "ch") {
......@@ -93,10 +100,12 @@ function display_current_coop_form() {
if (current_coop.shift_template) {
var st = current_coop.shift_template.data;
form.find('[name="week"]').val(weeks_name[st.week]);
form.find('[name="day"]').val(st.day);
form.find('[name="hour"]').val(st.begin);
var place = st.place;
if (place == mag_place_string) {
place = 'Magasin';
} else if (place == office_place_string) {
......@@ -112,17 +121,19 @@ function display_current_coop_form() {
if (show_change_shift == true) {
chgt_shift_btn.show();
chgt_shift_btn.on('click',open_shift_choice);
chgt_shift_btn.on('click', open_shift_choice);
}
if (typeof(coop_page) != "undefined"){coop_page.show();}
if (typeof(coop_page) != "undefined") {
coop_page.show();
}
}
$('#payment_meaning').change(function(){
if ($(this).val() == 'ch'){
show_checks_nb()
$('#payment_meaning').change(function() {
if ($(this).val() == 'ch') {
show_checks_nb();
} else {
hide_checks_nb()
hide_checks_nb();
}
});
......@@ -7,22 +7,22 @@ let vform = $('#coop_validation_form'),
wform.hide();
vform.find('input').attr('required','required');
vform.find('input').attr('required', 'required');
// Setting required to fields doesn't prevent submit with empty fields anymore !!!
// TODO : Find out why
if (street2.length > 0) street2.get(0).removeAttribute('required')
if (phone.length > 0) phone.get(0).removeAttribute('required')
vform.find('[name="shares_nb"]').attr('disabled','disabled');
vform.find('[name="shares_euros"]').attr('disabled','disabled');
vform.find('[name="checks_nb"]').attr('disabled','disabled');
vform.find('[name="country"]').attr('disabled','disabled');
vform.find('[name="email"]').attr('disabled','disabled');
if (street2.length > 0) street2.get(0).removeAttribute('required');
if (phone.length > 0) phone.get(0).removeAttribute('required');
vform.find('[name="shares_nb"]').attr('disabled', 'disabled');
vform.find('[name="shares_euros"]').attr('disabled', 'disabled');
vform.find('[name="checks_nb"]').attr('disabled', 'disabled');
vform.find('[name="country"]').attr('disabled', 'disabled');
vform.find('[name="email"]').attr('disabled', 'disabled');
if (m_barcode.length > 0) {
m_barcode.attr('disabled','disabled')
m_barcode.attr('disabled', 'disabled');
}
function show_warning_form(){
function show_warning_form() {
vform.hide();
wform.show();
}
......@@ -36,25 +36,32 @@ function show_coop_form() {
function process_form_submission(event){
function process_form_submission(event) {
event.preventDefault();
var clicked = $(this),
fname = clicked.attr('name');
if (fname == 'valider'){
if (fname == 'valider') {
var form_data = new FormData(vform.get(0)),
has_empty_values = false;
if (sex.length > 0) {
//value attrribute is emptied when form is loaded !!
//so, we have to retrive sex value using unusual way
form_data.set('sex',
$('input[name="sex"]:checked').attr('id').replace('_sex',''))
form_data.set(
'sex',
$('input[name="sex"]:checked').attr('id')
.replace('_sex', '')
);
}
for (var pair of form_data.entries()) {
let val = pair[1],
key = pair[0]
if ($('input[name="' + key +'"]').get(0).hasAttribute('required') && val.length == 0) {
has_empty_values = true
key = pair[0];
if ($('input[name="' + key +'"]').get(0)
.hasAttribute('required') && val.length == 0) {
has_empty_values = true;
}
}
......@@ -62,27 +69,35 @@ function process_form_submission(event){
if (has_empty_values == true) {
alert('Vous devez remplir tous les champs pour valider.');
} else {
form_data.set('firstname',
vform.find('input[name="firstname"]').val().toFormatedFirstName());
form_data.set('lastname',
vform.find('input[name="lastname"]').val().toFormatedLastName());
form_data.set(
'firstname',
vform.find('input[name="firstname"]').val()
.toFormatedFirstName()
);
form_data.set(
'lastname',
vform.find('input[name="lastname"]').val()
.toFormatedLastName()
);
form_data.set('odoo_id', current_coop.odoo_id);
form_data.set('shift_template', JSON.stringify(current_coop.shift_template));
form_data.set('shares_euros',vform.find('input[name="shares_euros"]').val())
form_data.set('email',current_coop._id);
form_data.set('shares_nb',current_coop.shares_nb);
form_data.set('shares_euros', vform.find('input[name="shares_euros"]').val());
form_data.set('email', current_coop._id);
form_data.set('shares_nb', current_coop.shares_nb);
form_data.set('checks_nb', current_coop.checks_nb);
form_data.set('country', current_coop.country);
if (m_barcode.length > 0) {
form_data.set('m_barcode', current_coop.m_barcode)
form_data.set('m_barcode', current_coop.m_barcode);
}
openModal()
post_form('/members/coop_validated_data',form_data,
function(err,result){
openModal();
post_form(
'/members/coop_validated_data', form_data,
function(err, result) {
closeModal();
if (!err) {
var msg = "Vous êtes maintenant enregistré ! ";
msg += "<a href='" + em_url + "'>Cliquez ici</a> ";
msg += "pour découvrir l'espace membre";
$('p.intro').remove();
......@@ -91,24 +106,28 @@ function process_form_submission(event){
}
});
}
);
}
} else if (fname =='warning') {
var msg = $('textarea[name="message"]').val();
var data = {'odoo_id': current_coop.odoo_id,
'msg': msg,'_rev': current_coop._rev,'_id': current_coop._id};
openModal()
post_form('/members/coop_warning_msg',data,
function(err,result){
'msg': msg, '_rev': current_coop._rev, '_id': current_coop._id};
openModal();
post_form(
'/members/coop_warning_msg', data,
function(err, result) {
closeModal();
if (!err) {
$('#main_content').remove()
$('#main_content').remove();
display_msg_box('Message enregistré ! Le bureau des membres est averti.');
}
});
}
);
}
}
......@@ -116,8 +135,9 @@ try {
current_coop = coop;
display_current_coop_form();
var w_msg = current_coop.coop_msg || '';
wform.find('textarea').val(w_msg);
} catch(e) {
} catch (e) {
console.log(e);
}
......
......@@ -5,10 +5,12 @@
init: function(id) {
var box = document.getElementById(id);
var node;
SelectBox.cache[id] = [];
var cache = SelectBox.cache[id];
var boxOptions = box.options;
var boxOptionsLength = boxOptions.length;
for (var i = 0, j = boxOptionsLength; i < j; i++) {
node = boxOptions[i];
cache.push({value: node.value, text: node.text, displayed: 1});
......@@ -18,14 +20,17 @@
// Repopulate HTML select box from cache
var box = document.getElementById(id);
var node;
$(box).empty(); // clear all options
var new_options = box.outerHTML.slice(0, -9); // grab just the opening tag
var cache = SelectBox.cache[id];
for (var i = 0, j = cache.length; i < j; i++) {
node = cache[i];
if (node.displayed) {
var new_option = new Option(node.text, node.value, false, false);
// Shows a tooltip when hovering over the option
new_option.setAttribute("title", node.text);
new_options += new_option.outerHTML;
}
......@@ -39,11 +44,13 @@
var tokens = text.toLowerCase().split(/\s+/);
var node, token;
var cache = SelectBox.cache[id];
for (var i = 0, j = cache.length; i < j; i++) {
node = cache[i];
node.displayed = 1;
var node_text = node.text.toLowerCase();
var numTokens = tokens.length;
for (var k = 0; k < numTokens; k++) {
token = tokens[k];
if (node_text.indexOf(token) === -1) {
......@@ -57,6 +64,7 @@
delete_from_cache: function(id, value) {
var node, delete_index = null;
var cache = SelectBox.cache[id];
for (var i = 0, j = cache.length; i < j; i++) {
node = cache[i];
if (node.value === value) {
......@@ -73,12 +81,14 @@
// Check if an item is contained in the cache
var node;
var cache = SelectBox.cache[id];
for (var i = 0, j = cache.length; i < j; i++) {
node = cache[i];
if (node.value === value) {
return true;
}
}
return false;
},
move: function(from, to) {
......@@ -86,9 +96,11 @@
var option;
var boxOptions = from_box.options;
var boxOptionsLength = boxOptions.length;
for (var i = 0, j = boxOptionsLength; i < j; i++) {
option = boxOptions[i];
var option_value = option.value;
if (option.selected && SelectBox.cache_contains(from, option_value)) {
SelectBox.add_to_cache(to, {value: option_value, text: option.text, displayed: 1});
SelectBox.delete_from_cache(from, option_value);
......@@ -102,9 +114,11 @@
var option;
var boxOptions = from_box.options;
var boxOptionsLength = boxOptions.length;
for (var i = 0, j = boxOptionsLength; i < j; i++) {
option = boxOptions[i];
var option_value = option.value;
if (SelectBox.cache_contains(from, option_value)) {
SelectBox.add_to_cache(to, {value: option_value, text: option.text, displayed: 1});
SelectBox.delete_from_cache(from, option_value);
......@@ -124,21 +138,23 @@
if (a < b) {
return -1;
}
}
catch (e) {
} catch (e) {
// silently fail on IE 'unknown' exception
}
return 0;
} );
});
},
select_all: function(id) {
var box = document.getElementById(id);
var boxOptions = box.options;
var boxOptionsLength = boxOptions.length;
for (var i = 0; i < boxOptionsLength; i++) {
boxOptions[i].selected = 'selected';
}
}
};
window.SelectBox = SelectBox;
})(django.jQuery);
......@@ -11,6 +11,7 @@ Requires jQuery, core.js, and SelectBox.js.
if (node.tagName.toLowerCase() !== 'form') {
return findForm(node.parentNode);
}
return node;
}
......@@ -21,10 +22,12 @@ Requires jQuery, core.js, and SelectBox.js.
return;
}
var from_box = document.getElementById(field_id);
from_box.id += '_from'; // change its ID
from_box.className = 'filtered';
var ps = from_box.parentNode.getElementsByTagName('p');
for (var i = 0; i < ps.length; i++) {
if (ps[i].className.indexOf("info") !== -1) {
// Remove <p class="info">, because it just gets in the way.
......@@ -39,26 +42,28 @@ Requires jQuery, core.js, and SelectBox.js.
// <div class="selector"> or <div class="selector stacked">
var selector_div = quickElement('div', from_box.parentNode);
selector_div.className = is_stacked ? 'selector stacked' : 'selector';
// <div class="selector-available">
var selector_available = quickElement('div', selector_div);
selector_available.className = 'selector-available';
var title_available = quickElement('h2', selector_available, interpolate(gettext('Available %s') + ' ', [field_name]));
quickElement(
'span', title_available, '',
'class', 'help help-tooltip help-icon',
'title', interpolate(
gettext(
'This is the list of available %s. You may choose some by ' +
gettext('This is the list of available %s. You may choose some by ' +
'selecting them in the box below and then clicking the ' +
'"Choose" arrow between the two boxes.'
),
'"Choose" arrow between the two boxes.'),
[field_name]
)
);
var filter_p = quickElement('p', selector_available, '', 'id', field_id + '_filter');
filter_p.className = 'selector-filter';
var search_filter_label = quickElement('label', filter_p, '', 'for', field_id + '_input');
......@@ -72,40 +77,47 @@ Requires jQuery, core.js, and SelectBox.js.
filter_p.appendChild(document.createTextNode(' '));
var filter_input = quickElement('input', filter_p, '', 'type', 'text', 'placeholder', gettext("Filter"));
filter_input.id = field_id + '_input';
selector_available.appendChild(from_box);
var choose_all = quickElement('a', selector_available, gettext('Choose all'), 'title', interpolate(gettext('Click to choose all %s at once.'), [field_name]), 'href', '#', 'id', field_id + '_add_all_link');
choose_all.className = 'selector-chooseall';
// <ul class="selector-chooser">
var selector_chooser = quickElement('ul', selector_div);
selector_chooser.className = 'selector-chooser';
var add_link = quickElement('a', quickElement('li', selector_chooser), gettext('Choose'), 'title', gettext('Choose'), 'href', '#', 'id', field_id + '_add_link');
add_link.className = 'selector-add';
var remove_link = quickElement('a', quickElement('li', selector_chooser), gettext('Remove'), 'title', gettext('Remove'), 'href', '#', 'id', field_id + '_remove_link');
remove_link.className = 'selector-remove';
// <div class="selector-chosen">
var selector_chosen = quickElement('div', selector_div);
selector_chosen.className = 'selector-chosen';
var title_chosen = quickElement('h2', selector_chosen, interpolate(gettext('Chosen %s') + ' ', [field_name]));
quickElement(
'span', title_chosen, '',
'class', 'help help-tooltip help-icon',
'title', interpolate(
gettext(
'This is the list of chosen %s. You may remove some by ' +
gettext('This is the list of chosen %s. You may remove some by ' +
'selecting them in the box below and then clicking the ' +
'"Remove" arrow between the two boxes.'
),
'"Remove" arrow between the two boxes.'),
[field_name]
)
);
var to_box = quickElement('select', selector_chosen, '', 'id', field_id + '_to', 'multiple', 'multiple', 'size', from_box.size, 'name', from_box.getAttribute('name'));
to_box.className = 'filtered';
var clear_all = quickElement('a', selector_chosen, gettext('Remove all'), 'title', interpolate(gettext('Click to remove all chosen %s at once.'), [field_name]), 'href', '#', 'id', field_id + '_remove_all_link');
clear_all.className = 'selector-clearall';
from_box.setAttribute('name', from_box.getAttribute('name') + '_old');
......@@ -118,6 +130,7 @@ Requires jQuery, core.js, and SelectBox.js.
}
e.preventDefault();
};
choose_all.addEventListener('click', function(e) {
move_selection(e, this, SelectBox.move_all, field_id + '_from', field_id + '_to');
});
......@@ -166,7 +179,10 @@ Requires jQuery, core.js, and SelectBox.js.
// In horizontal mode, give the same height to the two boxes.
var j_from_box = $(from_box);
var j_to_box = $(to_box);
var resize_filters = function() { j_to_box.height($(filter_p).outerHeight() + j_from_box.outerHeight()); };
var resize_filters = function() {
j_to_box.height($(filter_p).outerHeight() + j_from_box.outerHeight());
};
if (j_from_box.outerHeight() > 0) {
resize_filters(); // This fieldset is already open. Resize now.
} else {
......@@ -180,6 +196,7 @@ Requires jQuery, core.js, and SelectBox.js.
},
any_selected: function(field) {
var any_selected = false;
try {
// Temporarily add the required attribute and check validity.
// This is much faster in WebKit browsers than the fallback.
......@@ -190,12 +207,14 @@ Requires jQuery, core.js, and SelectBox.js.
// Browsers that don't support :valid (IE < 10)
any_selected = field.find('option:selected').length > 0;
}
return any_selected;
},
refresh_icons: function(field_id) {
var from = $('#' + field_id + '_from');
var to = $('#' + field_id + '_to');
// Active if at least one item is selected
$('#' + field_id + '_add_link').toggleClass('active', SelectFilter.any_selected(from));
$('#' + field_id + '_remove_link').toggleClass('active', SelectFilter.any_selected(to));
// Active if the corresponding box isn't empty
......@@ -205,28 +224,35 @@ Requires jQuery, core.js, and SelectBox.js.
filter_key_press: function(event, field_id) {
var from = document.getElementById(field_id + '_from');
// don't submit form if user pressed Enter
if ((event.which && event.which === 13) || (event.keyCode && event.keyCode === 13)) {
from.selectedIndex = 0;
SelectBox.move(field_id + '_from', field_id + '_to');
from.selectedIndex = 0;
event.preventDefault();
return false;
}
},
filter_key_up: function(event, field_id) {
var from = document.getElementById(field_id + '_from');
var temp = from.selectedIndex;
SelectBox.filter(field_id + '_from', document.getElementById(field_id + '_input').value);
from.selectedIndex = temp;
return true;
},
filter_key_down: function(event, field_id) {
var from = document.getElementById(field_id + '_from');
// right arrow -- move across
if ((event.which && event.which === 39) || (event.keyCode && event.keyCode === 39)) {
var old_index = from.selectedIndex;
SelectBox.move(field_id + '_from', field_id + '_to');
from.selectedIndex = (old_index === from.length) ? from.length - 1 : old_index;
return false;
}
// down arrow -- wrap around
......@@ -237,6 +263,7 @@ Requires jQuery, core.js, and SelectBox.js.
if ((event.which && event.which === 38) || (event.keyCode && event.keyCode === 38)) {
from.selectedIndex = (from.selectedIndex === 0) ? from.length - 1 : from.selectedIndex - 1;
}
return true;
}
};
......@@ -245,6 +272,7 @@ Requires jQuery, core.js, and SelectBox.js.
$('select.selectfilter, select.selectfilterstacked').each(function() {
var $el = $(this),
data = $el.data();
SelectFilter.init($el.attr('id'), data.fieldName, parseInt(data.isStacked, 10));
});
});
......
......@@ -37,20 +37,23 @@
reset();
}
$(actionCheckboxes).prop("checked", checked)
.parent().parent().toggleClass(options.selectedClass, checked);
.parent()
.parent()
.toggleClass(options.selectedClass, checked);
},
updateCounter = function() {
var sel = $(actionCheckboxes).filter(":checked").length;
// data-actions-icnt is defined in the generated HTML
// and contains the total amount of objects in the queryset
var actions_icnt = $('.action-counter').data('actionsIcnt');
$(options.counterContainer).html(interpolate(
ngettext('%(sel)s of %(cnt)s selected', '%(sel)s of %(cnt)s selected', sel), {
$(options.counterContainer).html(interpolate(ngettext('%(sel)s of %(cnt)s selected', '%(sel)s of %(cnt)s selected', sel), {
sel: sel,
cnt: actions_icnt
}, true));
$(options.allToggle).prop("checked", function() {
var value;
if (sel === actionCheckboxes.length) {
value = true;
showQuestion();
......@@ -58,20 +61,26 @@
value = false;
clearAcross();
}
return value;
});
};
// Show counter by default
$(options.counterContainer).show();
// Check state of checkboxes and reinit state if needed
$(this).filter(":checked").each(function(i) {
$(this).parent().parent().toggleClass(options.selectedClass);
$(this).filter(":checked")
.each(function(i) {
$(this).parent()
.parent()
.toggleClass(options.selectedClass);
updateCounter();
if ($(options.acrossInput).val() === 1) {
showClear();
}
});
$(options.allToggle).show().click(function() {
$(options.allToggle).show()
.click(function() {
checker($(this).prop("checked"));
updateCounter();
});
......@@ -89,23 +98,33 @@
});
lastChecked = null;
$(actionCheckboxes).click(function(event) {
if (!event) { event = window.event; }
if (!event) {
event = window.event;
}
var target = event.target ? event.target : event.srcElement;
if (lastChecked && $.data(lastChecked) !== $.data(target) && event.shiftKey === true) {
var inrange = false;
$(lastChecked).prop("checked", target.checked)
.parent().parent().toggleClass(options.selectedClass, target.checked);
.parent()
.parent()
.toggleClass(options.selectedClass, target.checked);
$(actionCheckboxes).each(function() {
if ($.data(this) === $.data(lastChecked) || $.data(this) === $.data(target)) {
inrange = (inrange) ? false : true;
}
if (inrange) {
$(this).prop("checked", target.checked)
.parent().parent().toggleClass(options.selectedClass, target.checked);
.parent()
.parent()
.toggleClass(options.selectedClass, target.checked);
}
});
}
$(target).parent().parent().toggleClass(options.selectedClass, target.checked);
$(target).parent()
.parent()
.toggleClass(options.selectedClass, target.checked);
lastChecked = target;
updateCounter();
});
......@@ -119,6 +138,7 @@
});
$('form#changelist-form input[name="_save"]').click(function(event) {
var action_changed = false;
$('select option:selected', options.actionContainer).each(function() {
if ($(this).val()) {
action_changed = true;
......@@ -146,6 +166,7 @@
};
$(document).ready(function() {
var $actionsEls = $('tr input.action-select');
if ($actionsEls.length > 0) {
$actionsEls.actions();
}
......
......@@ -12,19 +12,23 @@
function id_to_windowname(text) {
text = text.replace(/\./g, '__dot__');
text = text.replace(/\-/g, '__dash__');
return text;
}
function windowname_to_id(text) {
text = text.replace(/__dot__/g, '.');
text = text.replace(/__dash__/g, '-');
return text;
}
function showAdminPopup(triggeringLink, name_regexp, add_popup) {
var name = triggeringLink.id.replace(name_regexp, '');
name = id_to_windowname(name);
var href = triggeringLink.href;
if (add_popup) {
if (href.indexOf('?') === -1) {
href += '?_popup=1';
......@@ -33,7 +37,9 @@
}
}
var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
}
......@@ -44,6 +50,7 @@
function dismissRelatedLookupPopup(win, chosenId) {
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem.className.indexOf('vManyToManyRawIdAdminField') !== -1 && elem.value) {
elem.value += ',' + chosenId;
} else {
......@@ -59,13 +66,16 @@
function updateRelatedObjectLinks(triggeringLink) {
var $this = $(triggeringLink);
var siblings = $this.nextAll('.change-related, .delete-related');
if (!siblings.length) {
return;
}
var value = $this.val();
if (value) {
siblings.each(function() {
var elm = $(this);
elm.attr('href', elm.attr('data-href-template').replace('__fk__', value));
});
} else {
......@@ -76,8 +86,10 @@
function dismissAddRelatedObjectPopup(win, newId, newRepr) {
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem) {
var elemName = elem.nodeName.toUpperCase();
if (elemName === 'SELECT') {
elem.options[elem.options.length] = new Option(newRepr, newId, true, true);
} else if (elemName === 'INPUT') {
......@@ -92,6 +104,7 @@
} else {
var toId = name + "_to";
var o = new Option(newRepr, newId);
SelectBox.add_to_cache(toId, o);
SelectBox.redisplay(toId);
}
......@@ -100,15 +113,21 @@
function dismissChangeRelatedObjectPopup(win, objId, newRepr, newId) {
var id = windowname_to_id(win.name).replace(/^edit_/, '');
var selectsSelector = interpolate('#%s, #%s_from, #%s_to', [id, id, id]);
var selectsSelector = interpolate('#%s, #%s_from, #%s_to', [
id,
id,
id
]);
var selects = $(selectsSelector);
selects.find('option').each(function() {
if (this.value === objId) {
this.textContent = newRepr;
this.value = newId;
}
});
selects.next().find('.select2-selection__rendered').each(function() {
selects.next().find('.select2-selection__rendered')
.each(function() {
// The element can have a clear button as a child.
// Use the lastChild to modify only the displayed value.
this.lastChild.textContent = newRepr;
......@@ -119,13 +138,19 @@
function dismissDeleteRelatedObjectPopup(win, objId) {
var id = windowname_to_id(win.name).replace(/^delete_/, '');
var selectsSelector = interpolate('#%s, #%s_from, #%s_to', [id, id, id]);
var selectsSelector = interpolate('#%s, #%s_from, #%s_to', [
id,
id,
id
]);
var selects = $(selectsSelector);
selects.find('option').each(function() {
if (this.value === objId) {
$(this).remove();
}
}).trigger('change');
})
.trigger('change');
win.close();
}
......@@ -154,6 +179,7 @@
e.preventDefault();
if (this.href) {
var event = $.Event('django:show-related', {href: this.href});
$(this).trigger(event);
if (!event.isDefaultPrevented()) {
showRelatedObjectPopup(this);
......@@ -162,6 +188,7 @@
});
$('body').on('change', '.related-widget-wrapper select', function(e) {
var event = $.Event('django:update-related');
$(this).trigger(event);
if (!event.isDefaultPrevented()) {
updateRelatedObjectLinks(this);
......@@ -171,6 +198,7 @@
$('body').on('click', '.related-lookup', function(e) {
e.preventDefault();
var event = $.Event('django:lookup-related');
$(this).trigger(event);
if (!event.isDefaultPrevented()) {
showRelatedObjectLookupPopup(this);
......
......@@ -11,22 +11,27 @@
}
}
}, options);
$element.select2(settings);
};
$.fn.djangoAdminSelect2 = function(options) {
var settings = $.extend({}, options);
$.each(this, function(i, element) {
var $element = $(element);
init($element, settings);
});
return this;
};
$(function() {
// Initialize all autocomplete widgets except the one in the template
// form used when a new formset is added.
$('.admin-autocomplete').not('[name*=__prefix__]').djangoAdminSelect2();
$('.admin-autocomplete').not('[name*=__prefix__]')
.djangoAdminSelect2();
});
$(document).on('formset:added', (function() {
......
......@@ -33,22 +33,21 @@ depends on core.js for utility functions like removeChildren or quickElement
],
firstDayOfWeek: parseInt(get_format('FIRST_DAY_OF_WEEK')),
isLeapYear: function(year) {
return (((year % 4) === 0) && ((year % 100) !== 0 ) || ((year % 400) === 0));
return (((year % 4) === 0) && ((year % 100) !== 0) || ((year % 400) === 0));
},
getDaysInMonth: function(month, year) {
var days;
if (month === 1 || month === 3 || month === 5 || month === 7 || month === 8 || month === 10 || month === 12) {
days = 31;
}
else if (month === 4 || month === 6 || month === 9 || month === 11) {
} else if (month === 4 || month === 6 || month === 9 || month === 11) {
days = 30;
}
else if (month === 2 && CalendarNamespace.isLeapYear(year)) {
} else if (month === 2 && CalendarNamespace.isLeapYear(year)) {
days = 29;
}
else {
} else {
days = 28;
}
return days;
},
draw: function(month, year, div_id, callback, selected) { // month = 1-12, year = 1-9999
......@@ -70,6 +69,7 @@ depends on core.js for utility functions like removeChildren or quickElement
// The day variable above will be 1 instead of 2 in, say, US Pacific time
// zone.
var isSelectedMonth = false;
if (typeof selected !== 'undefined') {
isSelectedMonth = (selected.getUTCFullYear() === year && (selected.getUTCMonth() + 1) === month);
}
......@@ -77,13 +77,16 @@ depends on core.js for utility functions like removeChildren or quickElement
month = parseInt(month);
year = parseInt(year);
var calDiv = document.getElementById(div_id);
removeChildren(calDiv);
var calTable = document.createElement('table');
quickElement('caption', calTable, CalendarNamespace.monthsOfYear[month - 1] + ' ' + year);
var tableBody = quickElement('tbody', calTable);
// Draw days-of-week header
var tableRow = quickElement('tr', tableBody);
for (var i = 0; i < 7; i++) {
quickElement('th', tableRow, CalendarNamespace.daysOfWeek[(i + CalendarNamespace.firstDayOfWeek) % 7]);
}
......@@ -105,11 +108,13 @@ depends on core.js for utility functions like removeChildren or quickElement
e.preventDefault();
callback(y, m, this.textContent);
}
return onClick;
}
// Draw days of month
var currentDay = 1;
for (i = startingPos; currentDay <= days; i++) {
if (i % 7 === 0 && currentDay !== 1) {
tableRow = quickElement('tr', tableBody);
......@@ -130,6 +135,7 @@ depends on core.js for utility functions like removeChildren or quickElement
var cell = quickElement('td', tableRow, '', 'class', todayClass);
var link = quickElement('a', cell, currentDay, 'href', '#');
link.addEventListener('click', calendarMonth(year, month));
currentDay++;
}
......@@ -168,7 +174,7 @@ depends on core.js for utility functions like removeChildren or quickElement
this.currentMonth = month;
this.currentYear = year;
if(selected) {
if (selected) {
this.selected = selected;
}
......@@ -178,8 +184,7 @@ depends on core.js for utility functions like removeChildren or quickElement
if (this.currentMonth === 1) {
this.currentMonth = 12;
this.currentYear--;
}
else {
} else {
this.currentMonth--;
}
this.drawCurrent();
......@@ -188,8 +193,7 @@ depends on core.js for utility functions like removeChildren or quickElement
if (this.currentMonth === 12) {
this.currentMonth = 1;
this.currentYear++;
}
else {
} else {
this.currentMonth++;
}
this.drawCurrent();
......
......@@ -4,9 +4,11 @@
'use strict';
$(document).ready(function() {
var modelName = $('#django-admin-form-add-constants').data('modelName');
$('body').on('click', '.add-another', function(e) {
e.preventDefault();
var event = $.Event('django:add-another-related');
$(this).trigger(event);
if (!event.isDefaultPrevented()) {
showAddAnotherPopup(this);
......
......@@ -6,20 +6,31 @@
$("fieldset.collapse").each(function(i, elem) {
// Don't hide if fields in this fieldset have errors
if ($(elem).find("div.errors").length === 0) {
$(elem).addClass("collapsed").find("h2").first().append(' (<a id="fieldsetcollapser' +
$(elem).addClass("collapsed")
.find("h2")
.first()
.append(' (<a id="fieldsetcollapser' +
i + '" class="collapse-toggle" href="#">' + gettext("Show") +
'</a>)');
}
});
// Add toggle to anchor tag
$("fieldset.collapse a.collapse-toggle").click(function(ev) {
if ($(this).closest("fieldset").hasClass("collapsed")) {
if ($(this).closest("fieldset")
.hasClass("collapsed")) {
// Show
$(this).text(gettext("Hide")).closest("fieldset").removeClass("collapsed").trigger("show.fieldset", [$(this).attr("id")]);
$(this).text(gettext("Hide"))
.closest("fieldset")
.removeClass("collapsed")
.trigger("show.fieldset", [$(this).attr("id")]);
} else {
// Hide
$(this).text(gettext("Show")).closest("fieldset").addClass("collapsed").trigger("hide.fieldset", [$(this).attr("id")]);
$(this).text(gettext("Show"))
.closest("fieldset")
.addClass("collapsed")
.trigger("hide.fieldset", [$(this).attr("id")]);
}
return false;
});
});
......
......@@ -8,15 +8,19 @@ var isIE = ((document.all) && (!isOpera)) && parseFloat(navigator.appVersion.spl
function quickElement() {
'use strict';
var obj = document.createElement(arguments[0]);
if (arguments[2]) {
var textNode = document.createTextNode(arguments[2]);
obj.appendChild(textNode);
}
var len = arguments.length;
for (var i = 3; i < len; i += 2) {
obj.setAttribute(arguments[i], arguments[i + 1]);
}
arguments[1].appendChild(obj);
return obj;
}
......@@ -35,6 +39,7 @@ function removeChildren(a) {
function findPosX(obj) {
'use strict';
var curleft = 0;
if (obj.offsetParent) {
while (obj.offsetParent) {
curleft += obj.offsetLeft - ((isOpera) ? 0 : obj.scrollLeft);
......@@ -47,12 +52,14 @@ function findPosX(obj) {
} else if (obj.x) {
curleft += obj.x;
}
return curleft;
}
function findPosY(obj) {
'use strict';
var curtop = 0;
if (obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop - ((isOpera) ? 0 : obj.scrollTop);
......@@ -65,6 +72,7 @@ function findPosY(obj) {
} else if (obj.y) {
curtop += obj.y;
}
return curtop;
}
......@@ -75,10 +83,10 @@ function findPosY(obj) {
'use strict';
Date.prototype.getTwelveHours = function() {
var hours = this.getHours();
if (hours === 0) {
return 12;
}
else {
} else {
return hours <= 12 ? hours : hours - 12;
}
};
......@@ -140,27 +148,30 @@ function findPosY(obj) {
'%': '%'
};
var result = '', i = 0;
while (i < format.length) {
if (format.charAt(i) === '%') {
result = result + fields[format.charAt(i + 1)];
++i;
}
else {
} else {
result = result + format.charAt(i);
}
++i;
}
return result;
};
// ----------------------------------------------------------------------------
// String object extensions
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// String object extensions
// ----------------------------------------------------------------------------
String.prototype.pad_left = function(pad_length, pad_string) {
var new_string = this;
for (var i = 0; new_string.length < pad_length; i++) {
new_string = pad_string + new_string;
}
return new_string;
};
......@@ -169,6 +180,7 @@ function findPosY(obj) {
var date = this.split(/[.\-/]/);
var i = 0;
var day, month, year;
while (i < split_format.length) {
switch (split_format[i]) {
case "%d":
......@@ -199,14 +211,15 @@ function findPosY(obj) {
function getStyle(oElm, strCssRule) {
'use strict';
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle) {
if (document.defaultView && document.defaultView.getComputedStyle) {
strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
}
else if(oElm.currentStyle) {
} else if (oElm.currentStyle) {
strCssRule = strCssRule.replace(/\-(\w)/g, function(strMatch, p1) {
return p1.toUpperCase();
});
strValue = oElm.currentStyle[strCssRule];
}
return strValue;
}
......@@ -24,8 +24,10 @@
var updateElementIndex = function(el, prefix, ndx) {
var id_regex = new RegExp("(" + prefix + "-(\\d+|__prefix__))");
var replacement = prefix + "-" + ndx;
if ($(el).prop("for")) {
$(el).prop("for", $(el).prop("for").replace(id_regex, replacement));
$(el).prop("for", $(el).prop("for")
.replace(id_regex, replacement));
}
if (el.id) {
el.id = el.id.replace(id_regex, replacement);
......@@ -40,28 +42,34 @@
// only show the add button if we are allowed to add more items,
// note that max_num = None translates to a blank string.
var showAddButton = maxForms.val() === '' || (maxForms.val() - totalForms.val()) > 0;
$this.each(function(i) {
$(this).not("." + options.emptyCssClass).addClass(options.formCssClass);
$(this).not("." + options.emptyCssClass)
.addClass(options.formCssClass);
});
if ($this.length && showAddButton) {
var addButton = options.addButton;
if (addButton === null) {
if ($this.prop("tagName") === "TR") {
// If forms are laid out as table rows, insert the
// "add" button in a new table row:
var numCols = this.eq(-1).children().length;
$parent.append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + '"><a href="#">' + options.addText + "</a></tr>");
addButton = $parent.find("tr:last a");
} else {
// Otherwise, insert it immediately after the last form:
$this.filter(":last").after('<div class="' + options.addCssClass + '"><a href="#">' + options.addText + "</a></div>");
addButton = $this.filter(":last").next().find("a");
addButton = $this.filter(":last").next()
.find("a");
}
}
addButton.click(function(e) {
e.preventDefault();
var template = $("#" + options.prefix + "-empty");
var row = template.clone(true);
row.removeClass(options.emptyCssClass)
.addClass(options.formCssClass)
.attr("id", options.prefix + "-" + nextIndex);
......@@ -100,9 +108,13 @@
if (options.removed) {
options.removed(row);
}
$(document).trigger('formset:removed', [row, options.prefix]);
$(document).trigger('formset:removed', [
row,
options.prefix
]);
// Update the TOTAL_FORMS form count.
var forms = $("." + options.formCssClass);
$("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length);
// Show add button again once we drop below max
if ((maxForms.val() === '') || (maxForms.val() - forms.length) > 0) {
......@@ -114,18 +126,24 @@
var updateElementCallback = function() {
updateElementIndex(this, options.prefix, i);
};
for (i = 0, formCount = forms.length; i < formCount; i++) {
updateElementIndex($(forms).get(i), options.prefix, i);
$(forms.get(i)).find("*").each(updateElementCallback);
$(forms.get(i)).find("*")
.each(updateElementCallback);
}
});
// If a post-add callback was supplied, call it with the added form:
if (options.added) {
options.added(row);
}
$(document).trigger('formset:added', [row, options.prefix]);
$(document).trigger('formset:added', [
row,
options.prefix
]);
});
}
return this;
};
......@@ -148,9 +166,13 @@
$.fn.tabularFormset = function(options) {
var $rows = $(this);
var alternatingRows = function(row) {
$($rows.selector).not(".add-row").removeClass("row1 row2")
.filter(":even").addClass("row1").end()
.filter(":odd").addClass("row2");
$($rows.selector).not(".add-row")
.removeClass("row1 row2")
.filter(":even")
.addClass("row1")
.end()
.filter(":odd")
.addClass("row2");
};
var reinitDateTimeShortCuts = function() {
......@@ -167,10 +189,12 @@
if (typeof SelectFilter !== 'undefined') {
$('.selectfilter').each(function(index, value) {
var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], false);
});
$('.selectfilterstacked').each(function(index, value) {
var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], true);
});
}
......@@ -182,8 +206,10 @@
input = field.find('input, select, textarea'),
dependency_list = input.data('dependency_list') || [],
dependencies = [];
$.each(dependency_list, function(i, field_name) {
dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea').attr('id'));
dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea')
.attr('id'));
});
if (dependencies.length) {
input.prepopulate(dependencies, input.attr('maxlength'));
......@@ -215,9 +241,12 @@
$.fn.stackedFormset = function(options) {
var $rows = $(this);
var updateInlineLabel = function(row) {
$($rows.selector).find(".inline_label").each(function(i) {
$($rows.selector).find(".inline_label")
.each(function(i) {
var count = i + 1;
$(this).html($(this).html().replace(/(#\d+)/g, "#" + count));
$(this).html($(this).html()
.replace(/(#\d+)/g, "#" + count));
});
};
......@@ -234,10 +263,12 @@
if (typeof SelectFilter !== "undefined") {
$(".selectfilter").each(function(index, value) {
var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], false);
});
$(".selectfilterstacked").each(function(index, value) {
var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], true);
});
}
......@@ -249,8 +280,10 @@
input = field.find('input, select, textarea'),
dependency_list = input.data('dependency_list') || [],
dependencies = [];
$.each(dependency_list, function(i, field_name) {
dependencies.push('#' + row.find('.form-row .field-' + field_name).find('input, select, textarea').attr('id'));
dependencies.push('#' + row.find('.form-row .field-' + field_name).find('input, select, textarea')
.attr('id'));
});
if (dependencies.length) {
input.prepopulate(dependencies, input.attr('maxlength'));
......@@ -282,7 +315,8 @@
$(".js-inline-admin-formset").each(function() {
var data = $(this).data(),
inlineOptions = data.inlineFormset;
switch(data.inlineType) {
switch (data.inlineType) {
case "stacked":
$(inlineOptions.name + "-group .inline-related").stackedFormset(inlineOptions.options);
break;
......
......@@ -2,7 +2,8 @@
(function() {
'use strict';
var initData = JSON.parse(document.getElementById('django-admin-popup-response-constants').dataset.popupResponse);
switch(initData.action) {
switch (initData.action) {
case 'change':
opener.dismissChangeRelatedObjectPopup(window, initData.value, initData.obj, initData.new_value);
break;
......
......@@ -20,6 +20,7 @@
}
var values = [];
$.each(dependencies, function(i, field) {
field = $(field);
if (field.val().length > 0) {
......@@ -35,7 +36,9 @@
});
if (!prepopulatedField.val()) {
$(dependencies.join(',')).keyup(populate).change(populate).focus(populate);
$(dependencies.join(',')).keyup(populate)
.change(populate)
.focus(populate);
}
});
};
......
(function($) {
'use strict';
var fields = $('#django-admin-prepopulated-fields-constants').data('prepopulatedFields');
$.each(fields, function(index, field) {
$('.empty-form .form-row .field-' + field.name + ', .empty-form.form-row .field-' + field.name).addClass('prepopulated_field');
$(field.id).data('dependency_list', field.dependency_list).prepopulate(
field.dependency_ids, field.maxLength, field.allowUnicode
);
$(field.id).data('dependency_list', field.dependency_list)
.prepopulate(field.dependency_ids, field.maxLength, field.allowUnicode);
});
})(django.jQuery);
......@@ -31,6 +31,7 @@
re: /^(\d+)\s*([ap])(?:.?m.?)?$/i,
handler: function(bits) {
var hour = parseInt(bits[1]);
if (hour === 12) {
hour = 0;
}
......@@ -38,6 +39,7 @@
if (hour === 12) {
hour = 0;
}
return (hour + 12) + ':00';
} else {
if (hour < 10) {
......@@ -54,6 +56,7 @@
handler: function(bits) {
var hour = parseInt(bits[1]);
var mins = parseInt(bits[2]);
if (mins < 10) {
mins = '0' + mins;
}
......@@ -64,6 +67,7 @@
if (hour === 12) {
hour = 0;
}
return (hour + 12) + ':' + mins;
} else {
if (hour < 10) {
......@@ -95,10 +99,12 @@
var re = timeParsePatterns[i].re;
var handler = timeParsePatterns[i].handler;
var bits = re.exec(s);
if (bits) {
return handler(bits);
}
}
return s;
}
......
jQuery(document).ready(function($){
jQuery(document).ready(function($) {
var month_sel = $("select[name$='_month']"),
year_sel = $("select[name$='_year']"),
default_month, default_year
default_month, default_year;
var now = new Date()
var current_month = now.getMonth() + 1 //jan = 0
var now = new Date();
var current_month = now.getMonth() + 1; //jan = 0
//Usually, export concerns previous month, so we select it as the default
if (current_month == 1){
default_month = 12
default_year = now.getFullYear() - 1
}
else {
default_month = current_month - 1
default_year = now.getFullYear()
if (current_month == 1) {
default_month = 12;
default_year = now.getFullYear() - 1;
} else {
default_month = current_month - 1;
default_year = now.getFullYear();
}
month_sel.find("option[value='" + default_month + "']").attr('selected','selected');
year_sel.find("option[value='" + default_year + "']").attr('selected','selected');
month_sel.find("option[value='" + default_month + "']").attr('selected', 'selected');
year_sel.find("option[value='" + default_year + "']").attr('selected', 'selected');
function wait_for_odoo_export_file (export_id, url) {
openWaiting('La demande de génération du document Odoo avec toutes les lignes comptables est lancée.<br/>Cela peut prendre plusieurs minutes.')
$.ajax({url : url + '?phase=1&export_id='+export_id ,
openWaiting('La demande de génération du document Odoo avec toutes les lignes comptables est lancée.<br/>Cela peut prendre plusieurs minutes.');
$.ajax({url : url + '?phase=1&export_id='+export_id,
dataType :'json'
})
.done(function(rData){
.done(function(rData) {
if (rData.response && rData.response == true) {
newWaitingMessage('Le document Odoo est terminé.<br/>Les ventes journalières sont compilées et les identifiants de coop. substitués.')
newWaitingMessage('Le document Odoo est terminé.<br/>Les ventes journalières sont compilées et les identifiants de coop. substitués.');
$.ajax({url : url + '?phase=2&export_id='+export_id+ '&final_format=' + $('[name="final_format"]').val(),
dataType :'json'
})
.done(function(rData){
.done(function(rData) {
if (rData.response && rData.response.file_path) {
var download_link = $('<a>').attr('href','/' + rData.response.file_path).text('Télécharger le fichier')
$('form').hide()
var download_link = $('<a>').attr('href', '/' + rData.response.file_path)
.text('Télécharger le fichier');
$('form').hide();
if (rData.response.sells_total) {
var preambule = $('<p>').html('A titre indicatif:')
var vente_ht = $('<p>').html('Ventes H.T: <strong>' + parseFloat(rData.response.sells_total).toFixed(2) + '</strong> € ')
var tva = $('<p>').html('TVA sur ventes: <strong>' + parseFloat(rData.response.vat_total).toFixed(2) + '</strong> € ')
var preambule = $('<p>').html('A titre indicatif:');
var vente_ht = $('<p>').html('Ventes H.T: <strong>' + parseFloat(rData.response.sells_total).toFixed(2) + '</strong> € ');
var tva = $('<p>').html('TVA sur ventes: <strong>' + parseFloat(rData.response.vat_total).toFixed(2) + '</strong> € ');
$('body')
.append(preambule)
.append(vente_ht)
.append(tva)
.append(download_link)
.append(download_link);
} else {
$('body').append(download_link)
$('body').append(download_link);
}
}
closeWaiting()
})
closeWaiting();
});
}
})
});
}
$('form').submit(function(){
var form = $(this)
var month = month_sel.val()
var year = year_sel.val()
if ( month > 0 && year > 0 && is_time_to('request_compta',120000)) {
month = new String(month).pad('0',2)
$('form').submit(function() {
var form = $(this);
var month = month_sel.val();
var year = year_sel.val();
if (month > 0 && year > 0 && is_time_to('request_compta', 120000)) {
month = new String(month).pad('0', 2);
data = {'from': year + '-' + month + '-01',
'to': year + '-' + month + '-' + new Date(year, month, 0).getDate()
}
url = form.attr('action')
post_form(url, data, function(error, rData){
};
url = form.attr('action');
post_form(url, data, function(error, rData) {
if (rData.response && !isNaN(rData.response))
wait_for_odoo_export_file (rData.response, url)
wait_for_odoo_export_file(rData.response, url);
else
alert("L'export ne peut pas se faire, merci de contacter le service informatique.")
})
alert("L'export ne peut pas se faire, merci de contacter le service informatique.");
});
} else {
if ( month > 0 && year > 0) {
alert('Délai trop court entre 2 demandes...')
if (month > 0 && year > 0) {
alert('Délai trop court entre 2 demandes...');
} else {
alert('La sélection du mois n\'est pas valable')
alert('La sélection du mois n\'est pas valable');
}
}
//always return false because form is processed through ajax call
return false
return false;
})
})
});
});
var param_template = $('#templates #param'),
submit_btn = $('#templates #submit_button'),
main_content = $('#main_content')
main_content = $('#main_content');
function save_module_settings() {
var form_data = new FormData(main_content.get(0))
var data = {}
for(var pair of form_data.entries()) {
var form_data = new FormData(main_content.get(0));
var data = {};
for (var pair of form_data.entries()) {
let val = pair[1],
key = pair[0]
let elt = main_content.find('[name="' + key +'"]')
data[key] = {title: elt.closest('.param').find('label').text(),
key = pair[0];
let elt = main_content.find('[name="' + key +'"]');
data[key] = {title: elt.closest('.param').find('label')
.text(),
type: elt.get(0).type,
value: val}
value: val};
}
post_form('settings', {params: JSON.stringify(data)},
function(err,result){
post_form(
'settings', {params: JSON.stringify(data)},
function(err, result) {
if (!err) {
var succeeded = false
var succeeded = false;
try {
if (result.res.save == true) {
display_msg_box('Enregistrement réussi !')
succeeded = true
display_msg_box('Enregistrement réussi !');
succeeded = true;
}
} catch(e) {
console.log(e)
} catch (e) {
console.log(e);
}
if (succeeded == false) display_msg_box('L\'enregistrement a échoué !', 'error')
if (succeeded == false) display_msg_box('L\'enregistrement a échoué !', 'error');
} else {
console.log(err)
console.log(err);
}
})
}
);
}
function get_module_settings() {
$.ajax('settings')
.done(function(rData){
.done(function(rData) {
try {
if (typeof rData.res.settings != "undefined"){
var added_elts = []
if (typeof rData.res.settings != "undefined") {
var added_elts = [];
for (let key in rData.res.settings) {
var param = $(param_template.clone().html())
var input = null
let data = rData.res.settings[key]
param.find('label').text(data.title).attr('for', key)
var param = $(param_template.clone().html());
var input = null;
let data = rData.res.settings[key];
param.find('label').text(data.title)
.attr('for', key);
if (data.type == 'textarea') {
param.find('input').remove()
input = param.find('textarea')
input.attr('name', key).text(data.value)
param.find('input').remove();
input = param.find('textarea');
input.attr('name', key).text(data.value);
} else {
param.find('textarea').remove()
input = param.find('input')
input.attr('name', key).attr('value', data.value)
param.find('textarea').remove();
input = param.find('input');
input.attr('name', key).attr('value', data.value);
}
/*
......@@ -59,19 +68,19 @@ function get_module_settings() {
console.log(data)
console.log(param)
*/
param.appendTo(main_content)
added_elts.push(key)
param.appendTo(main_content);
added_elts.push(key);
}
if (added_elts.length > 0) {
submit_btn.appendTo(main_content)
submit_btn.appendTo(main_content);
}
submit_btn.click(save_module_settings)
submit_btn.click(save_module_settings);
}
} catch (e) {
console.log(e)
console.log(e);
}
})
});
}
get_module_settings()
\ No newline at end of file
get_module_settings();
\ No newline at end of file
var results_table = null
var results_table = null;
function coop_init_datatable(params,data, cols, action_btn) {
var buttons = []
var columns = []
function coop_init_datatable(params, data, cols, action_btn) {
var buttons = [];
var columns = [];
$.each(cols,function(i,e){
$.each(cols, function(i, e) {
columns.push(e);
});
......@@ -13,7 +13,22 @@ function coop_init_datatable(params,data, cols, action_btn) {
var settings = {
dom: '<lf<t>ip><"clear"><B>',
lengthMenu : [[50,100,150,200,-1],[50,100,150,200,'Tout']],
lengthMenu : [
[
50,
100,
150,
200,
-1
],
[
50,
100,
150,
200,
'Tout'
]
],
pageLength : 50,
buttons: buttons,
......@@ -22,47 +37,49 @@ function coop_init_datatable(params,data, cols, action_btn) {
rowId : "_id",
data : data,
language: {url : '/static/js/datatables/french.json'}
}
};
return $('#results').DataTable(settings)
return $('#results').DataTable(settings);
}
var viewJSErrors = function() {
$.get('/monitor/js_errors', {dataType: 'json'})
.done(function(rData) {
if (typeof rData.res.content != "undefined") {
if (results_table) results_table.destroy()
var data = []
if (results_table) results_table.destroy();
var data = [];
var cols = [
{data: 'date', title: "Date"},
{data: 'module', title: "Module"},
{data: 'agent', title: "Signature nav."},
{data: 'context', title: "Contexte"},
{data: 'message', title: "Message"},
{data: 'message', title: "Message"}
];
rData.res.content.forEach(function(e) {
var line = e;
]
rData.res.content.forEach(function(e){
var line = e
if (typeof e.data == 'object') {
line.context = e.data.ctx
line.message = e.data.msg
delete e.data
line.context = e.data.ctx;
line.message = e.data.msg;
delete e.data;
} else {
line.context = '?'
line.message = e.data
line.context = '?';
line.message = e.data;
}
data.push(line)
})
console.log(data)
data.push(line);
});
console.log(data);
results_table = coop_init_datatable(null, data, cols);
}
})
}
});
};
$(document).ready(function() {
if (coop_is_connected()) {
$('header').show()
$('.nav-list .js_errors').click(viewJSErrors)
$('header').show();
$('.nav-list .js_errors').click(viewJSErrors);
}
})
\ No newline at end of file
});
\ No newline at end of file
......@@ -6,18 +6,25 @@ var oidoc = {
_id: '_design/index',
views: {
by_fp: {
map: function (doc) { emit(doc.fingerprint); }.toString()
map: function (doc) {
emit(doc.fingerprint);
}.toString()
},
by_completed: {
map: function (doc) { emit(doc.completed); }.toString()
map: function (doc) {
emit(doc.completed);
}.toString()
},
by_odoo_id: {
map: function (doc) { emit(doc.odoo_id); }.toString()
map: function (doc) {
emit(doc.odoo_id);
}.toString()
}
}
};
// save it
dbc.put(oidoc,function (err, result) {
dbc.put(oidoc, function (err, result) {
if (!err) {
console.log('index enregistré');
} else {
......
......@@ -5,87 +5,91 @@ IFCBarcodes = {
init : async function() {
// as it is a long time response task, restrict it
if (is_time_to('load_barcodes', 5000)) {
openWaiting('Récupération des informations code-barres....')
openWaiting('Récupération des informations code-barres....');
try {
let response = await fetch('/products/barcodes')
let bc_data = await response.json()
closeModal()
let response = await fetch('/products/barcodes');
let bc_data = await response.json();
closeModal();
if (typeof bc_data.res.error == "undefined") {
this.patterns = bc_data.res.patterns
this.codes = bc_data.res.bc
this.patterns = bc_data.res.patterns;
this.codes = bc_data.res.bc;
} else {
this.errors.push(bc_data.error)
this.errors.push(bc_data.error);
}
} catch(e) {
err = {msg: e.name + ' : ' + e.message, ctx: 'retrieve barcodes'}
console.error(err)
report_JS_error(err, 'products')
closeModal()
this.errors.push(JSON.stringify(err))
} catch (e) {
err = {msg: e.name + ' : ' + e.message, ctx: 'retrieve barcodes'};
console.error(err);
report_JS_error(err, 'products');
closeModal();
this.errors.push(JSON.stringify(err));
}
}
},
display_last_error: function() {
alert(this.errors[this.errors.length - 1])
alert(this.errors[this.errors.length - 1]);
},
get_corresponding_odoo_product: function(bc) {
//console.log('To analyze :' + bc)
var odoo_product = null
var odoo_product = null;
var index = 0,
pattern_found = false,
encoded_value = ''
encoded_value = '';
// Let's find out if it matches a pattern
while (index < this.patterns.length -1 && pattern_found === false) {
var pattern = this.patterns[index]
var significant_prefix = pattern.replace(/[^0-9]/g,'') //remove all but figures
var pattern = this.patterns[index];
var significant_prefix = pattern.replace(/[^0-9]/g, ''); //remove all but figures
if (bc.indexOf(significant_prefix) === 0) {
// console.log(pattern)
// console.log(bc)
//0493...{NNDDD} (pattern)
//0493213018809 (bc)
pattern_found = true
pattern = pattern.replace(/[^0-9\.ND]/,'')
bc = bc.slice(0,-1) // remove original check figure
odoo_bc = ''
pattern_found = true;
pattern = pattern.replace(/[^0-9\.ND]/, '');
bc = bc.slice(0, -1); // remove original check figure
odoo_bc = '';
// Read pattern character by character
for (var i = 0; i < pattern.length; i++) {
if (/[0-9]/.exec(pattern[i])) {
odoo_bc += pattern[i]
odoo_bc += pattern[i];
} else if (pattern[i].indexOf('.') === 0) {
odoo_bc += bc[i]
odoo_bc += bc[i];
} else if (/[ND]/.exec(pattern[i])) {
odoo_bc += '0'
odoo_bc += '0';
if (pattern[i] === 'D' && encoded_value.indexOf('.') < 0)
encoded_value += '.'
encoded_value += bc[i]
encoded_value += '.';
encoded_value += bc[i];
}
}
// Add check digit at the end of odoo_bc to find out "normalized" code
bc = odoo_bc + eanCheckDigit(odoo_bc)
bc = odoo_bc + eanCheckDigit(odoo_bc);
}
index++
index++;
}
// let's seek "normalized" bc in codes array
for (code in this.codes) {
if (code == bc) {
odoo_product = {barcode: code, data: this.codes[code], value: encoded_value}
odoo_product = {barcode: code, data: this.codes[code], value: encoded_value};
}
}
//console.log(odoo_product)
return odoo_product
return odoo_product;
}
}
};
init_barcodes = async function() {
var result = null
var ifcb = Object.create(IFCBarcodes)
await ifcb.init()
var result = null;
var ifcb = Object.create(IFCBarcodes);
await ifcb.init();
if (ifcb.errors.length > 0)
ifcb.display_last_error()
ifcb.display_last_error();
else
result = ifcb
result = ifcb;
// console.log(result.patterns)
return result
}
return result;
};
......@@ -7,149 +7,162 @@ var active_table = null,
bc_scanner = $('#barcode_scanner');
function getLocalSelected() {
var local_in_process = localStorage.getItem("selected_products") || "[]"
return JSON.parse(local_in_process)
var local_in_process = localStorage.getItem("selected_products") || "[]";
return JSON.parse(local_in_process);
}
function setLocalSelected(lip) {
localStorage.setItem("selected_products",JSON.stringify(lip))
localStorage.setItem("selected_products", JSON.stringify(lip));
}
function getLocalPdtDB() {
var local_pdt_db = JSON.parse(localStorage.getItem("products_db") || "{}")
var local_pdt_db = JSON.parse(localStorage.getItem("products_db") || "{}");
if (typeof (local_pdt_db.list) == "undefined")
local_pdt_db.list = []
return local_pdt_db
local_pdt_db.list = [];
return local_pdt_db;
}
function setLocalPdtDB(lpdb) {
localStorage.setItem("products_db",JSON.stringify(lpdb))
localStorage.setItem("products_db", JSON.stringify(lpdb));
}
function display_in_search_results(matching) {
var ul = $('<ul>');
$.each(matching, function(i,e){
var li = $('<li>').attr('data-index',e.index).text(e.doc.barcode + ' ' + e.doc.display_name)
ul.append(li)
})
search_result.html(ul)
$.each(matching, function(i, e) {
var li = $('<li>').attr('data-index', e.index)
.text(e.doc.barcode + ' ' + e.doc.display_name);
ul.append(li);
});
search_result.html(ul);
}
function search_in_pdt_list(kwords) {
if (kwords.length > 3) {
var matching = []
var is_bc = !isNaN(kwords)
var matching = [];
var is_bc = !isNaN(kwords);
if (!is_bc)
kwords = jQuery.fn.DataTable.ext.type.search.string(kwords.toLowerCase())
$.each(local_pdt_db.list, function(i,e) {
kwords = jQuery.fn.DataTable.ext.type.search.string(kwords.toLowerCase());
$.each(local_pdt_db.list, function(i, e) {
if (is_bc) {
if (e.barcode && e.barcode.indexOf(kwords) === 0) {
matching.push({doc:e,index:i})
matching.push({doc:e, index:i});
}
} else {
var p_name = jQuery.fn.DataTable.ext.type.search.string(e.display_name)
var p_name = jQuery.fn.DataTable.ext.type.search.string(e.display_name);
if (p_name.toLowerCase().indexOf(kwords) > -1)
matching.push({doc:e,index:i})
matching.push({doc:e, index:i});
}
})
});
if (matching.length > 0) {
if (matching.length == 1 && is_bc == true){
add_product_to_table(matching[0].index)
if (matching.length == 1 && is_bc == true) {
add_product_to_table(matching[0].index);
} else {
display_in_search_results(matching)
display_in_search_results(matching);
}
}
} else {
search_result.html('')
search_result.html('');
}
}
$(document).pos();
$(document).on('scan.pos.barcode', function(event){
$(document).on('scan.pos.barcode', function(event) {
//access `event.code` - barcode data
var barcode = event.code
var barcode = event.code;
if (barcode.length >=13) {
barcode = barcode.substring(barcode.length-13)
search_in_pdt_list(barcode)
barcode = barcode.substring(barcode.length-13);
search_in_pdt_list(barcode);
} else {
console.log($(':focus').attr('type'))
console.log(new Date().getTime() + ' -> '+barcode)
console.log($(':focus').attr('type'));
console.log(new Date().getTime() + ' -> '+barcode);
}
});
function destocking_record() {
console.log('envoyer les informations à Django')
console.log('envoyer les informations à Django');
}
function init_table_interface (data) {
if (active_table)
active_table.destroy()
active_table.destroy();
var cols = [
{data: 'display_name', title: "Nom"},
{data: 'qty', title: "Quantité", defaultContent: ""}
]
];
var action_btn = {
text: 'Valider le déstockage',
action : function(e,dt) {
action : function(e, dt) {
if (dt.rows().indexes().length > 0)
openModal('Valider le déstockage', destocking_record, 'Enregistrer');
else
alert("Impossible, il n'y a aucun produit !")
alert("Impossible, il n'y a aucun produit !");
}
};
var params = {no_search: true}
var params = {no_search: true};
active_table = coop_init_datatable(params, data, '.pdt_liste_to_transfert', cols, action_btn);
}
function add_product_to_table(p_index) {
var local_selected = getLocalSelected();
selected_p = local_pdt_db.list[p_index]
selected_p = local_pdt_db.list[p_index];
if (selected_p.uom_id[0] == 1)
selected_p.qty = 1
console.log('p_index='+p_index)
console.log(selected_p)
local_selected.push(selected_p)
setLocalSelected(local_selected)
search_result.html('')
init_table_interface(local_selected)
selected_p.qty = 1;
console.log('p_index='+p_index);
console.log(selected_p);
local_selected.push(selected_p);
setLocalSelected(local_selected);
search_result.html('');
init_table_interface(local_selected);
}
var need_to_load_odoo_products = true;
local_pdt_db = getLocalPdtDB()
local_selected = getLocalSelected()
local_pdt_db = getLocalPdtDB();
local_selected = getLocalSelected();
if (local_pdt_db.list.length > 0) {
if (new Date().getTime() - local_pdt_db.created_at < 7200000) {
// if data have been retrieved less than 2h ago, no need to make ajax call
need_to_load_odoo_products = false;
loader.hide()
search_div.show()
loader.hide();
search_div.show();
}
}
if (need_to_load_odoo_products == true) {
$.ajax('get_all_available_products').done(function(rData){
local_pdt_db.list = rData
local_pdt_db.created_at = new Date().getTime()
setLocalPdtDB(local_pdt_db)
loader.hide()
search_div.show()
$.ajax('get_all_available_products').done(function(rData) {
local_pdt_db.list = rData;
local_pdt_db.created_at = new Date().getTime();
setLocalPdtDB(local_pdt_db);
loader.hide();
search_div.show();
});
}
search_input.on('keyup focus', function(){
search_in_pdt_list($(this).val())
})
search_input.on('keyup focus', function() {
search_in_pdt_list($(this).val());
});
search_div.on('click', 'li', function() {
var p_index = $(this).data('index');
search_div.on('click', 'li', function(){
var p_index = $(this).data('index')
add_product_to_table(p_index)
})
add_product_to_table(p_index);
});
if (local_selected.length > 0) {
init_table_interface(local_selected)
init_table_interface(local_selected);
}
\ No newline at end of file
function products_shelf_label_print (products, callback) {
console.log('Demande impression etiquettes rayon')
params = {products: JSON.stringify(products)}
post_form('/products/shelf_labels', params, callback)
console.log('Demande impression etiquettes rayon');
params = {products: JSON.stringify(products)};
post_form('/products/shelf_labels', params, callback);
}
/*
$.ajax({
......
......@@ -4,7 +4,7 @@ var order = {
callback_update = false,
callback_report = false,
selection_type = null,
saved_groups = []
saved_groups = [];
/* UTILS */
......@@ -38,13 +38,13 @@ function group_goto(i) {
* Set local storage for given order
*/
function set_local_storage(order_data) {
console.log(order_data)
console.log(order_data);
if (Modernizr.localstorage) {
var stored_order = JSON.parse(localStorage.getItem('order_' + order_data.id));
// Set local storage if key doesn't exist
if (stored_order == null) {
localStorage.setItem("order_" + order_data.id , JSON.stringify(order_data));
localStorage.setItem("order_" + order_data.id, JSON.stringify(order_data));
}
}
}
......@@ -60,8 +60,9 @@ function validatePrices() {
var update_data = {
'update_type' : 'br_valid',
'orders' : {}
}
update_data.orders[order['id']] = { 'po' : [] }
};
update_data.orders[order['id']] = { 'po' : [] };
$.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });
$.ajax({
......@@ -77,7 +78,7 @@ function validatePrices() {
reload();
},
error: function() {
closeModal()
closeModal();
alert('Erreur dans la validation des prix');
}
});
......@@ -105,10 +106,10 @@ function validatePrices() {
reload();
},
error: function() {
closeModal()
closeModal();
alert('Erreur dans l\'envoi du rapport.');
err = {msg: 'Erreur dans l\'envoi du rapport.', ctx: 'validatePrices'}
report_JS_error(err, 'reception')
err = {msg: 'Erreur dans l\'envoi du rapport.', ctx: 'validatePrices'};
report_JS_error(err, 'reception');
}
});
}
......@@ -151,25 +152,25 @@ function group_action() {
grouped_orders.push(group_ids);
// store grouped orders array
localStorage.setItem('grouped_orders' , JSON.stringify(grouped_orders));
localStorage.setItem('grouped_orders', JSON.stringify(grouped_orders));
}
// Go to products page of order with smallest id
goto(min_id)
goto(min_id);
} else if (pswd == null) {
} else {
alert('Mauvais mot de passe !')
alert('Mauvais mot de passe !');
}
}
$(document).ready(function() {
// Set date format for DataTable so date ordering can work
$.fn.dataTable.moment( 'D/M/Y' );
$.fn.dataTable.moment('D/M/Y');
var saved_grouped_orders = JSON.parse(localStorage.getItem('grouped_orders'));
var table_orders = $('#orders').DataTable( {
var table_orders = $('#orders').DataTable({
ajax: "get_list_orders",
columns:[
{
......@@ -177,7 +178,7 @@ $(document).ready(function() {
title:"Sélectionner",
className:"dt-body-center",
render: function (data, type, full, meta) {
return '<input type="checkbox" id="select_bc_'+data+'" value="'+data+'">'
return '<input type="checkbox" id="select_bc_'+data+'" value="'+data+'">';
},
width: "4%",
orderable: false
......@@ -222,56 +223,65 @@ $(document).ready(function() {
}
],
dom: 'rtip',
order: [[ 1, "asc" ]],
order: [
[
1,
"asc"
]
],
iDisplayLength: 25,
language: {url : '/static/js/datatables/french.json'},
initComplete: function(settings, json) { // After data is loaded
// if there are grouped orders
if (saved_grouped_orders != null) {
$('#groups_items').append("<ul>")
$('#groups_items').append("<ul>");
// for each group
for (group of saved_grouped_orders) {
var g = []
var g = [];
// for each order in group
for (group_element_id of group) {
// Look for order in datatable
for (var i = 0; i < table_orders.rows().data().length; i++) {
if (group_element_id == table_orders.rows(i).data()[0].id) {
var order = table_orders.rows(i).data()[0];
g.push(order)
g.push(order);
// remove raw from table
table_orders.rows( i ).remove().draw();
table_orders.rows(i).remove()
.draw();
}
}
}
// Display group
document.getElementById("container_groups").hidden = false;
var group_row = "<ul> <li> Commandes de "
var group_row = "<ul> <li> Commandes de ";
for (i in g) {
if (i == g.length-1) { // last element of list
group_row += "<b>" + g[i].partner + "</b> du " + g[i].date_order + " : "
group_row += "<b>" + g[i].partner + "</b> du " + g[i].date_order + " : ";
} else {
group_row += "<b>" + g[i].partner + "</b> du " + g[i].date_order + ", "
group_row += "<b>" + g[i].partner + "</b> du " + g[i].date_order + ", ";
}
}
if (g[0].reception_status == 'False') {
group_row += "<button class='btn--primary' onClick='group_goto(" + saved_groups.length + ")'>Compter les produits</button>"
group_row += "<button class='btn--primary' onClick='group_goto(" + saved_groups.length + ")'>Compter les produits</button>";
} else {
group_row += "<button class='btn--success' onClick='group_goto(" + saved_groups.length + ")'>Mettre à jour les prix</button>"
group_row += "<button class='btn--success' onClick='group_goto(" + saved_groups.length + ")'>Mettre à jour les prix</button>";
}
group_row += "</li>"
$('#groups_items').append(group_row)
group_row += "</li>";
$('#groups_items').append(group_row);
saved_groups.push(g)
saved_groups.push(g);
}
}
$('#groups_items').append("</ul>")
$('#groups_items').append("</ul>");
}
});
......@@ -308,7 +318,7 @@ $(document).ready(function() {
$(this.parentElement).toggleClass('selected');
document.getElementById("select_bc_"+row_data.id).checked = false;
alert('Vous ne pouvez pas grouper des commandes qui ont un statut différent.')
alert('Vous ne pouvez pas grouper des commandes qui ont un statut différent.');
} else {
//display 'group action' button
document.getElementById("group_action").hidden = false;
......@@ -338,12 +348,12 @@ $(document).ready(function() {
// Use local storage to pass order data to next page
set_local_storage(row_data);
goto(row_data.id)
goto(row_data.id);
}
}
// If 'update prices' step, click on before-last cell -> validate all prices
else if (this.cellIndex == 3 && row_data.reception_status == "qty_valid") {
order = row_data
order = row_data;
openModal($('#modal_no_prices').html(), validatePrices, 'Confirmer', false);
}
});
......@@ -353,7 +363,7 @@ $(document).ready(function() {
table_orders
.search(jQuery.fn.DataTable.ext.type.search.string(this.value))
.draw();
} );
});
});
......@@ -8,7 +8,7 @@ Informations affichées :
var parent_location = '/shelfs',
shelf,
table_products,
search_chars = []
search_chars = [];
/* UTILS */
......@@ -18,17 +18,17 @@ function round(value, decimals) {
}
function back() {
document.location.href = parent_location
document.location.href = parent_location;
}
// Set search field with product name when barcode is read
function select_product_from_bc(barcode) {
$.each(shelf_products, function(i,e) {
$.each(shelf_products, function(i, e) {
if (e.barcode == barcode) {
$('#search_input').val(e.name)
table_products.search(jQuery.fn.DataTable.ext.type.search.string(e.name)).draw()
$('#search_input').val(e.name);
table_products.search(jQuery.fn.DataTable.ext.type.search.string(e.name)).draw();
}
})
});
}
/* LIST HANDLING */
......@@ -36,7 +36,7 @@ function select_product_from_bc(barcode) {
// Init Data & listeners
function initList() {
// Init table for items to process
table_products = $('#table_shelf_products').DataTable( {
table_products = $('#table_shelf_products').DataTable({
data: shelf_products,
columns: [
{data:"id", title: "id", visible: false},
......@@ -46,7 +46,7 @@ function initList() {
title:"Stock théorique",
width: "10%",
render: function (data, type, full) {
return round(data, 2) + ' ' + full.uom_id[1]
return round(data, 2) + ' ' + full.uom_id[1];
}
},
{
......@@ -56,12 +56,12 @@ function initList() {
className:"dt-body-center",
render: function (data, type, full, meta) {
if (type == "sort" || type == 'type')
return data
return data;
if (data == -99999999) {
return '/'
return '/';
} else {
return data
return data;
}
}
},
......@@ -72,18 +72,23 @@ function initList() {
className:"dt-body-center",
render: function (data, type, full, meta) {
if (type == "sort" || type == 'type')
return data
return data;
if (data == -99999999) {
return '/'
return '/';
} else {
return data + ' €'
return data + ' €';
}
}
}
},
],
rowId : "id",
order: [[ 0, "asc" ]],
order: [
[
0,
"asc"
]
],
paging: false,
dom: 'lrtip', // Remove the search input from that table
language: {url : '/static/js/datatables/french.json'}
......@@ -96,8 +101,8 @@ function initList() {
$('#search_input').on('keyup', function () {
table_products
.search(jQuery.fn.DataTable.ext.type.search.string(this.value)) // search without accents (see DataTable plugin)
.draw()
})
.draw();
});
}
......@@ -113,25 +118,25 @@ function get_shelf_data() {
traditional: true,
contentType: "application/json; charset=utf-8",
success: function(data) {
shelf = data.res
init()
shelf = data.res;
init();
},
error: function(data) {
if (typeof data.responseJSON != 'undefined' ) {
console.log(data.responseJSON)
if (typeof data.responseJSON != 'undefined') {
console.log(data.responseJSON);
}
alert('Les données n\'ont pas pu être récupérées, réessayez plus tard.');
}
})
});
}
// Init page : to be launched when shelf data is here
function init() {
// Set shelf name in DOM
$('#shelf_name').text(shelf.name)
$('#shelf_name').text(shelf.name);
// Products passed at page loading as 'shelf_products'
initList()
initList();
// Barcode reader: listen for 13 digits read in a very short time
$('#search_input').keypress(function(e) {
......@@ -140,41 +145,43 @@ function init() {
}
if (search_chars.length >= 13) {
var barcode = search_chars.join("");
if (!isNaN(barcode)) {
search_chars = [];
setTimeout(function(){
setTimeout(function() {
select_product_from_bc(barcode);
}, 300);
}
}
})
});
}
$(document).ready(function() {
// Get Route parameter
var pathArray = window.location.pathname.split('/')
shelf = {id: pathArray[pathArray.length-1]}
var pathArray = window.location.pathname.split('/');
shelf = {id: pathArray[pathArray.length-1]};
// Get shelf data from local storage
if (Modernizr.localstorage) {
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + shelf.id))
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + shelf.id));
if (stored_shelf != null) {
shelf = stored_shelf
init()
shelf = stored_shelf;
init();
} else {
// Get shelf info if not coming from shelves list
get_shelf_data()
get_shelf_data();
}
} else {
get_shelf_data()
get_shelf_data();
}
// listeners
// Cancel search
$('.cancel_search').on('click', function () {
$('#search_input').val('')
table_products.search('').draw()
})
$('#search_input').val('');
table_products.search('').draw();
});
});
var shelfs_table = null
var shelfs_table = null;
function init_datatable() {
return $('#shelfs').DataTable( {
return $('#shelfs').DataTable({
data: shelfs, // data passed at page loading
rowId: 'id',
columns:[
......@@ -20,13 +20,15 @@ function init_datatable() {
render: function (data, type, full, meta) {
// Sort on data, not rendering
if (type == "sort" || type == 'type')
return data
return data;
if (data == '0001-01-01')
return "Ce rayon n'a jamais été inventorié !"
return "Ce rayon n'a jamais été inventorié !";
else {
var date = new Date(data)
return date.toLocaleDateString('fr-FR')
var date = new Date(data);
return date.toLocaleDateString('fr-FR');
}
}
},
......@@ -36,14 +38,14 @@ function init_datatable() {
title:"Valeur théorique du rayon",
render: function (data, type, full, meta) {
if (type == "sort" || type == 'type')
return data
return data;
if (data == -1) { // Code: server send empty field -> loading
return '<i class="fas fa-spinner fa-spin"></i>'
return '<i class="fas fa-spinner fa-spin"></i>';
} else if (data == -2) { // Code: error getting data from server
return '/'
return '/';
} else {
return data + ' €'
return data + ' €';
}
},
width: "5%",
......@@ -56,12 +58,12 @@ function init_datatable() {
className:"dt-body-center",
render: function (data, type, full, meta) {
if (type == "sort" || type == 'type')
return data
return data;
if (data == -99999999) {
return '/'
return '/';
} else {
return data + ' %'
return data + ' %';
}
}
},
......@@ -72,12 +74,12 @@ function init_datatable() {
className:"dt-body-center",
render: function (data, type, full, meta) {
if (type == "sort" || type == 'type')
return data
return data;
if (data == -99999999) {
return '/'
return '/';
} else {
return data + ' %'
return data + ' %';
}
}
},
......@@ -88,17 +90,22 @@ function init_datatable() {
width: "15%",
render: function (data, type, full, meta) {
if (data == '')
return "<button class='btn--primary do_shelf_inventory'>Inventaire en rayon</button>"
return "<button class='btn--primary do_shelf_inventory'>Inventaire en rayon</button>";
else
return "<button class='btn--success do_shelf_inventory'>Inventaire en réserve</button>"
return "<button class='btn--success do_shelf_inventory'>Inventaire en réserve</button>";
}
}
],
dom: 'rtip',
order: [[ 1, "asc" ]],
order: [
[
1,
"asc"
]
],
iDisplayLength: 25,
language: {url : '/static/js/datatables/french.json'}
})
});
}
function get_shelfs_extra_data() {
......@@ -112,94 +119,98 @@ function get_shelfs_extra_data() {
contentType: "application/json; charset=utf-8",
success: function(data) {
for (item of data.res) {
var row_data = shelfs_table.row('#'+item.id).data()
row_data.shelf_value = item.shelf_value
var row_data = shelfs_table.row('#'+item.id).data();
row_data.shelf_value = item.shelf_value;
shelfs_table
.row( '#'+item.id )
.data( row_data )
.draw()
.row('#'+item.id)
.data(row_data)
.draw();
}
},
error: function(data) {
if (typeof data.responseJSON != 'undefined') {
console.log(data.responseJSON)
console.log(data.responseJSON);
}
set_null_to_extra_data()
set_null_to_extra_data();
}
})
});
} catch (e) {
console.log(e)
set_null_to_extra_data()
console.log(e);
set_null_to_extra_data();
}
}
function set_null_to_extra_data() {
shelfs_table.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
var d = this.data()
d.shelf_value = -2
this.invalidate() // invalidate the data DataTables has cached for this row
} );
shelfs_table.rows().every(function (rowIdx, tableLoop, rowLoop) {
var d = this.data();
shelfs_table.draw()
d.shelf_value = -2;
this.invalidate(); // invalidate the data DataTables has cached for this row
});
shelfs_table.draw();
}
var getRowData = function(clicked) {
var row = shelfs_table.row(clicked.parents('tr'))
return row.data()
}
var row = shelfs_table.row(clicked.parents('tr'));
return row.data();
};
function go_to_shelf_inventory() {
openModal()
openModal();
var clicked = $(this)
var row_data = getRowData(clicked)
var clicked = $(this);
var row_data = getRowData(clicked);
// Use local storage to pass data to next page
if (Modernizr.localstorage) {
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + row_data.id))
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + row_data.id));
// Set local storage if key doesn't exist
if (stored_shelf == null) {
localStorage.setItem("shelf_" + row_data.id , JSON.stringify(row_data))
localStorage.setItem("shelf_" + row_data.id, JSON.stringify(row_data));
}
}
document.location.href = "shelf_inventory/" + row_data.id
document.location.href = "shelf_inventory/" + row_data.id;
}
function go_to_shelf_view() {
openModal()
openModal();
var clicked = $(this)
var row_data = getRowData(clicked)
var clicked = $(this);
var row_data = getRowData(clicked);
// Use local storage to pass data to next page
if (Modernizr.localstorage) {
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + row_data.id))
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + row_data.id));
// Set local storage if key doesn't exist
if (stored_shelf == null) {
localStorage.setItem("shelf_" + row_data.id , JSON.stringify(row_data))
localStorage.setItem("shelf_" + row_data.id, JSON.stringify(row_data));
}
}
document.location.href = "shelf_view/" + row_data.id
document.location.href = "shelf_view/" + row_data.id;
}
$(document).ready(function() {
shelfs_table = init_datatable()
get_shelfs_extra_data()
shelfs_table = init_datatable();
get_shelfs_extra_data();
$(document).on('click', 'button.do_shelf_inventory', go_to_shelf_inventory)
$('#shelfs').on('click', 'tbody td', go_to_shelf_view)
$(document).on('click', 'button.do_shelf_inventory', go_to_shelf_inventory);
$('#shelfs').on('click', 'tbody td', go_to_shelf_view);
// Search input
$('#search_input').on('keyup', function () {
shelfs_table
.search(jQuery.fn.DataTable.ext.type.search.string(this.value))
.draw()
})
.draw();
});
})
});
var shelfs_table = null
var shelfs_table = null;
function init_datatable() {
return $('#shelfs').DataTable( {
return $('#shelfs').DataTable({
data: shelfs, // data passed at page loading
rowId: 'id',
columns:[
......@@ -20,13 +20,15 @@ function init_datatable() {
render: function (data, type, full, meta) {
// Sort on data, not rendering
if (type == "sort" || type == 'type')
return data
return data;
if (data == '0001-01-01')
return "Ce rayon n'a jamais été inventorié !"
return "Ce rayon n'a jamais été inventorié !";
else {
var date = new Date(data)
return date.toLocaleDateString('fr-FR')
var date = new Date(data);
return date.toLocaleDateString('fr-FR');
}
}
},
......@@ -36,43 +38,50 @@ function init_datatable() {
className:"dt-body-center",
width: "15%",
render: function (data, type, full, meta) {
return "<button class='btn--success do_export_sales_data'>Export Ventes</button>"
return "<button class='btn--success do_export_sales_data'>Export Ventes</button>";
}
}
],
dom: 'rtip',
order: [[ 1, "asc" ]],
order: [
[
1,
"asc"
]
],
iDisplayLength: 25,
language: {url : '/static/js/datatables/french.json'}
})
});
}
var getRowData = function(clicked) {
var row = shelfs_table.row(clicked.parents('tr'))
return row.data()
}
var row = shelfs_table.row(clicked.parents('tr'));
return row.data();
};
function go_to_shelf_view() {
openModal()
openModal();
var clicked = $(this)
var row_data = getRowData(clicked)
var clicked = $(this);
var row_data = getRowData(clicked);
// Use local storage to pass data to next page
if (Modernizr.localstorage) {
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + row_data.id))
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + row_data.id));
// Set local storage if key doesn't exist
if (stored_shelf == null) {
localStorage.setItem("shelf_" + row_data.id , JSON.stringify(row_data))
localStorage.setItem("shelf_" + row_data.id, JSON.stringify(row_data));
}
}
document.location.href = "shelf_view/" + row_data.id
document.location.href = "shelf_view/" + row_data.id;
}
function get_shelfs_sales_data() {
......@@ -86,47 +95,49 @@ function get_shelfs_sales_data() {
contentType: "application/json; charset=utf-8",
success: function(data) {
for (item of data.res) {
var row_data = shelfs_table.row('#'+item.id).data()
row_data.shelf_value = item.shelf_value
var row_data = shelfs_table.row('#'+item.id).data();
row_data.shelf_value = item.shelf_value;
shelfs_table
.row( '#'+item.id )
.data( row_data )
.draw()
.row('#'+item.id)
.data(row_data)
.draw();
}
},
error: function(data) {
if (typeof data.responseJSON != 'undefined') {
console.log(data.responseJSON)
console.log(data.responseJSON);
}
}
})
});
} catch (e) {
err = {msg: e.toString(), ctx: 'get_shelfs_sales_data'}
report_JS_error(err, 'shelfs')
err = {msg: e.toString(), ctx: 'get_shelfs_sales_data'};
report_JS_error(err, 'shelfs');
}
}
function export_sales_data(event) {
event.stopImmediatePropagation()
var clicked = $(this)
var row_data = getRowData(clicked)
console.log(row_data)
event.stopImmediatePropagation();
var clicked = $(this);
var row_data = getRowData(clicked);
console.log(row_data);
}
$(document).ready(function() {
shelfs_table = init_datatable()
shelfs_table = init_datatable();
$('#shelfs').on('click', 'button.do_export_sales_data', export_sales_data)
$('#shelfs').on('click', 'tbody td', go_to_shelf_view)
$('#shelfs').on('click', 'button.do_export_sales_data', export_sales_data);
$('#shelfs').on('click', 'tbody td', go_to_shelf_view);
// Search input
$('#search_input').on('keyup', function () {
shelfs_table
.search(jQuery.fn.DataTable.ext.type.search.string(this.value))
.draw()
})
.draw();
});
})
});
......@@ -33,6 +33,7 @@ $(document).ready(function() {
// Member can ask for 6 delays, which is 24 weeks after entering alert status
// 'date_alert_stop' field is begining of alert + 4 weeks
var date_end_alert = new Date(dataPartner.date_alert_stop);
date_end_alert.setDate(date_end_alert.getDate()+20*7);
if (date_end_alert < new Date()) {
......@@ -41,10 +42,10 @@ $(document).ready(function() {
$('#delay').removeAttr('hidden');
}
} else if (dataPartner.cooperative_state == "unsubscribed") {
$('#unsubscribed').show()
$('#unsubscribed').show();
} else if (dataPartner.cooperative_state == "exempted") {
$('#exempted').show()
$('#exempted').show();
} else {
$('body').append('Merci de prendre contact avec le Bureau des membres pour examiner votre situation.')
$('body').append('Merci de prendre contact avec le Bureau des membres pour examiner votre situation.');
}
});
var myChart;
function get_ajax_data(product_id){
function get_ajax_data(product_id) {
$.ajax({
type: 'GET',
......@@ -33,20 +33,21 @@ var config = {
},
legend: { display: false }
}
};
};
window.onload = function() {
myChart = new Chart(document.getElementById("mixed-chart"), config);
}
};
$(function(){
$(function() {
$('.modal').on('show.bs.modal', function (e) {
var button = $(e.relatedTarget)
var index = button.data('remote')
var button = $(e.relatedTarget);
var index = button.data('remote');
//$(this).find('.modal-content').load('remote' + index + '.html')
get_ajax_data(index);
})
})
});
});
......@@ -5,36 +5,38 @@
var table_article;
var dataSet =[] ;
var dataSet =[];
var csrftoken;
// lance la recherche sur le nom des l'article
function search_table_article(){
function search_table_article() {
table_article.ajax.url('get_list_article?rech='+$("#searchInput").val()).load();
}
// Lance la recherche sur les codes barres
function search_article_byBarcode(){
function search_article_byBarcode() {
table_article.ajax.url('get_article_byBarcode?rech='+$("#searchInput").val()).load();
}
}
function archiveArticle(){
function archiveArticle() {
var jIdArcticle = { 'idArticle': selArctileData.product_id};
actionButton("set_archive", jIdArcticle, "/stock/listArticleBreaking");
};
}
function dontPurchase(){
function dontPurchase() {
var jIdArcticle = { 'idArticle': selArctileData.product_id};
actionButton("set_dontPurchase", jIdArcticle, "/stock/listArticleBreaking");
};
}
function actionButton (vUrl,jIdArcticle, followPage){
function actionButton (vUrl, jIdArcticle, followPage) {
$.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } });
$.ajax({
type: "PUT",
url: vUrl ,
url: vUrl,
//dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
......@@ -52,7 +54,7 @@ function actionButton (vUrl,jIdArcticle, followPage){
// Initialise le table des articles
$(document).ready(function() {
table_article = $('#tableArticle').DataTable( {
table_article = $('#tableArticle').DataTable({
"ajax": {
"url": "get_list_article_breaking",
"data": ""
......@@ -63,38 +65,41 @@ $(document).ready(function() {
"title":"Photo",
"render": function (data, type, full, meta) {
debut = '<button id="page1" type="button" data-toggle="modal" data-target=".modal" data-remote=' + full.product_id + ' class="btn btn-primary">'
fin = "</button>"
debut = '<button id="page1" type="button" data-toggle="modal" data-target=".modal" data-remote=' + full.product_id + ' class="btn btn-primary">';
fin = "</button>";
return debut + "<img src='data:image/png;base64," + data + "'>" + fin;
}
},
{data:"name", "title":"Article","width": "50%"},
{data:"name", "title":"Article", "width": "50%"},
{data:"create_date",
"render":function (data, type, row){
my = new Date (data)
"render":function (data, type, row) {
my = new Date(data);
return my.toLocaleDateString() +" " + my.toLocaleTimeString();
},
"title":"Date","width":"15%"},
"title":"Date", "width":"15%"},
{data:"create_date",
"render":function (data, type, row){
my = new Date (data)
"render":function (data, type, row) {
my = new Date(data);
var today = new Date();
dif = new Number((today - my)/86400000).toFixed(2);
return dif;
},
"title":"Durée","width":"5%"},
"title":"Durée", "width":"5%"},
{data:"purchase_ok", "width":"5%",
"title":"Achetable", "className":"dt-body-center",
"render": function (data, type, full, meta) {
if (data == true){
return '<div><input type="checkbox" id="bt_dontPurchase" checked><div>';}
else{
return '<div><input type="checkbox" id="bt_dontPurchase" ><div>';}
if (data == true) {
return '<div><input type="checkbox" id="bt_dontPurchase" checked><div>';
} else {
return '<div><input type="checkbox" id="bt_dontPurchase" ><div>';
}
}
},
{data:"reception_status",
......@@ -107,7 +112,12 @@ $(document).ready(function() {
],
"searching": true,
"order": [[ 0, "desc" ]],
"order": [
[
0,
"desc"
]
],
"iDisplayLength": 25,
"language": {
"emptyTable": "Pas de donnée",
......@@ -133,12 +143,14 @@ $(document).ready(function() {
}
}
});
});
});
/* Listener */
/* Listener */
$(document).on('click','#dp_Search',function(){search_table_article();});
$(document).on('click', '#dp_Search', function() {
search_table_article();
});
//barcode-reader
......@@ -146,15 +158,17 @@ $(document).on('click','#dp_Search',function(){search_table_article();});
$(document).ready(function() {
var pressed = false;
var chars = [];
$(window).keypress(function(e) {
if (e.which >= 48 && e.which <= 57) {
chars.push(String.fromCharCode(e.which));
}
if (pressed == false) {
setTimeout(function(){
setTimeout(function() {
if (chars.length >= 13) {
var barcode = chars.join("");
if (!isNaN(barcode)) {
chars = [];
pressed = false;
......@@ -162,7 +176,7 @@ $(document).ready(function() {
}
}
},300);
}, 300);
}
pressed = true;
});
......@@ -179,28 +193,30 @@ var selArctileData;
$(document).on('click', 'button#bt_archive', function () {
$(document).on('click', 'button#bt_archive', function () {
var row = table_article.row($(this).parents('tr'));
var data = row.data();
html ='<div id="askTitle" >Vous êtes sur que cet article doit être archivée ? </div>';
html += '<div id="showData" ><div id="articleName" >'+data.name+'</div></div>';
selArctileData = data ;
selArctileData = data;
openModal(html, archiveArticle, " - Ok - ");
} );
});
$(document).on('click', '#bt_dontPurchase', function () {
if (!this.checked){
$(document).on('click', '#bt_dontPurchase', function () {
if (!this.checked) {
var row = table_article.row($(this).parents('tr'));
var data = row.data();
html ='<div id="askTitle" >Vous êtes sur que cet article ne doit plus être acheter ? </div>';
html += '<div id="showData" ><div id="articleName" >'+data.name+'</div><div id="articleQty" >'+data.create_date+ '</div></div>';
selArctileData = data ;
selArctileData = data;
openModal(html, dontPurchase, " - Ok - ");
this.checked = true
}else{
this.checked = false
this.checked = true;
} else {
this.checked = false;
}
} );
});
......@@ -10,12 +10,12 @@
var table_article;
var dataSet =[] ;
var dataSet =[];
var csrftoken;
var four_id=0;
// lance la recherche sur le nom des l'article
function search_table_article(){
function search_table_article() {
table_article.ajax.url('get_list_article_fournisseur/'+four_id+"/").load();
......@@ -24,21 +24,26 @@ function search_table_article(){
// Initialise le table des articles
$(document).ready(function() {
table_article = $('#tableArticle').DataTable( {
table_article = $('#tableArticle').DataTable({
"ajax": {
"url": "get_list_article_fournisseur/1712/",
"data": ""
},
"columns":[
{data:"name_template", "title":"Article","width": "50%"},
{data:"name_template", "title":"Article", "width": "50%"},
{data:"stock_qty", "title":"En Stock", "width": "10%"},
{data:"average", "title":"Moyen de vente", "width": "10%"},
{data:"average_breaking", "title":"Moyenne vent rupture", "width": "10%"},
{data:"average_breaking", "title":"Moyenne vent rupture", "width": "10%"}
],
"searching": false,
"order": [[ 0, "desc" ]],
"order": [
[
0,
"desc"
]
],
"iDisplayLength": 25,
"language": {
"emptyTable": "Pas de donnée",
......@@ -64,12 +69,14 @@ $(document).ready(function() {
}
}
});
});
});
/* Listener */
/* Listener */
$(document).on('click','#dp_Search',function(){search_table_article();});
$(document).on('click', '#dp_Search', function() {
search_table_article();
});
//barcode-reader
......@@ -77,15 +84,17 @@ $(document).on('click','#dp_Search',function(){search_table_article();});
$(document).ready(function() {
var pressed = false;
var chars = [];
$(window).keypress(function(e) {
if (e.which >= 48 && e.which <= 57) {
chars.push(String.fromCharCode(e.which));
}
if (pressed == false) {
setTimeout(function(){
setTimeout(function() {
if (chars.length >= 13) {
var barcode = chars.join("");
if (!isNaN(barcode)) {
chars = [];
pressed = false;
......@@ -94,7 +103,7 @@ $(document).ready(function() {
}
},300);
}, 300);
}
pressed = true;
});
......@@ -105,7 +114,7 @@ $(document).ready(function() {
});
// Lancement de la rupture sur l'article choisie
function ruptureArticle(test){
function ruptureArticle(test) {
var jIdArcticle = { 'idArticle': selArctileData.id, 'uom_id' : selArctileData.uom_id[0] };
......@@ -113,7 +122,7 @@ function ruptureArticle(test){
$.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } });
$.ajax({
type: "PUT",
url: "set_rupture" ,
url: "set_rupture",
//dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
......@@ -128,7 +137,7 @@ function ruptureArticle(test){
}
});
}
}
var selArctileData;
......@@ -150,12 +159,11 @@ $(document).ready(function() {
four_id = $("#template-custom").getSelectedItemData().id;
}
}
,
},
getValue: "display_name",
template: {
type: "display_name",
type: "display_name"
//method: function(value, item) {
// return "<img src='" + item.icon + "' /> | " + item.type + " | " + value;
//}
......
......@@ -5,23 +5,23 @@
var table_article;
var dataSet =[] ;
var dataSet =[];
var csrftoken;
// lance la recherche sur le nom des l'article
function search_table_article(){
function search_table_article() {
table_article.ajax.url('get_list_article?rech='+$("#searchInput").val()).load();
}
// Lance la recherche sur les codes barres
function search_article_byBarcode(){
function search_article_byBarcode() {
table_article.ajax.url('get_article_byBarcode?rech='+$("#searchInput").val()).load();
}
}
// Initialise le table des articles
$(document).ready(function() {
table_article = $('#tableArticle').DataTable( {
table_article = $('#tableArticle').DataTable({
"ajax": {
"url": "get_list_article?rech=",
"data": ""
......@@ -32,26 +32,26 @@ $(document).ready(function() {
"title":"Photo",
"render": function (data, type, full, meta) {
debut = '<button id="page1" type="button" data-toggle="modal" data-target=".modal" data-remote=' + full.id + ' class="btn btn-primary">'
fin = "</button>"
debut = '<button id="page1" type="button" data-toggle="modal" data-target=".modal" data-remote=' + full.id + ' class="btn btn-primary">';
fin = "</button>";
return debut + "<img src='data:image/png;base64," + data + "'>" + fin;
}
},
{data:"name", "title":"Article","width": "50%"},
{data:"name", "title":"Article", "width": "50%"},
{data:"qty_available", "title":"En Stock", "width": "10%"},
{data:"uom_id",
"render":function (data, type, row){
"render":function (data, type, row) {
return data[1];
},
"title":"Unité","width":"5%"},
"title":"Unité", "width":"5%"},
{data:"reception_status",
"title":"Rupture", "className":"dt-body-center",
"render": function (data, type, full, meta) {
if (full.qty_available > 0 ) {
if (full.qty_available > 0) {
return "<div><button id='bt_change' href='#'>Rupture</button></div>";
} else{
} else {
return "<div>--</div>";
}
}
......@@ -59,7 +59,12 @@ $(document).ready(function() {
],
"searching": false,
"order": [[ 0, "desc" ]],
"order": [
[
0,
"desc"
]
],
"iDisplayLength": 25,
"language": {
"emptyTable": "Pas de donnée",
......@@ -85,12 +90,14 @@ $(document).ready(function() {
}
}
});
});
});
/* Listener */
/* Listener */
$(document).on('click','#dp_Search',function(){search_table_article();});
$(document).on('click', '#dp_Search', function() {
search_table_article();
});
//barcode-reader
......@@ -98,15 +105,17 @@ $(document).on('click','#dp_Search',function(){search_table_article();});
$(document).ready(function() {
var pressed = false;
var chars = [];
$(window).keypress(function(e) {
if (e.which >= 48 && e.which <= 57) {
chars.push(String.fromCharCode(e.which));
}
if (pressed == false) {
setTimeout(function(){
setTimeout(function() {
if (chars.length >= 13) {
var barcode = chars.join("");
if (!isNaN(barcode)) {
chars = [];
pressed = false;
......@@ -115,7 +124,7 @@ $(document).ready(function() {
}
},300);
}, 300);
}
pressed = true;
});
......@@ -126,14 +135,14 @@ $(document).ready(function() {
});
// Lancement de la rupture sur l'article choisie
function ruptureArticle(test){
function ruptureArticle(test) {
var jIdArcticle = { 'idArticle': selArctileData.id, 'uom_id' : selArctileData.uom_id[0] };
$.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } });
$.ajax({
type: "PUT",
url: "set_rupture" ,
url: "set_rupture",
//dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
......@@ -148,7 +157,7 @@ function ruptureArticle(test){
}
});
}
}
var selArctileData;
......@@ -160,11 +169,11 @@ $(document).on('click', 'button#bt_change', function () {
html ='<div id="askTitle" >Vous êtes sur que cet article est en rupture de stock ? </div>';
html += '<div id="showData" ><img id ="showImg" WIDTH="100" HEIGHT="100" src="data:image/png;base64,'+data.image_small+'"><div id="articleName" >'+data.name+'</div><div id="articleQty" >'+data.qty_available+ ' - '+data.uom_id[1] + '</div></div>';
selArctileData = data ;
selArctileData = data;
openModal(html, ruptureArticle, " - Ok - ");
} );
});
......@@ -6,14 +6,14 @@
// Initialise le table des articles
$(document).ready(function() {
table_article = $('#tableArticle').DataTable( {
table_article = $('#tableArticle').DataTable({
"ajax": {
"url": "get_saleWitheNotSale",
"data": ""
},
"columns":[
{data:"name", "title":"Article","width": "50%"},
{data:"name", "title":"Article", "width": "50%"},
{data:"qty", "title":"Qt. en vendu", "width":"15%"
......@@ -24,7 +24,12 @@ $(document).ready(function() {
],
"searching": true,
"order": [[ 2, "desc" ]],
"order": [
[
2,
"desc"
]
],
"iDisplayLength": 50,
"language": {
"emptyTable": "Pas de donnée",
......@@ -50,12 +55,14 @@ $(document).ready(function() {
}
}
});
});
});
/* Listener */
/* Listener */
$(document).on('click','#dp_Search',function(){search_table_article();});
$(document).on('click', '#dp_Search', function() {
search_table_article();
});
var csrftoken;
......@@ -65,25 +72,28 @@ $(document).ready(function() {
// Lancement de la rupture sur l'article choisie
function ruptureArticle(){
var jIdArcticle = { 'idArticle': selArctileData.id , 'uom_id' : selArctileData.uom_id };
actionButton("set_rupture",jIdArcticle, "/stock/stockQuantLastSale");
};
function archiveArticle(){
function ruptureArticle() {
var jIdArcticle = { 'idArticle': selArctileData.id, 'uom_id' : selArctileData.uom_id };
actionButton("set_rupture", jIdArcticle, "/stock/stockQuantLastSale");
}
function archiveArticle() {
var jIdArcticle = { 'idArticle': selArctileData.id};
actionButton("set_archive", jIdArcticle, "/stock/stockQuantLastSale");
};
}
function dontPurchase(){
function dontPurchase() {
var jIdArcticle = { 'idArticle': selArctileData.id};
actionButton("set_dontPurchase", jIdArcticle, "/stock/stockQuantLastSale");
};
function actionButton (vUrl,jIdArcticle, followPage){
}
function actionButton (vUrl, jIdArcticle, followPage) {
$.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } });
$.ajax({
type: "PUT",
url: vUrl ,
url: vUrl,
//dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
......@@ -105,36 +115,39 @@ var selArctileData;
$(document).on('click', 'button#bt_change', function () {
var row = table_article.row($(this).parents('tr'));
var data = row.data();
html ='<div id="askTitle" >Vous êtes sur que cet article est en rupture de stock ? </div>';
html += '<div id="showData" ><div id="articleName" >'+data.name+'</div><div id="articleQty" >'+data.stockqt+ ' - '+data.uom_id + '</div></div>';
selArctileData = data ;
selArctileData = data;
openModal(html, ruptureArticle, " - Ok - ");
} );
});
$(document).on('click', 'button#bt_archive', function () {
$(document).on('click', 'button#bt_archive', function () {
var row = table_article.row($(this).parents('tr'));
var data = row.data();
html ='<div id="askTitle" >Vous êtes sur que cet article doit être archivée ? </div>';
html += '<div id="showData" ><div id="articleName" >'+data.name+'</div><div id="articleQty" >'+data.stockqt+ ' - '+data.uom_id + '</div></div>';
selArctileData = data ;
selArctileData = data;
openModal(html, archiveArticle, " - Ok - ");
} );
$(document).on('click', '#bt_dontPurchase', function () {
});
$(document).on('click', '#bt_dontPurchase', function () {
if (!this.checked){
if (!this.checked) {
var row = table_article.row($(this).parents('tr'));
var data = row.data();
html ='<div id="askTitle" >Vous êtes sur que cet article ne doit plus être acheter ? </div>';
html += '<div id="showData" ><div id="articleName" >'+data.name+'</div><div id="articleQty" >'+data.stockqt+ ' - '+data.uom_id + '</div></div>';
selArctileData = data ;
selArctileData = data;
openModal(html, dontPurchase, " - Ok - ");
this.checked = true
}else{
this.checked = false
this.checked = true;
} else {
this.checked = false;
}
} );
});
......
......@@ -6,30 +6,32 @@
// Initialise le table des articles
$(document).ready(function() {
table_article = $('#tableArticle').DataTable( {
table_article = $('#tableArticle').DataTable({
"ajax": {
"url": "get_list_date_last_sale",
"data": ""
},
"columns":[
{data:"name", "title":"Article","width": "50%"},
{data:"name", "title":"Article", "width": "50%"},
{data:"maxdate",
"render":function (data, type, row){
my = new Date (data)
"render":function (data, type, row) {
my = new Date(data);
return my.toLocaleDateString() +" " + my.toLocaleTimeString();
},
"title":"Date","width":"15%"},
"title":"Date", "width":"15%"},
{data:"maxdate",
"render":function (data, type, row){
my = new Date (data)
"render":function (data, type, row) {
my = new Date(data);
var today = new Date();
dif = new Number((today - my)/86400000).toFixed(2);
return dif;
},
"title":"Durée","width":"5%"},
"title":"Durée", "width":"5%"},
{data:"stockqt", "title":"Qt. en Stock", "width":"5%"
},
......@@ -37,10 +39,11 @@ $(document).ready(function() {
"title":"Achetable", "className":"dt-body-center",
"render": function (data, type, full, meta) {
if (data == true){
return '<div><input type="checkbox" id="bt_dontPurchase" checked><div>';}
else{
return '<div><input type="checkbox" id="bt_dontPurchase" ><div>';}
if (data == true) {
return '<div><input type="checkbox" id="bt_dontPurchase" checked><div>';
} else {
return '<div><input type="checkbox" id="bt_dontPurchase" ><div>';
}
}
},
{data:"reception_status", "width":"5%",
......@@ -60,7 +63,12 @@ $(document).ready(function() {
],
"searching": true,
"order": [[ 2, "desc" ]],
"order": [
[
2,
"desc"
]
],
"iDisplayLength": 50,
"language": {
"emptyTable": "Pas de donnée",
......@@ -86,12 +94,14 @@ $(document).ready(function() {
}
}
});
});
});
/* Listener */
/* Listener */
$(document).on('click','#dp_Search',function(){search_table_article();});
$(document).on('click', '#dp_Search', function() {
search_table_article();
});
var csrftoken;
......@@ -101,25 +111,28 @@ $(document).ready(function() {
// Lancement de la rupture sur l'article choisie
function ruptureArticle(){
var jIdArcticle = { 'idArticle': selArctileData.id , 'uom_id' : selArctileData.uom_id };
actionButton("set_rupture",jIdArcticle, "/stock/stockQuantLastSale");
};
function archiveArticle(){
function ruptureArticle() {
var jIdArcticle = { 'idArticle': selArctileData.id, 'uom_id' : selArctileData.uom_id };
actionButton("set_rupture", jIdArcticle, "/stock/stockQuantLastSale");
}
function archiveArticle() {
var jIdArcticle = { 'idArticle': selArctileData.id};
actionButton("set_archive", jIdArcticle, "/stock/stockQuantLastSale");
};
}
function dontPurchase(){
function dontPurchase() {
var jIdArcticle = { 'idArticle': selArctileData.id};
actionButton("set_dontPurchase", jIdArcticle, "/stock/stockQuantLastSale");
};
function actionButton (vUrl,jIdArcticle, followPage){
}
function actionButton (vUrl, jIdArcticle, followPage) {
$.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } });
$.ajax({
type: "PUT",
url: vUrl ,
url: vUrl,
//dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
......@@ -141,36 +154,39 @@ var selArctileData;
$(document).on('click', 'button#bt_change', function () {
var row = table_article.row($(this).parents('tr'));
var data = row.data();
html ='<div id="askTitle" >Vous êtes sur que cet article est en rupture de stock ? </div>';
html += '<div id="showData" ><div id="articleName" >'+data.name+'</div><div id="articleQty" >'+data.stockqt+ ' - '+data.uom_id + '</div></div>';
selArctileData = data ;
selArctileData = data;
openModal(html, ruptureArticle, " - Ok - ");
} );
});
$(document).on('click', 'button#bt_archive', function () {
$(document).on('click', 'button#bt_archive', function () {
var row = table_article.row($(this).parents('tr'));
var data = row.data();
html ='<div id="askTitle" >Vous êtes sur que cet article doit être archivée ? </div>';
html += '<div id="showData" ><div id="articleName" >'+data.name+'</div><div id="articleQty" >'+data.stockqt+ ' - '+data.uom_id + '</div></div>';
selArctileData = data ;
selArctileData = data;
openModal(html, archiveArticle, " - Ok - ");
} );
$(document).on('click', '#bt_dontPurchase', function () {
});
$(document).on('click', '#bt_dontPurchase', function () {
if (!this.checked){
if (!this.checked) {
var row = table_article.row($(this).parents('tr'));
var data = row.data();
html ='<div id="askTitle" >Vous êtes sur que cet article ne doit plus être acheter ? </div>';
html += '<div id="showData" ><div id="articleName" >'+data.name+'</div><div id="articleQty" >'+data.stockqt+ ' - '+data.uom_id + '</div></div>';
selArctileData = data ;
selArctileData = data;
openModal(html, dontPurchase, " - Ok - ");
this.checked = true
}else{
this.checked = false
this.checked = true;
} else {
this.checked = false;
}
} );
});
......
......@@ -3,59 +3,71 @@ try {
m_sel = $('[name="mm"]'),
j_sel = $('[name="jj"]'),
birthdate = $('[name="birthdate"]'),
save_btn = $('#save')
save_btn = $('#save');
var make_save_button_active = function() {
if (! save_btn.hasClass('btn--primary')) {
save_btn.addClass('btn--primary')
save_btn.css({'cursor':'pointer'})
}
save_btn.addClass('btn--primary');
save_btn.css({'cursor':'pointer'});
}
};
var update_birthdate = function() {
birthdate.val(y_sel.val() + '-' + m_sel.val() + '-' + j_sel.val())
make_save_button_active()
}
birthdate.val(y_sel.val() + '-' + m_sel.val() + '-' + j_sel.val());
make_save_button_active();
};
var init_birthdate_selects = function() {
let [
y,
m,
d
] = birthdate.val().split('-');
var init_birthdate_selects = function(){
let [y,m,d] = birthdate.val().split('-')
var now = new Date();
var end_year = new Date(now.setYear(now.getFullYear() - 15)).getFullYear();
var now = new Date()
var end_year = new Date(now.setYear(now.getFullYear() - 15)).getFullYear()
for (var i=100; i>0; i--) {
var opt = $('<option>').val(end_year-i).text(end_year-i)
if (end_year-i == y) opt.prop('selected', true)
opt.appendTo(y_sel)
var opt = $('<option>').val(end_year-i)
.text(end_year-i);
if (end_year-i == y) opt.prop('selected', true);
opt.appendTo(y_sel);
}
for (var k=1; k<=12; k++) {
let mth = k.pad(2)
var opt = $('<option>').val(mth).text(mth)
if (m == mth) opt.prop('selected', true)
opt.appendTo(m_sel)
let mth = k.pad(2);
var opt = $('<option>').val(mth)
.text(mth);
if (m == mth) opt.prop('selected', true);
opt.appendTo(m_sel);
}
for (var l=1; l<=31; l++) {
let day = l.pad(2)
var opt = $('<option>').val(day).text(day)
if (d == day) opt.prop('selected', true)
opt.appendTo(j_sel)
}
y_sel.change(update_birthdate)
m_sel.change(update_birthdate)
j_sel.change(update_birthdate)
let day = l.pad(2);
var opt = $('<option>').val(day)
.text(day);
if (d == day) opt.prop('selected', true);
opt.appendTo(j_sel);
}
y_sel.change(update_birthdate);
m_sel.change(update_birthdate);
j_sel.change(update_birthdate);
};
var save_data = function() {
//Transmit only what has been changed
var changed = {}
var changed = {};
for (attr in original) {
var current_val = $('[name="' + attr + '"]').val()
var current_val = $('[name="' + attr + '"]').val();
if (attr == 'sex') {
current_val = $('[name="' + attr + '"]:checked').val()
current_val = $('[name="' + attr + '"]:checked').val();
}
if (current_val.trim() != original[attr]) {
if (! (original[attr] == 'False' && current_val.length ==0))
changed[attr] = current_val.trim()
changed[attr] = current_val.trim();
}
}
// console.log(changed)
......@@ -63,9 +75,9 @@ try {
if ('firstname' in changed || 'lastname' in changed) {
changed['name'] = $('[name="firstname"]').val()
+ name_sep
+ $('[name="lastname"]').val()
+ $('[name="lastname"]').val();
}
delete changed['email']
delete changed['email'];
post_form(
'/website/update_info_perso',
changed,
......@@ -73,38 +85,39 @@ try {
if (typeof result.res.process != "undefined" &&
typeof result.res.process.update != "undefined" &&
result.res.process.update == true) {
save_btn.removeClass('btn--primary')
save_btn.css({'cursor':'default'})
save_btn.removeClass('btn--primary');
save_btn.css({'cursor':'default'});
for (attr in changed) {
if (attr != 'name')
original[attr] = changed[attr]
original[attr] = changed[attr];
}
alert('Modifications enregistrées !')
alert('Modifications enregistrées !');
} else {
alert('Une erreur est intervenue pendant l\'enregistrement')
alert('Une erreur est intervenue pendant l\'enregistrement');
}
}
)
);
} else {
alert('Aucune modification significative détectée')
alert('Aucune modification significative détectée');
}
}
};
if (typeof original.sex != "undefined") {
$("#" + original.sex + "_sex").prop('checked', true)
$("#" + original.sex + "_sex").prop('checked', true);
}
init_birthdate_selects()
$('input').keyup(make_save_button_active)
init_birthdate_selects();
$('input').keyup(make_save_button_active);
save_btn.click(function() {
if ($(this).hasClass('btn--primary') && is_time_to('save_perso_data')) {
save_data();
}
})
});
} catch(error) {
err_obj = {msg: error.name + ' : ' + error.message, ctx: 'info_perso'}
report_JS_error(error, 'website')
} catch (error) {
err_obj = {msg: error.name + ' : ' + error.message, ctx: 'info_perso'};
report_JS_error(error, 'website');
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment