Unverified Commit c2889195 by Paul B

[AUTO] apply automatic fixes from eslint rules

parent 5753246a
var shelfs_table = null
function init_datatable() {
return $('#lists').DataTable( {
data: lists, // data passed at page loading
rowId: 'id',
columns:[
{data: "id", title:"id", "visible": false},
{
data:"datetime_created",
title:"Liste",
render: function (data, type, full, meta) {
return "Liste du " + data
}
},
{data:"p_nb", title:"Nombre de réfs", width: "10%", className:"dt-body-center"},
{
data:"inventory_status",
title:"Inventaire à faire",
className:"dt-body-center",
width: "15%",
render: function (data, type, full, meta) {
if (data == '')
return "<button class='btn--primary do_inventory'>Inventaire en rayon</button>"
else
return "<button class='btn--success do_inventory'>Inventaire en réserve</button>"
}
}
],
dom: 'rtip',
order: [[ 1, "asc" ]],
iDisplayLength: 25,
language: {url : '/static/js/datatables/french.json'}
})
}
function go_to_inventory() {
openModal()
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))
// Set local storage if key doesn't exist
if (stored_list == null) {
localStorage.setItem("custom_list_" + row_data.id , JSON.stringify(row_data))
}
}
document.location.href = "custom_list_inventory/" + row_data.id
}
$(document).ready(function() {
console.log(lists)
shelfs_table = init_datatable()
$(document).on('click', 'button.do_inventory', go_to_inventory)
})
var shelfs_table = null;
function init_datatable() {
return $('#lists').DataTable({
data: lists, // data passed at page loading
rowId: 'id',
columns:[
{data: "id", title:"id", "visible": false},
{
data:"datetime_created",
title:"Liste",
render: function (data, type, full, meta) {
return "Liste du " + data;
}
},
{data:"p_nb", title:"Nombre de réfs", width: "10%", className:"dt-body-center"},
{
data:"inventory_status",
title:"Inventaire à faire",
className:"dt-body-center",
width: "15%",
render: function (data, type, full, meta) {
if (data == '')
return "<button class='btn--primary do_inventory'>Inventaire en rayon</button>";
else
return "<button class='btn--success do_inventory'>Inventaire en réserve</button>";
}
}
],
dom: 'rtip',
order: [
[
1,
"asc"
]
],
iDisplayLength: 25,
language: {url : '/static/js/datatables/french.json'}
});
}
function go_to_inventory() {
openModal();
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));
// Set local storage if key doesn't exist
if (stored_list == null) {
localStorage.setItem("custom_list_" + row_data.id, JSON.stringify(row_data));
}
}
document.location.href = "custom_list_inventory/" + row_data.id;
}
$(document).ready(function() {
console.log(lists);
shelfs_table = init_datatable();
$(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() {
schoice_view.show();
coop_page.hide();
retrieve_and_draw_shift_tempates();
schoice_view.show();
coop_page.hide();
retrieve_and_draw_shift_tempates();
}
function display_current_coop_form() {
let form = $('#coop_validation_form'),
chgt_shift_btn = $('#change_shift_template');
var ftop_shift = $('#choosen_shift [name="ftop"]'),
m_barcode = form.find('[name="m_barcode"]'),
sex = $('#sex')
let street2_input = form.find('[name="street2"]'),
phone_input = form.find('[name="phone"]')
chgt_shift_btn.hide();
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)
}
//console.log(current_coop)
if (sex.length > 0 && typeof current_coop.sex != "undefined") {
$("#" + current_coop.sex + "_sex").prop('checked', true)
}
// form.find('[name="barcode_base"]').val(current_coop.barcode_base);
form.find('[name="email"]').val(current_coop._id);
if (current_coop.shift_template &&
let form = $('#coop_validation_form'),
chgt_shift_btn = $('#change_shift_template');
var ftop_shift = $('#choosen_shift [name="ftop"]'),
m_barcode = form.find('[name="m_barcode"]'),
sex = $('#sex');
let street2_input = form.find('[name="street2"]'),
phone_input = form.find('[name="phone"]');
chgt_shift_btn.hide();
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);
}
//console.log(current_coop)
if (sex.length > 0 && typeof current_coop.sex != "undefined") {
$("#" + current_coop.sex + "_sex").prop('checked', true);
}
// form.find('[name="barcode_base"]').val(current_coop.barcode_base);
form.find('[name="email"]').val(current_coop._id);
if (current_coop.shift_template &&
current_coop.shift_template.data.type == 2) {
$('#choosen_shift input').hide();
ftop_shift.val('Volant');
ftop_shift.show();
$('#choosen_shift input').hide();
ftop_shift.val('Volant');
ftop_shift.show();
} else {
} else {
// Bien laisser dans cet ordre
$('#choosen_shift input').show();
ftop_shift.hide();
}
form.find('[name="birthdate"]').val(current_coop.birthdate || '');
form.find('[name="address"]').val(current_coop.address || '');
form.find('[name="city"]').val(current_coop.city || '');
form.find('[name="zip"]').val(current_coop.zip || '');
form.find('[name="country"]').val(current_coop.country || 'France');
form.find('[name="mobile"]').val(current_coop.mobile || '');
form.find('[name="shares_nb"]').val(current_coop.shares_nb || '');
form.find('[name="shares_euros"]').val(current_coop.shares_euros || '');
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 || '')
}
if (phone_input.length > 0) {
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") {
show_checks_nb();
// Display check details if in payment validation step and more than 1 check
if (current_coop.validation_state == "waiting_validation_employee" && current_coop.checks_nb > 1) {
$('#checks').show();
for (var i = 1; i <= current_coop.checks_nb; i++) {
$(check_details).append('<p>Chèque #' + i +' : <input type="text" name="check_' + i + '" class="b_green check_item" required/> € </p>');
}
$('#choosen_shift input').show();
ftop_shift.hide();
}
form.find('[name="birthdate"]').val(current_coop.birthdate || '');
form.find('[name="address"]').val(current_coop.address || '');
form.find('[name="city"]').val(current_coop.city || '');
form.find('[name="zip"]').val(current_coop.zip || '');
form.find('[name="country"]').val(current_coop.country || 'France');
form.find('[name="mobile"]').val(current_coop.mobile || '');
form.find('[name="shares_nb"]').val(current_coop.shares_nb || '');
form.find('[name="shares_euros"]').val(current_coop.shares_euros || '');
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 || '');
}
}
var show_change_shift = false;
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) {
place = 'Bureau';
if (phone_input.length > 0) {
phone_input.val(current_coop.phone || '');
}
form.find('[name="place"]').val(place);
if (current_coop.coop_msg) {
show_change_shift = true;
// 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") {
show_checks_nb();
// Display check details if in payment validation step and more than 1 check
if (current_coop.validation_state == "waiting_validation_employee" && current_coop.checks_nb > 1) {
$('#checks').show();
for (var i = 1; i <= current_coop.checks_nb; i++) {
$(check_details).append('<p>Chèque #' + i +' : <input type="text" name="check_' + i + '" class="b_green check_item" required/> € </p>');
}
}
}
} else {
show_change_shift = true;
}
if (show_change_shift == true) {
chgt_shift_btn.show();
chgt_shift_btn.on('click',open_shift_choice);
}
var show_change_shift = false;
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) {
place = 'Bureau';
}
form.find('[name="place"]').val(place);
if (current_coop.coop_msg) {
show_change_shift = true;
}
} else {
show_change_shift = true;
}
if (typeof(coop_page) != "undefined"){coop_page.show();}
if (show_change_shift == true) {
chgt_shift_btn.show();
chgt_shift_btn.on('click', open_shift_choice);
}
if (typeof(coop_page) != "undefined") {
coop_page.show();
}
}
$('#payment_meaning').change(function(){
if ($(this).val() == 'ch'){
show_checks_nb()
} else {
hide_checks_nb()
}
$('#payment_meaning').change(function() {
if ($(this).val() == 'ch') {
show_checks_nb();
} else {
hide_checks_nb();
}
});
......@@ -7,24 +7,24 @@ 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(){
vform.hide();
wform.show();
function show_warning_form() {
vform.hide();
wform.show();
}
function show_coop_form() {
......@@ -36,79 +36,98 @@ 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'){
var form_data = new FormData(vform.get(0)),
has_empty_values = false;
if (sex.length > 0) {
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',''))
}
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
}
}
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('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('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(
'sex',
$('input[name="sex"]:checked').attr('id')
.replace('_sex', '')
);
}
openModal()
post_form('/members/coop_validated_data',form_data,
function(err,result){
closeModal();
if (!err) {
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;
}
}
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('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('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);
}
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();
vform.remove();
display_msg_box(msg);
}
}
});
}
}
);
}
} 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){
closeModal();
if (!err) {
$('#main_content').remove()
display_msg_box('Message enregistré ! Le bureau des membres est averti.');
}
});
'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();
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 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,16 +44,18 @@
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) {
node.displayed = 0;
break; // Once the first token isn't found we're done
break; // Once the first token isn't found we're done
}
}
}
......@@ -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));
});
});
......
......@@ -8,73 +8,82 @@
var actionCheckboxes = $(this);
var list_editable_changed = false;
var showQuestion = function() {
$(options.acrossClears).hide();
$(options.acrossQuestions).show();
$(options.allContainer).hide();
},
showClear = function() {
$(options.acrossClears).show();
$(options.acrossQuestions).hide();
$(options.actionContainer).toggleClass(options.selectedClass);
$(options.allContainer).show();
$(options.counterContainer).hide();
},
reset = function() {
$(options.acrossClears).hide();
$(options.acrossQuestions).hide();
$(options.allContainer).hide();
$(options.counterContainer).show();
},
clearAcross = function() {
reset();
$(options.acrossInput).val(0);
$(options.actionContainer).removeClass(options.selectedClass);
},
checker = function(checked) {
if (checked) {
showQuestion();
} else {
$(options.acrossClears).hide();
$(options.acrossQuestions).show();
$(options.allContainer).hide();
},
showClear = function() {
$(options.acrossClears).show();
$(options.acrossQuestions).hide();
$(options.actionContainer).toggleClass(options.selectedClass);
$(options.allContainer).show();
$(options.counterContainer).hide();
},
reset = function() {
$(options.acrossClears).hide();
$(options.acrossQuestions).hide();
$(options.allContainer).hide();
$(options.counterContainer).show();
},
clearAcross = function() {
reset();
}
$(actionCheckboxes).prop("checked", 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), {
sel: sel,
cnt: actions_icnt
}, true));
$(options.allToggle).prop("checked", function() {
var value;
if (sel === actionCheckboxes.length) {
value = true;
$(options.acrossInput).val(0);
$(options.actionContainer).removeClass(options.selectedClass);
},
checker = function(checked) {
if (checked) {
showQuestion();
} else {
value = false;
clearAcross();
reset();
}
return value;
});
};
$(actionCheckboxes).prop("checked", 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), {
sel: sel,
cnt: actions_icnt
}, true));
$(options.allToggle).prop("checked", function() {
var value;
if (sel === actionCheckboxes.length) {
value = true;
showQuestion();
} else {
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);
updateCounter();
if ($(options.acrossInput).val() === 1) {
showClear();
}
});
$(options.allToggle).show().click(function() {
checker($(this).prop("checked"));
updateCounter();
});
$(this).filter(":checked")
.each(function(i) {
$(this).parent()
.parent()
.toggleClass(options.selectedClass);
updateCounter();
if ($(options.acrossInput).val() === 1) {
showClear();
}
});
$(options.allToggle).show()
.click(function() {
checker($(this).prop("checked"));
updateCounter();
});
$("a", options.acrossQuestions).click(function(event) {
event.preventDefault();
$(options.acrossInput).val(1);
......@@ -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,32 +113,44 @@
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;
this.title = newRepr;
});
this.lastChild.textContent = newRepr;
this.title = newRepr;
});
win.close();
}
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,20 +180,21 @@ 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":
day = date[i];
break;
case "%m":
month = date[i] - 1;
break;
case "%Y":
year = date[i];
break;
case "%y":
year = date[i];
break;
case "%d":
day = date[i];
break;
case "%m":
month = date[i] - 1;
break;
case "%Y":
year = date[i];
break;
case "%y":
year = date[i];
break;
}
++i;
}
......@@ -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;
}
......@@ -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){
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.')
$.ajax({url : url + '?phase=2&export_id='+export_id+ '&final_format=' + $('[name="final_format"]').val(),
dataType :'json'
})
.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()
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> € ')
.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.');
$.ajax({url : url + '?phase=2&export_id='+export_id+ '&final_format=' + $('[name="final_format"]').val(),
dataType :'json'
})
.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');
$('body')
.append(preambule)
.append(vente_ht)
.append(tva)
.append(download_link)
} else {
$('body').append(download_link)
}
}
closeWaiting()
})
}
$('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> € ');
})
$('body')
.append(preambule)
.append(vente_ht)
.append(tva)
.append(download_link);
} else {
$('body').append(download_link);
}
}
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){
'to': year + '-' + month + '-' + new Date(year, month, 0).getDate()
};
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(),
type: elt.get(0).type,
value: val}
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};
}
post_form('settings', {params: JSON.stringify(data)},
function(err,result){
if (!err) {
var succeeded = false
try {
if (result.res.save == true) {
display_msg_box('Enregistrement réussi !')
succeeded = true
}
} catch(e) {
console.log(e)
}
if (succeeded == false) display_msg_box('L\'enregistrement a échoué !', 'error')
} else {
console.log(err)
}
})
post_form(
'settings', {params: JSON.stringify(data)},
function(err, result) {
if (!err) {
var succeeded = false;
try {
if (result.res.save == true) {
display_msg_box('Enregistrement réussi !');
succeeded = true;
}
} catch (e) {
console.log(e);
}
if (succeeded == false) display_msg_box('L\'enregistrement a échoué !', 'error');
} else {
console.log(err);
}
}
);
}
function get_module_settings() {
$.ajax('settings')
.done(function(rData){
try {
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)
if (data.type == 'textarea') {
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)
}
/*
.done(function(rData) {
try {
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);
if (data.type == 'textarea') {
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);
}
/*
console.log(key)
console.log(data)
console.log(param)
*/
param.appendTo(main_content)
added_elts.push(key)
}
if (added_elts.length > 0) {
submit_btn.appendTo(main_content)
param.appendTo(main_content);
added_elts.push(key);
}
if (added_elts.length > 0) {
submit_btn.appendTo(main_content);
}
submit_btn.click(save_module_settings);
}
submit_btn.click(save_module_settings)
} catch (e) {
console.log(e);
}
} catch (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){
columns.push(e);
$.each(cols, function(i, e) {
columns.push(e);
});
var settings = {
dom: '<lf<t>ip><"clear"><B>',
lengthMenu : [[50,100,150,200,-1],[50,100,150,200,'Tout']],
pageLength : 50,
buttons: buttons,
dom: '<lf<t>ip><"clear"><B>',
lengthMenu : [
[
50,
100,
150,
200,
-1
],
[
50,
100,
150,
200,
'Tout'
]
],
pageLength : 50,
buttons: buttons,
columns: columns,
//select: select ,
rowId : "_id",
data : data,
language: {url : '/static/js/datatables/french.json'}
}
columns: columns,
//select: select ,
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 = []
var cols = [
{data: 'date', title: "Date"},
{data: 'module', title: "Module"},
{data: 'agent', title: "Signature nav."},
{data: 'context', title: "Contexte"},
{data: 'message', title: "Message"},
.done(function(rData) {
if (typeof rData.res.content != "undefined") {
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"}
]
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
} else {
line.context = '?'
line.message = e.data
}
data.push(line)
})
console.log(data)
results_table = coop_init_datatable(null, data, cols);
}
})
}
];
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;
} else {
line.context = '?';
line.message = e.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
......@@ -3,24 +3,31 @@
var oidoc = {
_id: '_design/index',
views: {
by_fp: {
map: function (doc) { emit(doc.fingerprint); }.toString()
},
by_completed: {
map: function (doc) { emit(doc.completed); }.toString()
},
by_odoo_id: {
map: function (doc) { emit(doc.odoo_id); }.toString()
_id: '_design/index',
views: {
by_fp: {
map: function (doc) {
emit(doc.fingerprint);
}.toString()
},
by_completed: {
map: function (doc) {
emit(doc.completed);
}.toString()
},
by_odoo_id: {
map: function (doc) {
emit(doc.odoo_id);
}.toString()
}
}
}
};
// save it
dbc.put(oidoc,function (err, result) {
if (!err) {
console.log('index enregistré');
} else {
dbc.put(oidoc, function (err, result) {
if (!err) {
console.log('index enregistré');
} else {
//console.log(err);
}
}
});
\ No newline at end of file
......@@ -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()
if (ifcb.errors.length > 0)
ifcb.display_last_error()
else
result = ifcb
// console.log(result.patterns)
return result
}
var result = null;
var ifcb = Object.create(IFCBarcodes);
await ifcb.init();
if (ifcb.errors.length > 0)
ifcb.display_last_error();
else
result = ifcb;
// console.log(result.patterns)
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)
} else {
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){
//access `event.code` - barcode data
var barcode = event.code
if (barcode.length >=13) {
barcode = barcode.substring(barcode.length-13)
search_in_pdt_list(barcode)
} else {
console.log($(':focus').attr('type'))
console.log(new Date().getTime() + ' -> '+barcode)
}
});
$(document).on('scan.pos.barcode', function(event) {
//access `event.code` - barcode data
var barcode = event.code;
if (barcode.length >=13) {
barcode = barcode.substring(barcode.length-13);
search_in_pdt_list(barcode);
} else {
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()
var cols = [
{data: 'display_name', title: "Nom"},
{data: 'qty', title: "Quantité", defaultContent: ""}
]
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) {
if (dt.rows().indexes().length > 0)
openModal('Valider le déstockage', destocking_record, 'Enregistrer');
else
alert("Impossible, il n'y a aucun produit !")
}
};
var params = {no_search: true}
text: 'Valider le déstockage',
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 !");
}
};
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({
......
......@@ -8,96 +8,101 @@ Informations affichées :
var parent_location = '/shelfs',
shelf,
table_products,
search_chars = []
search_chars = [];
/* UTILS */
// Round a decimal value
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
return Number(Math.round(value+'e'+decimals)+'e-'+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) {
if (e.barcode == barcode) {
$('#search_input').val(e.name)
table_products.search(jQuery.fn.DataTable.ext.type.search.string(e.name)).draw()
}
})
$.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();
}
});
}
/* LIST HANDLING */
// Init Data & listeners
function initList() {
// Init table for items to process
table_products = $('#table_shelf_products').DataTable( {
data: shelf_products,
columns: [
{data:"id", title: "id", visible: false},
{data:"name", title:"Produit"},
{
data:"qty_available",
title:"Stock théorique",
width: "10%",
render: function (data, type, full) {
return round(data, 2) + ' ' + full.uom_id[1]
}
},
{
data:"last_inv_delta",
title:"Delta (dernier inv.)",
width: "10%",
className:"dt-body-center",
render: function (data, type, full, meta) {
if (type == "sort" || type == 'type')
return data
if (data == -99999999) {
return '/'
} else {
return data
}
}
},
{
data:"last_inv_losses",
title:"Pertes (dernier inv.)",
width: "10%",
className:"dt-body-center",
render: function (data, type, full, meta) {
if (type == "sort" || type == 'type')
return data
if (data == -99999999) {
return '/'
} else {
return data + ' €'
}
}
},
],
rowId : "id",
order: [[ 0, "asc" ]],
paging: false,
dom: 'lrtip', // Remove the search input from that table
language: {url : '/static/js/datatables/french.json'}
});
/* Listeners on table & search input */
// Search input for table
$('#search_input').on('keyup', function () {
table_products
.search(jQuery.fn.DataTable.ext.type.search.string(this.value)) // search without accents (see DataTable plugin)
.draw()
})
// Init table for items to process
table_products = $('#table_shelf_products').DataTable({
data: shelf_products,
columns: [
{data:"id", title: "id", visible: false},
{data:"name", title:"Produit"},
{
data:"qty_available",
title:"Stock théorique",
width: "10%",
render: function (data, type, full) {
return round(data, 2) + ' ' + full.uom_id[1];
}
},
{
data:"last_inv_delta",
title:"Delta (dernier inv.)",
width: "10%",
className:"dt-body-center",
render: function (data, type, full, meta) {
if (type == "sort" || type == 'type')
return data;
if (data == -99999999) {
return '/';
} else {
return data;
}
}
},
{
data:"last_inv_losses",
title:"Pertes (dernier inv.)",
width: "10%",
className:"dt-body-center",
render: function (data, type, full, meta) {
if (type == "sort" || type == 'type')
return data;
if (data == -99999999) {
return '/';
} else {
return data + ' €';
}
}
}
],
rowId : "id",
order: [
[
0,
"asc"
]
],
paging: false,
dom: 'lrtip', // Remove the search input from that table
language: {url : '/static/js/datatables/french.json'}
});
/* Listeners on table & search input */
// Search input for table
$('#search_input').on('keyup', function () {
table_products
.search(jQuery.fn.DataTable.ext.type.search.string(this.value)) // search without accents (see DataTable plugin)
.draw();
});
}
......@@ -105,76 +110,78 @@ function initList() {
// Get shelf data from server if not in local storage
function get_shelf_data() {
$.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });
$.ajax({
type: 'GET',
url: '../' + shelf.id,
dataType:"json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function(data) {
shelf = data.res
init()
},
error: function(data) {
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.');
}
})
$.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });
$.ajax({
type: 'GET',
url: '../' + shelf.id,
dataType:"json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function(data) {
shelf = data.res;
init();
},
error: function(data) {
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)
// Set shelf name in DOM
$('#shelf_name').text(shelf.name);
// Products passed at page loading as 'shelf_products'
initList()
// Products passed at page loading as 'shelf_products'
initList();
// Barcode reader: listen for 13 digits read in a very short time
$('#search_input').keypress(function(e) {
if (e.which >= 48 && e.which <= 57) {
search_chars.push(String.fromCharCode(e.which));
}
if (search_chars.length >= 13) {
var barcode = search_chars.join("");
if (!isNaN(barcode)) {
search_chars = [];
setTimeout(function(){
select_product_from_bc(barcode);
}, 300);
}
}
})
// Barcode reader: listen for 13 digits read in a very short time
$('#search_input').keypress(function(e) {
if (e.which >= 48 && e.which <= 57) {
search_chars.push(String.fromCharCode(e.which));
}
if (search_chars.length >= 13) {
var barcode = search_chars.join("");
if (!isNaN(barcode)) {
search_chars = [];
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]}
// Get Route parameter
var pathArray = window.location.pathname.split('/');
// Get shelf data from local storage
if (Modernizr.localstorage) {
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + shelf.id))
shelf = {id: pathArray[pathArray.length-1]};
if (stored_shelf != null) {
shelf = stored_shelf
init()
// Get shelf data from local storage
if (Modernizr.localstorage) {
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + shelf.id));
if (stored_shelf != null) {
shelf = stored_shelf;
init();
} else {
// Get shelf info if not coming from shelves list
get_shelf_data();
}
} else {
// Get shelf info if not coming from shelves list
get_shelf_data()
get_shelf_data();
}
} else {
get_shelf_data()
}
// listeners
// Cancel search
$('.cancel_search').on('click', function () {
$('#search_input').val('')
table_products.search('').draw()
})
// listeners
// Cancel search
$('.cancel_search').on('click', function () {
$('#search_input').val('');
table_products.search('').draw();
});
});
var shelfs_table = null
function init_datatable() {
return $('#shelfs').DataTable( {
data: shelfs, // data passed at page loading
rowId: 'id',
columns:[
{data: "id", title:"id", "visible": false},
{
data:"sort_order",
title:"Numéro",
width: "10%",
className:"dt-body-center"
},
{data:"name", title:"Nom"},
{data:"description", title:"Description", orderable: false},
{
data:"date_last_inventory",
title:"Date dernier inventaire",
render: function (data, type, full, meta) {
// Sort on data, not rendering
if (type == "sort" || type == 'type')
return data
if (data == '0001-01-01')
return "Ce rayon n'a jamais été inventorié !"
else {
var date = new Date(data)
return date.toLocaleDateString('fr-FR')
}
}
},
{data:"p_nb", title:"Nb réfs", width: "5%", className:"dt-body-center"},
{
title:"",
className:"dt-body-center",
width: "15%",
render: function (data, type, full, meta) {
return "<button class='btn--success do_export_sales_data'>Export Ventes</button>"
}
}
],
dom: 'rtip',
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()
}
function go_to_shelf_view() {
openModal()
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))
// Set local storage if key doesn't exist
if (stored_shelf == null) {
localStorage.setItem("shelf_" + row_data.id , JSON.stringify(row_data))
}
}
document.location.href = "shelf_view/" + row_data.id
}
function get_shelfs_sales_data() {
try {
$.ajax({
type: 'GET',
url: '/shelfs/get_shelves_sales_data',
dataType:"json",
traditional: true,
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
shelfs_table
.row( '#'+item.id )
.data( row_data )
.draw()
}
},
error: function(data) {
if (typeof data.responseJSON != 'undefined') {
console.log(data.responseJSON)
}
}
})
} catch (e) {
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)
}
$(document).ready(function() {
shelfs_table = init_datatable()
$('#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()
})
})
var shelfs_table = null;
function init_datatable() {
return $('#shelfs').DataTable({
data: shelfs, // data passed at page loading
rowId: 'id',
columns:[
{data: "id", title:"id", "visible": false},
{
data:"sort_order",
title:"Numéro",
width: "10%",
className:"dt-body-center"
},
{data:"name", title:"Nom"},
{data:"description", title:"Description", orderable: false},
{
data:"date_last_inventory",
title:"Date dernier inventaire",
render: function (data, type, full, meta) {
// Sort on data, not rendering
if (type == "sort" || type == 'type')
return data;
if (data == '0001-01-01')
return "Ce rayon n'a jamais été inventorié !";
else {
var date = new Date(data);
return date.toLocaleDateString('fr-FR');
}
}
},
{data:"p_nb", title:"Nb réfs", width: "5%", className:"dt-body-center"},
{
title:"",
className:"dt-body-center",
width: "15%",
render: function (data, type, full, meta) {
return "<button class='btn--success do_export_sales_data'>Export Ventes</button>";
}
}
],
dom: 'rtip',
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();
};
function go_to_shelf_view() {
openModal();
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));
// Set local storage if key doesn't exist
if (stored_shelf == null) {
localStorage.setItem("shelf_" + row_data.id, JSON.stringify(row_data));
}
}
document.location.href = "shelf_view/" + row_data.id;
}
function get_shelfs_sales_data() {
try {
$.ajax({
type: 'GET',
url: '/shelfs/get_shelves_sales_data',
dataType:"json",
traditional: true,
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;
shelfs_table
.row('#'+item.id)
.data(row_data)
.draw();
}
},
error: function(data) {
if (typeof data.responseJSON != 'undefined') {
console.log(data.responseJSON);
}
}
});
} catch (e) {
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);
}
$(document).ready(function() {
shelfs_table = init_datatable();
$('#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();
});
});
// Request a delay for the current member
function request_delay() {
//Loading on
openModal();
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
//Loading on
openModal();
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
$.ajaxSetup({headers: {"X-CSRFToken": getCookie('csrftoken')}});
$.ajax({
type: 'POST',
url: '/shifts/request_delay',
dataType: 'json',
timeout: 3000,
data: {
idPartner: dataPartner.partner_id,
verif_token: dataPartner.verif_token,
start_date: date
},
success: function(doc) {
document.location.reload();
},
error: function() {
closeModal();
alert('Impossible de créer l\'extension. Je dois passer au Bureau des membres pour régler le problème.');
}
});
$.ajaxSetup({headers: {"X-CSRFToken": getCookie('csrftoken')}});
$.ajax({
type: 'POST',
url: '/shifts/request_delay',
dataType: 'json',
timeout: 3000,
data: {
idPartner: dataPartner.partner_id,
verif_token: dataPartner.verif_token,
start_date: date
},
success: function(doc) {
document.location.reload();
},
error: function() {
closeModal();
alert('Impossible de créer l\'extension. Je dois passer au Bureau des membres pour régler le problème.');
}
});
}
$(document).ready(function() {
$('#'+dataPartner.cooperative_state).removeAttr('hidden');
$('#'+dataPartner.cooperative_state).removeAttr('hidden');
if (dataPartner.cooperative_state == "suspended") {
if (dataPartner.cooperative_state == "suspended") {
// 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);
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()) {
$('#no_delay').removeAttr('hidden');
if (date_end_alert < new Date()) {
$('#no_delay').removeAttr('hidden');
} else {
$('#delay').removeAttr('hidden');
}
} else if (dataPartner.cooperative_state == "unsubscribed") {
$('#unsubscribed').show();
} else if (dataPartner.cooperative_state == "exempted") {
$('#exempted').show();
} else {
$('#delay').removeAttr('hidden');
$('body').append('Merci de prendre contact avec le Bureau des membres pour examiner votre situation.');
}
} else if (dataPartner.cooperative_state == "unsubscribed") {
$('#unsubscribed').show()
} else if (dataPartner.cooperative_state == "exempted") {
$('#exempted').show()
} else {
$('body').append('Merci de prendre contact avec le Bureau des membres pour examiner votre situation.')
}
});
var myChart;
function get_ajax_data(product_id){
$.ajax({
type: 'GET',
url: 'get_list_sale_breaking/' + product_id,
dataType:"json",
timeout: 3000,
beforeSend: function () { },
complete: function () { },
success: function(data) {
myChart.data = data['data'];
myChart.update();
},
error: function() {
alert('Les données n\'ont pas pu être récupérées, réessayez plus tard.');
}
});
function get_ajax_data(product_id) {
$.ajax({
type: 'GET',
url: 'get_list_sale_breaking/' + product_id,
dataType:"json",
timeout: 3000,
beforeSend: function () { },
complete: function () { },
success: function(data) {
myChart.data = data['data'];
myChart.update();
},
error: function() {
alert('Les données n\'ont pas pu être récupérées, réessayez plus tard.');
}
});
}
var config = {
type: 'bar',
data: {},
options: {
type: 'bar',
data: {},
options: {
title: {
display: true,
text: 'Graph. des ventes'
display: true,
text: 'Graph. des ventes'
},
legend: { display: false }
}
};
}
};
window.onload = function() {
myChart = new Chart(document.getElementById("mixed-chart"), config);
}
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')
//$(this).find('.modal-content').load('remote' + index + '.html')
get_ajax_data(index);
})
})
var button = $(e.relatedTarget);
var index = button.data('remote');
//$(this).find('.modal-content').load('remote' + index + '.html')
get_ajax_data(index);
});
});
/* Page de la commande:
* Creation d'un nouvelle commande d'un fournisseur.
/* Page de la commande:
* Creation d'un nouvelle commande d'un fournisseur.
* Liste des articles d'un fournisseur (Recherche des fournisseurs avec un prés saisi)
* Sur un article on a les stocks, la moyenne des ventes des 4 dernière semaines en incluant les rupture
* Visualisation par un graph des vente des 4 dernier semaines
* Pré-saisie des qantitee à commander en fonction du stock, des moyennes de vente, d'un coef multi et la date de la prochaine commande
*
*
* */
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();
}
// Initialise le table des articles
$(document).ready(function() {
table_article = $('#tableArticle').DataTable( {
"ajax": {
table_article = $('#tableArticle').DataTable({
"ajax": {
"url": "get_list_article_fournisseur/1712/",
"data": ""
},
"columns":[
{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%"},
],
"searching": false,
"order": [[ 0, "desc" ]],
"iDisplayLength": 25,
"language": {
"emptyTable": "Pas de donnée",
"info": "Affiché : lignes _START_ à _END_ sur _TOTAL_",
"infoEmpty": "Affiché : 0 ligne",
"infoFiltered": "(filtré de _MAX_ lignes au total)",
"thousands": ",",
"lengthMenu": "Afficher _MENU_ lignes",
"loadingRecords": "Loading...",
"processing": "Processing...",
//"search": "Rechercher un article :",
//"searchPlaceholder": "Référence, nom du fournisseur...",
"zeroRecords": "Aucun résultat",
"paginate": {
"first": "Premier",
"last": "Dernier",
"next": "Suivant",
"previous": "Precedant"
"data": ""
},
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
"columns":[
{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%"}
],
"searching": false,
"order": [
[
0,
"desc"
]
],
"iDisplayLength": 25,
"language": {
"emptyTable": "Pas de donnée",
"info": "Affiché : lignes _START_ à _END_ sur _TOTAL_",
"infoEmpty": "Affiché : 0 ligne",
"infoFiltered": "(filtré de _MAX_ lignes au total)",
"thousands": ",",
"lengthMenu": "Afficher _MENU_ lignes",
"loadingRecords": "Loading...",
"processing": "Processing...",
//"search": "Rechercher un article :",
//"searchPlaceholder": "Référence, nom du fournisseur...",
"zeroRecords": "Aucun résultat",
"paginate": {
"first": "Premier",
"last": "Dernier",
"next": "Suivant",
"previous": "Precedant"
},
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
}
}
}
});
});
});
/* Listener */
/* Listener */
$(document).on('click','#dp_Search',function(){search_table_article();});
$(document).on('click', '#dp_Search', function() {
search_table_article();
});
//barcode-reader
$(document).ready(function() {
var pressed = false;
var chars = [];
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;
search_article_byBarcode();
}
}
},300);
}, 300);
}
pressed = true;
});
});
$(document).ready(function() {
csrftoken = getCookie('csrftoken');
csrftoken = getCookie('csrftoken');
});
// 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 } });
$.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } });
$.ajax({
type: "PUT",
url: "set_rupture" ,
//dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jIdArcticle),
success: function(data) {
document.location.href = "/stock";
},
error: function(resultat, statut, erreur) {
alert('Erreur' + erreur);
}
type: "PUT",
url: "set_rupture",
//dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jIdArcticle),
success: function(data) {
document.location.href = "/stock";
},
error: function(resultat, statut, erreur) {
alert('Erreur' + erreur);
}
});
}
}
var selArctileData;
......@@ -139,23 +148,22 @@ $(document).ready(function() {
var options = {
url : "get_liste_supplyer",
list: {
maxNumberOfElements: 8,
match: {
enabled: true
},
sort: {
enabled: true
},
onSelectItemEvent: function() {
four_id = $("#template-custom").getSelectedItemData().id;
}
maxNumberOfElements: 8,
match: {
enabled: true
},
sort: {
enabled: true
},
onSelectItemEvent: 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;
//}
......
/* Module de rupture : Selection un article et le met en rupture à 0 dans les stockes:
*
*
* Ecran de rechreche d'un article sur le nom et sur le code barre */
var table_article;
var dataSet =[] ;
var dataSet =[];
var csrftoken;
// lance la recherche sur le nom des l'article
function search_table_article(){
table_article.ajax.url('get_list_article?rech='+$("#searchInput").val()).load();
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( {
"ajax": {
table_article = $('#tableArticle').DataTable({
"ajax": {
"url": "get_list_article?rech=",
"data": ""
},
"columns":[
{
data:"image_small",
"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>"
return debut + "<img src='data:image/png;base64," + data + "'>" + fin;
}
},
{data:"name", "title":"Article","width": "50%"},
{data:"qty_available", "title":"En Stock", "width": "10%"},
{data:"uom_id",
"render":function (data, type, row){
"columns":[
{
data:"image_small",
"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>";
return data[1];
return debut + "<img src='data:image/png;base64," + data + "'>" + fin;
}
},
{data:"name", "title":"Article", "width": "50%"},
{data:"qty_available", "title":"En Stock", "width": "10%"},
{data:"uom_id",
"render":function (data, type, row) {
return data[1];
},
"title":"Unité","width":"5%"},
{data:"reception_status",
"title":"Rupture", "className":"dt-body-center",
"render": function (data, type, full, meta) {
if (full.qty_available > 0 ) {
return "<div><button id='bt_change' href='#'>Rupture</button></div>";
} else{
return "<div>--</div>";
"title":"Unité", "width":"5%"},
{data:"reception_status",
"title":"Rupture", "className":"dt-body-center",
"render": function (data, type, full, meta) {
if (full.qty_available > 0) {
return "<div><button id='bt_change' href='#'>Rupture</button></div>";
} else {
return "<div>--</div>";
}
}
}
],
"searching": false,
"order": [
[
0,
"desc"
]
],
"iDisplayLength": 25,
"language": {
"emptyTable": "Pas de donnée",
"info": "Affiché : lignes _START_ à _END_ sur _TOTAL_",
"infoEmpty": "Affiché : 0 ligne",
"infoFiltered": "(filtré de _MAX_ lignes au total)",
"thousands": ",",
"lengthMenu": "Afficher _MENU_ lignes",
"loadingRecords": "Loading...",
"processing": "Processing...",
//"search": "Rechercher un article :",
//"searchPlaceholder": "Référence, nom du fournisseur...",
"zeroRecords": "Aucun résultat",
"paginate": {
"first": "Premier",
"last": "Dernier",
"next": "Suivant",
"previous": "Precedant"
},
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
}
}
}
],
"searching": false,
"order": [[ 0, "desc" ]],
"iDisplayLength": 25,
"language": {
"emptyTable": "Pas de donnée",
"info": "Affiché : lignes _START_ à _END_ sur _TOTAL_",
"infoEmpty": "Affiché : 0 ligne",
"infoFiltered": "(filtré de _MAX_ lignes au total)",
"thousands": ",",
"lengthMenu": "Afficher _MENU_ lignes",
"loadingRecords": "Loading...",
"processing": "Processing...",
//"search": "Rechercher un article :",
//"searchPlaceholder": "Référence, nom du fournisseur...",
"zeroRecords": "Aucun résultat",
"paginate": {
"first": "Premier",
"last": "Dernier",
"next": "Suivant",
"previous": "Precedant"
},
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
}
}
});
});
});
/* Listener */
/* Listener */
$(document).on('click','#dp_Search',function(){search_table_article();});
$(document).on('click', '#dp_Search', function() {
search_table_article();
});
//barcode-reader
$(document).ready(function() {
var pressed = false;
var chars = [];
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;
search_article_byBarcode();
}
}
},300);
}, 300);
}
pressed = true;
});
});
$(document).ready(function() {
csrftoken = getCookie('csrftoken');
csrftoken = getCookie('csrftoken');
});
// 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 } });
$.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } });
$.ajax({
type: "PUT",
url: "set_rupture" ,
//dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jIdArcticle),
success: function(data) {
document.location.href = "/stock/listArticleBreaking";
},
error: function(resultat, statut, erreur) {
alert('Erreur' + erreur);
}
type: "PUT",
url: "set_rupture",
//dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jIdArcticle),
success: function(data) {
document.location.href = "/stock/listArticleBreaking";
},
error: function(resultat, statut, erreur) {
alert('Erreur' + erreur);
}
});
}
}
var selArctileData;
// Fenetre de validation sur l'article
// Fenetre de validation sur l'article
$(document).on('click', 'button#bt_change', function () {
var row = table_article.row($(this).parents('tr'));
......@@ -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 - ");
} );
});
/* Module de rupture : Selection un article et le met en rupture à 0 dans les stockes:
*
*
* Ecran de rechreche d'un article sur le nom et sur le code barre */
// Initialise le table des articles
$(document).ready(function() {
table_article = $('#tableArticle').DataTable( {
"ajax": {
table_article = $('#tableArticle').DataTable({
"ajax": {
"url": "get_saleWitheNotSale",
"data": ""
},
"columns":[
{data:"name", "title":"Article","width": "50%"},
{data:"qty", "title":"Qt. en vendu", "width":"15%"
},
{data:"daySale", "title":"Jours de vente", "width":"15%"
}
],
"searching": true,
"order": [[ 2, "desc" ]],
"iDisplayLength": 50,
"language": {
"emptyTable": "Pas de donnée",
"info": "Affiché : lignes _START_ à _END_ sur _TOTAL_",
"infoEmpty": "Affiché : 0 ligne",
"infoFiltered": "(filtré de _MAX_ lignes au total)",
"thousands": ",",
"lengthMenu": "Afficher _MENU_ lignes",
"loadingRecords": "Loading...",
"processing": "Processing...",
"search": "Rechercher un article :",
"searchPlaceholder": "Référence, nom du fournisseur...",
"zeroRecords": "Aucun résultat",
"paginate": {
"first": "Premier",
"last": "Dernier",
"next": "Suivant",
"previous": "Precedant"
},
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
"columns":[
{data:"name", "title":"Article", "width": "50%"},
{data:"qty", "title":"Qt. en vendu", "width":"15%"
},
{data:"daySale", "title":"Jours de vente", "width":"15%"
}
],
"searching": true,
"order": [
[
2,
"desc"
]
],
"iDisplayLength": 50,
"language": {
"emptyTable": "Pas de donnée",
"info": "Affiché : lignes _START_ à _END_ sur _TOTAL_",
"infoEmpty": "Affiché : 0 ligne",
"infoFiltered": "(filtré de _MAX_ lignes au total)",
"thousands": ",",
"lengthMenu": "Afficher _MENU_ lignes",
"loadingRecords": "Loading...",
"processing": "Processing...",
"search": "Rechercher un article :",
"searchPlaceholder": "Référence, nom du fournisseur...",
"zeroRecords": "Aucun résultat",
"paginate": {
"first": "Premier",
"last": "Dernier",
"next": "Suivant",
"previous": "Precedant"
},
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
}
}
}
});
});
});
/* Listener */
/* Listener */
$(document).on('click','#dp_Search',function(){search_table_article();});
$(document).on('click', '#dp_Search', function() {
search_table_article();
});
var csrftoken;
$(document).ready(function() {
csrftoken = getCookie('csrftoken');
csrftoken = getCookie('csrftoken');
});
// 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){
$.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } });
}
function actionButton (vUrl, jIdArcticle, followPage) {
$.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } });
$.ajax({
type: "PUT",
url: vUrl ,
//dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jIdArcticle),
success: function(data) {
document.location.href = followPage;
},
error: function(resultat, statut, erreur) {
alert('Erreur' + erreur);
}
type: "PUT",
url: vUrl,
//dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jIdArcticle),
success: function(data) {
document.location.href = followPage;
},
error: function(resultat, statut, erreur) {
alert('Erreur' + erreur);
}
});
}
var selArctileData;
// Fenetre de validation sur l'article
// Fenetre de validation sur l'article
$(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 () {
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 ;
openModal(html, dontPurchase, " - Ok - ");
this.checked = true
}else{
this.checked = false
});
$(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.stockqt+ ' - '+data.uom_id + '</div></div>';
selArctileData = data;
openModal(html, dontPurchase, " - Ok - ");
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)
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)
}
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'})
for (attr in changed) {
if (attr != 'name')
original[attr] = changed[attr]
}
alert('Modifications enregistrées !')
save_btn.removeClass('btn--primary');
save_btn.css({'cursor':'default'});
for (attr in changed) {
if (attr != 'name')
original[attr] = changed[attr];
}
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