Unverified Commit c2889195 by Paul B

[AUTO] apply automatic fixes from eslint rules

parent 5753246a
var shelfs_table = null var shelfs_table = null;
function init_datatable() { function init_datatable() {
return $('#lists').DataTable( { return $('#lists').DataTable({
data: lists, // data passed at page loading data: lists, // data passed at page loading
rowId: 'id', rowId: 'id',
columns:[ columns:[
{data: "id", title:"id", "visible": false}, {data: "id", title:"id", "visible": false},
{ {
data:"datetime_created", data:"datetime_created",
title:"Liste", title:"Liste",
render: function (data, type, full, meta) { render: function (data, type, full, meta) {
return "Liste du " + data return "Liste du " + data;
} }
}, },
{data:"p_nb", title:"Nombre de réfs", width: "10%", className:"dt-body-center"}, {data:"p_nb", title:"Nombre de réfs", width: "10%", className:"dt-body-center"},
{ {
data:"inventory_status", data:"inventory_status",
title:"Inventaire à faire", title:"Inventaire à faire",
className:"dt-body-center", className:"dt-body-center",
width: "15%", width: "15%",
render: function (data, type, full, meta) { render: function (data, type, full, meta) {
if (data == '') if (data == '')
return "<button class='btn--primary do_inventory'>Inventaire en rayon</button>" return "<button class='btn--primary do_inventory'>Inventaire en rayon</button>";
else else
return "<button class='btn--success do_inventory'>Inventaire en réserve</button>" return "<button class='btn--success do_inventory'>Inventaire en réserve</button>";
} }
} }
], ],
dom: 'rtip', dom: 'rtip',
order: [[ 1, "asc" ]], order: [
iDisplayLength: 25, [
language: {url : '/static/js/datatables/french.json'} 1,
}) "asc"
} ]
],
iDisplayLength: 25,
function go_to_inventory() { language: {url : '/static/js/datatables/french.json'}
openModal() });
}
var clicked = $(this)
var row_data = shelfs_table.row(clicked.parents('tr')).data()
function go_to_inventory() {
// Use local storage to pass data to next page openModal();
if (Modernizr.localstorage) {
var stored_list = JSON.parse(localStorage.getItem('custom_list_' + row_data.id)) var clicked = $(this);
var row_data = shelfs_table.row(clicked.parents('tr')).data();
// Set local storage if key doesn't exist
if (stored_list == null) { // Use local storage to pass data to next page
localStorage.setItem("custom_list_" + row_data.id , JSON.stringify(row_data)) if (Modernizr.localstorage) {
} var stored_list = JSON.parse(localStorage.getItem('custom_list_' + row_data.id));
}
// Set local storage if key doesn't exist
document.location.href = "custom_list_inventory/" + row_data.id if (stored_list == null) {
} localStorage.setItem("custom_list_" + row_data.id, JSON.stringify(row_data));
}
$(document).ready(function() { }
console.log(lists)
shelfs_table = init_datatable() document.location.href = "custom_list_inventory/" + row_data.id;
}
$(document).on('click', 'button.do_inventory', go_to_inventory)
}) $(document).ready(function() {
console.log(lists);
shelfs_table = init_datatable();
$(document).on('click', 'button.do_inventory', go_to_inventory);
});
var coop_page = $('#coop_page'); var coop_page = $('#coop_page');
function show_checks_nb() { function show_checks_nb() {
$('#coop_validation_form').find('[name="checks_nb"]').show(); $('#coop_validation_form').find('[name="checks_nb"]')
$('#coop_validation_form').find('[id="checks_nb_label"]').show(); .show();
$('#coop_validation_form').find('[id="checks_nb_label"]')
.show();
} }
function hide_checks_nb() { function hide_checks_nb() {
$('#coop_validation_form').find('[name="checks_nb"]').hide(); $('#coop_validation_form').find('[name="checks_nb"]')
$('#coop_validation_form').find('[name="checks_nb"]').val(0); .hide();
$('#coop_validation_form').find('[id="checks_nb_label"]').hide(); $('#coop_validation_form').find('[name="checks_nb"]')
.val(0);
$('#coop_validation_form').find('[id="checks_nb_label"]')
.hide();
} }
function open_shift_choice() { function open_shift_choice() {
schoice_view.show(); schoice_view.show();
coop_page.hide(); coop_page.hide();
retrieve_and_draw_shift_tempates(); retrieve_and_draw_shift_tempates();
} }
function display_current_coop_form() { function display_current_coop_form() {
let form = $('#coop_validation_form'), let form = $('#coop_validation_form'),
chgt_shift_btn = $('#change_shift_template'); chgt_shift_btn = $('#change_shift_template');
var ftop_shift = $('#choosen_shift [name="ftop"]'), var ftop_shift = $('#choosen_shift [name="ftop"]'),
m_barcode = form.find('[name="m_barcode"]'), m_barcode = form.find('[name="m_barcode"]'),
sex = $('#sex') sex = $('#sex');
let street2_input = form.find('[name="street2"]'), let street2_input = form.find('[name="street2"]'),
phone_input = form.find('[name="phone"]') phone_input = form.find('[name="phone"]');
chgt_shift_btn.hide();
chgt_shift_btn.off('click',open_shift_choice); chgt_shift_btn.hide();
form.find('[name="firstname"]').val(current_coop.firstname); chgt_shift_btn.off('click', open_shift_choice);
form.find('[name="lastname"]').val(current_coop.lastname); 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) 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") { //console.log(current_coop)
$("#" + current_coop.sex + "_sex").prop('checked', true) 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); // form.find('[name="barcode_base"]').val(current_coop.barcode_base);
if (current_coop.shift_template && form.find('[name="email"]').val(current_coop._id);
if (current_coop.shift_template &&
current_coop.shift_template.data.type == 2) { current_coop.shift_template.data.type == 2) {
$('#choosen_shift input').hide(); $('#choosen_shift input').hide();
ftop_shift.val('Volant'); ftop_shift.val('Volant');
ftop_shift.show(); ftop_shift.show();
} else { } else {
// Bien laisser dans cet ordre // Bien laisser dans cet ordre
$('#choosen_shift input').show(); $('#choosen_shift input').show();
ftop_shift.hide(); ftop_shift.hide();
} }
form.find('[name="birthdate"]').val(current_coop.birthdate || ''); form.find('[name="birthdate"]').val(current_coop.birthdate || '');
form.find('[name="address"]').val(current_coop.address || ''); form.find('[name="address"]').val(current_coop.address || '');
form.find('[name="city"]').val(current_coop.city || ''); form.find('[name="city"]').val(current_coop.city || '');
form.find('[name="zip"]').val(current_coop.zip || ''); form.find('[name="zip"]').val(current_coop.zip || '');
form.find('[name="country"]').val(current_coop.country || 'France'); form.find('[name="country"]').val(current_coop.country || 'France');
form.find('[name="mobile"]').val(current_coop.mobile || ''); form.find('[name="mobile"]').val(current_coop.mobile || '');
form.find('[name="shares_nb"]').val(current_coop.shares_nb || ''); form.find('[name="shares_nb"]').val(current_coop.shares_nb || '');
form.find('[name="shares_euros"]').val(current_coop.shares_euros || ''); form.find('[name="shares_euros"]').val(current_coop.shares_euros || '');
form.find('[name="payment_meaning"]').val(current_coop.payment_meaning || ''); form.find('[name="payment_meaning"]').val(current_coop.payment_meaning || '');
form.find('[name="checks_nb"]').val(current_coop.checks_nb || 0); form.find('[name="checks_nb"]').val(current_coop.checks_nb || 0);
if (street2_input.length > 0) { if (street2_input.length > 0) {
street2_input.val(current_coop.street2 || '') street2_input.val(current_coop.street2 || '');
}
if (phone_input.length > 0) {
phone_input.val(current_coop.phone || '')
}
// 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>');
}
} }
} if (phone_input.length > 0) {
phone_input.val(current_coop.phone || '');
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); // Checks
if (current_coop.coop_msg) { form.find('[name="checks_nb"]').hide();
show_change_shift = true; 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) { var show_change_shift = false;
chgt_shift_btn.show();
chgt_shift_btn.on('click',open_shift_choice); 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(){ $('#payment_meaning').change(function() {
if ($(this).val() == 'ch'){ if ($(this).val() == 'ch') {
show_checks_nb() show_checks_nb();
} else { } else {
hide_checks_nb() hide_checks_nb();
} }
}); });
...@@ -7,24 +7,24 @@ let vform = $('#coop_validation_form'), ...@@ -7,24 +7,24 @@ let vform = $('#coop_validation_form'),
wform.hide(); 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 !!! // Setting required to fields doesn't prevent submit with empty fields anymore !!!
// TODO : Find out why // TODO : Find out why
if (street2.length > 0) street2.get(0).removeAttribute('required') if (street2.length > 0) street2.get(0).removeAttribute('required');
if (phone.length > 0) phone.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_nb"]').attr('disabled', 'disabled');
vform.find('[name="shares_euros"]').attr('disabled','disabled'); vform.find('[name="shares_euros"]').attr('disabled', 'disabled');
vform.find('[name="checks_nb"]').attr('disabled','disabled'); vform.find('[name="checks_nb"]').attr('disabled', 'disabled');
vform.find('[name="country"]').attr('disabled','disabled'); vform.find('[name="country"]').attr('disabled', 'disabled');
vform.find('[name="email"]').attr('disabled','disabled'); vform.find('[name="email"]').attr('disabled', 'disabled');
if (m_barcode.length > 0) { if (m_barcode.length > 0) {
m_barcode.attr('disabled','disabled') m_barcode.attr('disabled', 'disabled');
} }
function show_warning_form(){ function show_warning_form() {
vform.hide(); vform.hide();
wform.show(); wform.show();
} }
function show_coop_form() { function show_coop_form() {
...@@ -36,79 +36,98 @@ function show_coop_form() { ...@@ -36,79 +36,98 @@ function show_coop_form() {
function process_form_submission(event){ function process_form_submission(event) {
event.preventDefault(); event.preventDefault();
var clicked = $(this), var clicked = $(this),
fname = clicked.attr('name'); fname = clicked.attr('name');
if (fname == 'valider'){
var form_data = new FormData(vform.get(0)), if (fname == 'valider') {
has_empty_values = false; var form_data = new FormData(vform.get(0)),
if (sex.length > 0) { has_empty_values = false;
if (sex.length > 0) {
//value attrribute is emptied when form is loaded !! //value attrribute is emptied when form is loaded !!
//so, we have to retrive sex value using unusual way //so, we have to retrive sex value using unusual way
form_data.set('sex', form_data.set(
$('input[name="sex"]:checked').attr('id').replace('_sex','')) '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)
} }
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é ! "; var msg = "Vous êtes maintenant enregistré ! ";
msg += "<a href='" + em_url + "'>Cliquez ici</a> "; msg += "<a href='" + em_url + "'>Cliquez ici</a> ";
msg += "pour découvrir l'espace membre"; msg += "pour découvrir l'espace membre";
$('p.intro').remove(); $('p.intro').remove();
vform.remove(); vform.remove();
display_msg_box(msg); display_msg_box(msg);
} }
}); }
} );
}
} else if (fname =='warning') { } else if (fname =='warning') {
var msg = $('textarea[name="message"]').val(); var msg = $('textarea[name="message"]').val();
var data = {'odoo_id': current_coop.odoo_id, var data = {'odoo_id': current_coop.odoo_id,
'msg': msg,'_rev': current_coop._rev,'_id': current_coop._id}; 'msg': msg, '_rev': current_coop._rev, '_id': current_coop._id};
openModal()
post_form('/members/coop_warning_msg',data, openModal();
function(err,result){ post_form(
closeModal(); '/members/coop_warning_msg', data,
if (!err) { function(err, result) {
$('#main_content').remove() closeModal();
display_msg_box('Message enregistré ! Le bureau des membres est averti.'); if (!err) {
} $('#main_content').remove();
display_msg_box('Message enregistré ! Le bureau des membres est averti.');
}); }
}
);
} }
} }
...@@ -116,8 +135,9 @@ try { ...@@ -116,8 +135,9 @@ try {
current_coop = coop; current_coop = coop;
display_current_coop_form(); display_current_coop_form();
var w_msg = current_coop.coop_msg || ''; var w_msg = current_coop.coop_msg || '';
wform.find('textarea').val(w_msg); wform.find('textarea').val(w_msg);
} catch(e) { } catch (e) {
console.log(e); console.log(e);
} }
......
...@@ -5,10 +5,12 @@ ...@@ -5,10 +5,12 @@
init: function(id) { init: function(id) {
var box = document.getElementById(id); var box = document.getElementById(id);
var node; var node;
SelectBox.cache[id] = []; SelectBox.cache[id] = [];
var cache = SelectBox.cache[id]; var cache = SelectBox.cache[id];
var boxOptions = box.options; var boxOptions = box.options;
var boxOptionsLength = boxOptions.length; var boxOptionsLength = boxOptions.length;
for (var i = 0, j = boxOptionsLength; i < j; i++) { for (var i = 0, j = boxOptionsLength; i < j; i++) {
node = boxOptions[i]; node = boxOptions[i];
cache.push({value: node.value, text: node.text, displayed: 1}); cache.push({value: node.value, text: node.text, displayed: 1});
...@@ -18,14 +20,17 @@ ...@@ -18,14 +20,17 @@
// Repopulate HTML select box from cache // Repopulate HTML select box from cache
var box = document.getElementById(id); var box = document.getElementById(id);
var node; var node;
$(box).empty(); // clear all options $(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]; var cache = SelectBox.cache[id];
for (var i = 0, j = cache.length; i < j; i++) { for (var i = 0, j = cache.length; i < j; i++) {
node = cache[i]; node = cache[i];
if (node.displayed) { if (node.displayed) {
var new_option = new Option(node.text, node.value, false, false); var new_option = new Option(node.text, node.value, false, false);
// Shows a tooltip when hovering over the option // Shows a tooltip when hovering over the option
new_option.setAttribute("title", node.text); new_option.setAttribute("title", node.text);
new_options += new_option.outerHTML; new_options += new_option.outerHTML;
} }
...@@ -39,16 +44,18 @@ ...@@ -39,16 +44,18 @@
var tokens = text.toLowerCase().split(/\s+/); var tokens = text.toLowerCase().split(/\s+/);
var node, token; var node, token;
var cache = SelectBox.cache[id]; var cache = SelectBox.cache[id];
for (var i = 0, j = cache.length; i < j; i++) { for (var i = 0, j = cache.length; i < j; i++) {
node = cache[i]; node = cache[i];
node.displayed = 1; node.displayed = 1;
var node_text = node.text.toLowerCase(); var node_text = node.text.toLowerCase();
var numTokens = tokens.length; var numTokens = tokens.length;
for (var k = 0; k < numTokens; k++) { for (var k = 0; k < numTokens; k++) {
token = tokens[k]; token = tokens[k];
if (node_text.indexOf(token) === -1) { if (node_text.indexOf(token) === -1) {
node.displayed = 0; 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 @@ ...@@ -57,6 +64,7 @@
delete_from_cache: function(id, value) { delete_from_cache: function(id, value) {
var node, delete_index = null; var node, delete_index = null;
var cache = SelectBox.cache[id]; var cache = SelectBox.cache[id];
for (var i = 0, j = cache.length; i < j; i++) { for (var i = 0, j = cache.length; i < j; i++) {
node = cache[i]; node = cache[i];
if (node.value === value) { if (node.value === value) {
...@@ -73,12 +81,14 @@ ...@@ -73,12 +81,14 @@
// Check if an item is contained in the cache // Check if an item is contained in the cache
var node; var node;
var cache = SelectBox.cache[id]; var cache = SelectBox.cache[id];
for (var i = 0, j = cache.length; i < j; i++) { for (var i = 0, j = cache.length; i < j; i++) {
node = cache[i]; node = cache[i];
if (node.value === value) { if (node.value === value) {
return true; return true;
} }
} }
return false; return false;
}, },
move: function(from, to) { move: function(from, to) {
...@@ -86,9 +96,11 @@ ...@@ -86,9 +96,11 @@
var option; var option;
var boxOptions = from_box.options; var boxOptions = from_box.options;
var boxOptionsLength = boxOptions.length; var boxOptionsLength = boxOptions.length;
for (var i = 0, j = boxOptionsLength; i < j; i++) { for (var i = 0, j = boxOptionsLength; i < j; i++) {
option = boxOptions[i]; option = boxOptions[i];
var option_value = option.value; var option_value = option.value;
if (option.selected && SelectBox.cache_contains(from, 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.add_to_cache(to, {value: option_value, text: option.text, displayed: 1});
SelectBox.delete_from_cache(from, option_value); SelectBox.delete_from_cache(from, option_value);
...@@ -102,9 +114,11 @@ ...@@ -102,9 +114,11 @@
var option; var option;
var boxOptions = from_box.options; var boxOptions = from_box.options;
var boxOptionsLength = boxOptions.length; var boxOptionsLength = boxOptions.length;
for (var i = 0, j = boxOptionsLength; i < j; i++) { for (var i = 0, j = boxOptionsLength; i < j; i++) {
option = boxOptions[i]; option = boxOptions[i];
var option_value = option.value; var option_value = option.value;
if (SelectBox.cache_contains(from, option_value)) { if (SelectBox.cache_contains(from, option_value)) {
SelectBox.add_to_cache(to, {value: option_value, text: option.text, displayed: 1}); SelectBox.add_to_cache(to, {value: option_value, text: option.text, displayed: 1});
SelectBox.delete_from_cache(from, option_value); SelectBox.delete_from_cache(from, option_value);
...@@ -124,21 +138,23 @@ ...@@ -124,21 +138,23 @@
if (a < b) { if (a < b) {
return -1; return -1;
} }
} } catch (e) {
catch (e) {
// silently fail on IE 'unknown' exception // silently fail on IE 'unknown' exception
} }
return 0; return 0;
} ); });
}, },
select_all: function(id) { select_all: function(id) {
var box = document.getElementById(id); var box = document.getElementById(id);
var boxOptions = box.options; var boxOptions = box.options;
var boxOptionsLength = boxOptions.length; var boxOptionsLength = boxOptions.length;
for (var i = 0; i < boxOptionsLength; i++) { for (var i = 0; i < boxOptionsLength; i++) {
boxOptions[i].selected = 'selected'; boxOptions[i].selected = 'selected';
} }
} }
}; };
window.SelectBox = SelectBox; window.SelectBox = SelectBox;
})(django.jQuery); })(django.jQuery);
...@@ -11,6 +11,7 @@ Requires jQuery, core.js, and SelectBox.js. ...@@ -11,6 +11,7 @@ Requires jQuery, core.js, and SelectBox.js.
if (node.tagName.toLowerCase() !== 'form') { if (node.tagName.toLowerCase() !== 'form') {
return findForm(node.parentNode); return findForm(node.parentNode);
} }
return node; return node;
} }
...@@ -21,10 +22,12 @@ Requires jQuery, core.js, and SelectBox.js. ...@@ -21,10 +22,12 @@ Requires jQuery, core.js, and SelectBox.js.
return; return;
} }
var from_box = document.getElementById(field_id); var from_box = document.getElementById(field_id);
from_box.id += '_from'; // change its ID from_box.id += '_from'; // change its ID
from_box.className = 'filtered'; from_box.className = 'filtered';
var ps = from_box.parentNode.getElementsByTagName('p'); var ps = from_box.parentNode.getElementsByTagName('p');
for (var i = 0; i < ps.length; i++) { for (var i = 0; i < ps.length; i++) {
if (ps[i].className.indexOf("info") !== -1) { if (ps[i].className.indexOf("info") !== -1) {
// Remove <p class="info">, because it just gets in the way. // Remove <p class="info">, because it just gets in the way.
...@@ -39,26 +42,28 @@ Requires jQuery, core.js, and SelectBox.js. ...@@ -39,26 +42,28 @@ Requires jQuery, core.js, and SelectBox.js.
// <div class="selector"> or <div class="selector stacked"> // <div class="selector"> or <div class="selector stacked">
var selector_div = quickElement('div', from_box.parentNode); var selector_div = quickElement('div', from_box.parentNode);
selector_div.className = is_stacked ? 'selector stacked' : 'selector'; selector_div.className = is_stacked ? 'selector stacked' : 'selector';
// <div class="selector-available"> // <div class="selector-available">
var selector_available = quickElement('div', selector_div); var selector_available = quickElement('div', selector_div);
selector_available.className = 'selector-available'; selector_available.className = 'selector-available';
var title_available = quickElement('h2', selector_available, interpolate(gettext('Available %s') + ' ', [field_name])); var title_available = quickElement('h2', selector_available, interpolate(gettext('Available %s') + ' ', [field_name]));
quickElement( quickElement(
'span', title_available, '', 'span', title_available, '',
'class', 'help help-tooltip help-icon', 'class', 'help help-tooltip help-icon',
'title', interpolate( 'title', interpolate(
gettext( gettext('This is the list of available %s. You may choose some by ' +
'This is the list of available %s. You may choose some by ' +
'selecting them in the box below and then clicking the ' + 'selecting them in the box below and then clicking the ' +
'"Choose" arrow between the two boxes.' '"Choose" arrow between the two boxes.'),
),
[field_name] [field_name]
) )
); );
var filter_p = quickElement('p', selector_available, '', 'id', field_id + '_filter'); var filter_p = quickElement('p', selector_available, '', 'id', field_id + '_filter');
filter_p.className = 'selector-filter'; filter_p.className = 'selector-filter';
var search_filter_label = quickElement('label', filter_p, '', 'for', field_id + '_input'); var search_filter_label = quickElement('label', filter_p, '', 'for', field_id + '_input');
...@@ -72,40 +77,47 @@ Requires jQuery, core.js, and SelectBox.js. ...@@ -72,40 +77,47 @@ Requires jQuery, core.js, and SelectBox.js.
filter_p.appendChild(document.createTextNode(' ')); filter_p.appendChild(document.createTextNode(' '));
var filter_input = quickElement('input', filter_p, '', 'type', 'text', 'placeholder', gettext("Filter")); var filter_input = quickElement('input', filter_p, '', 'type', 'text', 'placeholder', gettext("Filter"));
filter_input.id = field_id + '_input'; filter_input.id = field_id + '_input';
selector_available.appendChild(from_box); 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'); 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'; choose_all.className = 'selector-chooseall';
// <ul class="selector-chooser"> // <ul class="selector-chooser">
var selector_chooser = quickElement('ul', selector_div); var selector_chooser = quickElement('ul', selector_div);
selector_chooser.className = 'selector-chooser'; 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'); 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'; 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'); 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'; remove_link.className = 'selector-remove';
// <div class="selector-chosen"> // <div class="selector-chosen">
var selector_chosen = quickElement('div', selector_div); var selector_chosen = quickElement('div', selector_div);
selector_chosen.className = 'selector-chosen'; selector_chosen.className = 'selector-chosen';
var title_chosen = quickElement('h2', selector_chosen, interpolate(gettext('Chosen %s') + ' ', [field_name])); var title_chosen = quickElement('h2', selector_chosen, interpolate(gettext('Chosen %s') + ' ', [field_name]));
quickElement( quickElement(
'span', title_chosen, '', 'span', title_chosen, '',
'class', 'help help-tooltip help-icon', 'class', 'help help-tooltip help-icon',
'title', interpolate( 'title', interpolate(
gettext( gettext('This is the list of chosen %s. You may remove some by ' +
'This is the list of chosen %s. You may remove some by ' +
'selecting them in the box below and then clicking the ' + 'selecting them in the box below and then clicking the ' +
'"Remove" arrow between the two boxes.' '"Remove" arrow between the two boxes.'),
),
[field_name] [field_name]
) )
); );
var to_box = quickElement('select', selector_chosen, '', 'id', field_id + '_to', 'multiple', 'multiple', 'size', from_box.size, 'name', from_box.getAttribute('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'; 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'); 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'; clear_all.className = 'selector-clearall';
from_box.setAttribute('name', from_box.getAttribute('name') + '_old'); from_box.setAttribute('name', from_box.getAttribute('name') + '_old');
...@@ -118,6 +130,7 @@ Requires jQuery, core.js, and SelectBox.js. ...@@ -118,6 +130,7 @@ Requires jQuery, core.js, and SelectBox.js.
} }
e.preventDefault(); e.preventDefault();
}; };
choose_all.addEventListener('click', function(e) { choose_all.addEventListener('click', function(e) {
move_selection(e, this, SelectBox.move_all, field_id + '_from', field_id + '_to'); move_selection(e, this, SelectBox.move_all, field_id + '_from', field_id + '_to');
}); });
...@@ -166,7 +179,10 @@ Requires jQuery, core.js, and SelectBox.js. ...@@ -166,7 +179,10 @@ Requires jQuery, core.js, and SelectBox.js.
// In horizontal mode, give the same height to the two boxes. // In horizontal mode, give the same height to the two boxes.
var j_from_box = $(from_box); var j_from_box = $(from_box);
var j_to_box = $(to_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) { if (j_from_box.outerHeight() > 0) {
resize_filters(); // This fieldset is already open. Resize now. resize_filters(); // This fieldset is already open. Resize now.
} else { } else {
...@@ -180,6 +196,7 @@ Requires jQuery, core.js, and SelectBox.js. ...@@ -180,6 +196,7 @@ Requires jQuery, core.js, and SelectBox.js.
}, },
any_selected: function(field) { any_selected: function(field) {
var any_selected = false; var any_selected = false;
try { try {
// Temporarily add the required attribute and check validity. // Temporarily add the required attribute and check validity.
// This is much faster in WebKit browsers than the fallback. // This is much faster in WebKit browsers than the fallback.
...@@ -190,12 +207,14 @@ Requires jQuery, core.js, and SelectBox.js. ...@@ -190,12 +207,14 @@ Requires jQuery, core.js, and SelectBox.js.
// Browsers that don't support :valid (IE < 10) // Browsers that don't support :valid (IE < 10)
any_selected = field.find('option:selected').length > 0; any_selected = field.find('option:selected').length > 0;
} }
return any_selected; return any_selected;
}, },
refresh_icons: function(field_id) { refresh_icons: function(field_id) {
var from = $('#' + field_id + '_from'); var from = $('#' + field_id + '_from');
var to = $('#' + field_id + '_to'); var to = $('#' + field_id + '_to');
// Active if at least one item is selected // Active if at least one item is selected
$('#' + field_id + '_add_link').toggleClass('active', SelectFilter.any_selected(from)); $('#' + field_id + '_add_link').toggleClass('active', SelectFilter.any_selected(from));
$('#' + field_id + '_remove_link').toggleClass('active', SelectFilter.any_selected(to)); $('#' + field_id + '_remove_link').toggleClass('active', SelectFilter.any_selected(to));
// Active if the corresponding box isn't empty // Active if the corresponding box isn't empty
...@@ -205,28 +224,35 @@ Requires jQuery, core.js, and SelectBox.js. ...@@ -205,28 +224,35 @@ Requires jQuery, core.js, and SelectBox.js.
filter_key_press: function(event, field_id) { filter_key_press: function(event, field_id) {
var from = document.getElementById(field_id + '_from'); var from = document.getElementById(field_id + '_from');
// don't submit form if user pressed Enter // don't submit form if user pressed Enter
if ((event.which && event.which === 13) || (event.keyCode && event.keyCode === 13)) { if ((event.which && event.which === 13) || (event.keyCode && event.keyCode === 13)) {
from.selectedIndex = 0; from.selectedIndex = 0;
SelectBox.move(field_id + '_from', field_id + '_to'); SelectBox.move(field_id + '_from', field_id + '_to');
from.selectedIndex = 0; from.selectedIndex = 0;
event.preventDefault(); event.preventDefault();
return false; return false;
} }
}, },
filter_key_up: function(event, field_id) { filter_key_up: function(event, field_id) {
var from = document.getElementById(field_id + '_from'); var from = document.getElementById(field_id + '_from');
var temp = from.selectedIndex; var temp = from.selectedIndex;
SelectBox.filter(field_id + '_from', document.getElementById(field_id + '_input').value); SelectBox.filter(field_id + '_from', document.getElementById(field_id + '_input').value);
from.selectedIndex = temp; from.selectedIndex = temp;
return true; return true;
}, },
filter_key_down: function(event, field_id) { filter_key_down: function(event, field_id) {
var from = document.getElementById(field_id + '_from'); var from = document.getElementById(field_id + '_from');
// right arrow -- move across // right arrow -- move across
if ((event.which && event.which === 39) || (event.keyCode && event.keyCode === 39)) { if ((event.which && event.which === 39) || (event.keyCode && event.keyCode === 39)) {
var old_index = from.selectedIndex; var old_index = from.selectedIndex;
SelectBox.move(field_id + '_from', field_id + '_to'); SelectBox.move(field_id + '_from', field_id + '_to');
from.selectedIndex = (old_index === from.length) ? from.length - 1 : old_index; from.selectedIndex = (old_index === from.length) ? from.length - 1 : old_index;
return false; return false;
} }
// down arrow -- wrap around // down arrow -- wrap around
...@@ -237,6 +263,7 @@ Requires jQuery, core.js, and SelectBox.js. ...@@ -237,6 +263,7 @@ Requires jQuery, core.js, and SelectBox.js.
if ((event.which && event.which === 38) || (event.keyCode && event.keyCode === 38)) { if ((event.which && event.which === 38) || (event.keyCode && event.keyCode === 38)) {
from.selectedIndex = (from.selectedIndex === 0) ? from.length - 1 : from.selectedIndex - 1; from.selectedIndex = (from.selectedIndex === 0) ? from.length - 1 : from.selectedIndex - 1;
} }
return true; return true;
} }
}; };
...@@ -245,6 +272,7 @@ Requires jQuery, core.js, and SelectBox.js. ...@@ -245,6 +272,7 @@ Requires jQuery, core.js, and SelectBox.js.
$('select.selectfilter, select.selectfilterstacked').each(function() { $('select.selectfilter, select.selectfilterstacked').each(function() {
var $el = $(this), var $el = $(this),
data = $el.data(); data = $el.data();
SelectFilter.init($el.attr('id'), data.fieldName, parseInt(data.isStacked, 10)); SelectFilter.init($el.attr('id'), data.fieldName, parseInt(data.isStacked, 10));
}); });
}); });
......
...@@ -8,73 +8,82 @@ ...@@ -8,73 +8,82 @@
var actionCheckboxes = $(this); var actionCheckboxes = $(this);
var list_editable_changed = false; var list_editable_changed = false;
var showQuestion = function() { var showQuestion = function() {
$(options.acrossClears).hide(); $(options.acrossClears).hide();
$(options.acrossQuestions).show(); $(options.acrossQuestions).show();
$(options.allContainer).hide(); $(options.allContainer).hide();
}, },
showClear = function() { showClear = function() {
$(options.acrossClears).show(); $(options.acrossClears).show();
$(options.acrossQuestions).hide(); $(options.acrossQuestions).hide();
$(options.actionContainer).toggleClass(options.selectedClass); $(options.actionContainer).toggleClass(options.selectedClass);
$(options.allContainer).show(); $(options.allContainer).show();
$(options.counterContainer).hide(); $(options.counterContainer).hide();
}, },
reset = function() { reset = function() {
$(options.acrossClears).hide(); $(options.acrossClears).hide();
$(options.acrossQuestions).hide(); $(options.acrossQuestions).hide();
$(options.allContainer).hide(); $(options.allContainer).hide();
$(options.counterContainer).show(); $(options.counterContainer).show();
}, },
clearAcross = function() { clearAcross = function() {
reset();
$(options.acrossInput).val(0);
$(options.actionContainer).removeClass(options.selectedClass);
},
checker = function(checked) {
if (checked) {
showQuestion();
} else {
reset(); reset();
} $(options.acrossInput).val(0);
$(actionCheckboxes).prop("checked", checked) $(options.actionContainer).removeClass(options.selectedClass);
.parent().parent().toggleClass(options.selectedClass, checked); },
}, checker = function(checked) {
updateCounter = function() { if (checked) {
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(); showQuestion();
} else { } else {
value = false; reset();
clearAcross();
} }
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 // Show counter by default
$(options.counterContainer).show(); $(options.counterContainer).show();
// Check state of checkboxes and reinit state if needed // Check state of checkboxes and reinit state if needed
$(this).filter(":checked").each(function(i) { $(this).filter(":checked")
$(this).parent().parent().toggleClass(options.selectedClass); .each(function(i) {
updateCounter(); $(this).parent()
if ($(options.acrossInput).val() === 1) { .parent()
showClear(); .toggleClass(options.selectedClass);
} updateCounter();
}); if ($(options.acrossInput).val() === 1) {
$(options.allToggle).show().click(function() { showClear();
checker($(this).prop("checked")); }
updateCounter(); });
}); $(options.allToggle).show()
.click(function() {
checker($(this).prop("checked"));
updateCounter();
});
$("a", options.acrossQuestions).click(function(event) { $("a", options.acrossQuestions).click(function(event) {
event.preventDefault(); event.preventDefault();
$(options.acrossInput).val(1); $(options.acrossInput).val(1);
...@@ -89,23 +98,33 @@ ...@@ -89,23 +98,33 @@
}); });
lastChecked = null; lastChecked = null;
$(actionCheckboxes).click(function(event) { $(actionCheckboxes).click(function(event) {
if (!event) { event = window.event; } if (!event) {
event = window.event;
}
var target = event.target ? event.target : event.srcElement; var target = event.target ? event.target : event.srcElement;
if (lastChecked && $.data(lastChecked) !== $.data(target) && event.shiftKey === true) { if (lastChecked && $.data(lastChecked) !== $.data(target) && event.shiftKey === true) {
var inrange = false; var inrange = false;
$(lastChecked).prop("checked", target.checked) $(lastChecked).prop("checked", target.checked)
.parent().parent().toggleClass(options.selectedClass, target.checked); .parent()
.parent()
.toggleClass(options.selectedClass, target.checked);
$(actionCheckboxes).each(function() { $(actionCheckboxes).each(function() {
if ($.data(this) === $.data(lastChecked) || $.data(this) === $.data(target)) { if ($.data(this) === $.data(lastChecked) || $.data(this) === $.data(target)) {
inrange = (inrange) ? false : true; inrange = (inrange) ? false : true;
} }
if (inrange) { if (inrange) {
$(this).prop("checked", target.checked) $(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; lastChecked = target;
updateCounter(); updateCounter();
}); });
...@@ -119,6 +138,7 @@ ...@@ -119,6 +138,7 @@
}); });
$('form#changelist-form input[name="_save"]').click(function(event) { $('form#changelist-form input[name="_save"]').click(function(event) {
var action_changed = false; var action_changed = false;
$('select option:selected', options.actionContainer).each(function() { $('select option:selected', options.actionContainer).each(function() {
if ($(this).val()) { if ($(this).val()) {
action_changed = true; action_changed = true;
...@@ -146,6 +166,7 @@ ...@@ -146,6 +166,7 @@
}; };
$(document).ready(function() { $(document).ready(function() {
var $actionsEls = $('tr input.action-select'); var $actionsEls = $('tr input.action-select');
if ($actionsEls.length > 0) { if ($actionsEls.length > 0) {
$actionsEls.actions(); $actionsEls.actions();
} }
......
...@@ -12,19 +12,23 @@ ...@@ -12,19 +12,23 @@
function id_to_windowname(text) { function id_to_windowname(text) {
text = text.replace(/\./g, '__dot__'); text = text.replace(/\./g, '__dot__');
text = text.replace(/\-/g, '__dash__'); text = text.replace(/\-/g, '__dash__');
return text; return text;
} }
function windowname_to_id(text) { function windowname_to_id(text) {
text = text.replace(/__dot__/g, '.'); text = text.replace(/__dot__/g, '.');
text = text.replace(/__dash__/g, '-'); text = text.replace(/__dash__/g, '-');
return text; return text;
} }
function showAdminPopup(triggeringLink, name_regexp, add_popup) { function showAdminPopup(triggeringLink, name_regexp, add_popup) {
var name = triggeringLink.id.replace(name_regexp, ''); var name = triggeringLink.id.replace(name_regexp, '');
name = id_to_windowname(name); name = id_to_windowname(name);
var href = triggeringLink.href; var href = triggeringLink.href;
if (add_popup) { if (add_popup) {
if (href.indexOf('?') === -1) { if (href.indexOf('?') === -1) {
href += '?_popup=1'; href += '?_popup=1';
...@@ -33,7 +37,9 @@ ...@@ -33,7 +37,9 @@
} }
} }
var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes'); var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus(); win.focus();
return false; return false;
} }
...@@ -44,6 +50,7 @@ ...@@ -44,6 +50,7 @@
function dismissRelatedLookupPopup(win, chosenId) { function dismissRelatedLookupPopup(win, chosenId) {
var name = windowname_to_id(win.name); var name = windowname_to_id(win.name);
var elem = document.getElementById(name); var elem = document.getElementById(name);
if (elem.className.indexOf('vManyToManyRawIdAdminField') !== -1 && elem.value) { if (elem.className.indexOf('vManyToManyRawIdAdminField') !== -1 && elem.value) {
elem.value += ',' + chosenId; elem.value += ',' + chosenId;
} else { } else {
...@@ -59,13 +66,16 @@ ...@@ -59,13 +66,16 @@
function updateRelatedObjectLinks(triggeringLink) { function updateRelatedObjectLinks(triggeringLink) {
var $this = $(triggeringLink); var $this = $(triggeringLink);
var siblings = $this.nextAll('.change-related, .delete-related'); var siblings = $this.nextAll('.change-related, .delete-related');
if (!siblings.length) { if (!siblings.length) {
return; return;
} }
var value = $this.val(); var value = $this.val();
if (value) { if (value) {
siblings.each(function() { siblings.each(function() {
var elm = $(this); var elm = $(this);
elm.attr('href', elm.attr('data-href-template').replace('__fk__', value)); elm.attr('href', elm.attr('data-href-template').replace('__fk__', value));
}); });
} else { } else {
...@@ -76,8 +86,10 @@ ...@@ -76,8 +86,10 @@
function dismissAddRelatedObjectPopup(win, newId, newRepr) { function dismissAddRelatedObjectPopup(win, newId, newRepr) {
var name = windowname_to_id(win.name); var name = windowname_to_id(win.name);
var elem = document.getElementById(name); var elem = document.getElementById(name);
if (elem) { if (elem) {
var elemName = elem.nodeName.toUpperCase(); var elemName = elem.nodeName.toUpperCase();
if (elemName === 'SELECT') { if (elemName === 'SELECT') {
elem.options[elem.options.length] = new Option(newRepr, newId, true, true); elem.options[elem.options.length] = new Option(newRepr, newId, true, true);
} else if (elemName === 'INPUT') { } else if (elemName === 'INPUT') {
...@@ -92,6 +104,7 @@ ...@@ -92,6 +104,7 @@
} else { } else {
var toId = name + "_to"; var toId = name + "_to";
var o = new Option(newRepr, newId); var o = new Option(newRepr, newId);
SelectBox.add_to_cache(toId, o); SelectBox.add_to_cache(toId, o);
SelectBox.redisplay(toId); SelectBox.redisplay(toId);
} }
...@@ -100,32 +113,44 @@ ...@@ -100,32 +113,44 @@
function dismissChangeRelatedObjectPopup(win, objId, newRepr, newId) { function dismissChangeRelatedObjectPopup(win, objId, newRepr, newId) {
var id = windowname_to_id(win.name).replace(/^edit_/, ''); 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); var selects = $(selectsSelector);
selects.find('option').each(function() { selects.find('option').each(function() {
if (this.value === objId) { if (this.value === objId) {
this.textContent = newRepr; this.textContent = newRepr;
this.value = newId; 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. // The element can have a clear button as a child.
// Use the lastChild to modify only the displayed value. // Use the lastChild to modify only the displayed value.
this.lastChild.textContent = newRepr; this.lastChild.textContent = newRepr;
this.title = newRepr; this.title = newRepr;
}); });
win.close(); win.close();
} }
function dismissDeleteRelatedObjectPopup(win, objId) { function dismissDeleteRelatedObjectPopup(win, objId) {
var id = windowname_to_id(win.name).replace(/^delete_/, ''); 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); var selects = $(selectsSelector);
selects.find('option').each(function() { selects.find('option').each(function() {
if (this.value === objId) { if (this.value === objId) {
$(this).remove(); $(this).remove();
} }
}).trigger('change'); })
.trigger('change');
win.close(); win.close();
} }
...@@ -154,6 +179,7 @@ ...@@ -154,6 +179,7 @@
e.preventDefault(); e.preventDefault();
if (this.href) { if (this.href) {
var event = $.Event('django:show-related', {href: this.href}); var event = $.Event('django:show-related', {href: this.href});
$(this).trigger(event); $(this).trigger(event);
if (!event.isDefaultPrevented()) { if (!event.isDefaultPrevented()) {
showRelatedObjectPopup(this); showRelatedObjectPopup(this);
...@@ -162,6 +188,7 @@ ...@@ -162,6 +188,7 @@
}); });
$('body').on('change', '.related-widget-wrapper select', function(e) { $('body').on('change', '.related-widget-wrapper select', function(e) {
var event = $.Event('django:update-related'); var event = $.Event('django:update-related');
$(this).trigger(event); $(this).trigger(event);
if (!event.isDefaultPrevented()) { if (!event.isDefaultPrevented()) {
updateRelatedObjectLinks(this); updateRelatedObjectLinks(this);
...@@ -171,6 +198,7 @@ ...@@ -171,6 +198,7 @@
$('body').on('click', '.related-lookup', function(e) { $('body').on('click', '.related-lookup', function(e) {
e.preventDefault(); e.preventDefault();
var event = $.Event('django:lookup-related'); var event = $.Event('django:lookup-related');
$(this).trigger(event); $(this).trigger(event);
if (!event.isDefaultPrevented()) { if (!event.isDefaultPrevented()) {
showRelatedObjectLookupPopup(this); showRelatedObjectLookupPopup(this);
......
...@@ -11,22 +11,27 @@ ...@@ -11,22 +11,27 @@
} }
} }
}, options); }, options);
$element.select2(settings); $element.select2(settings);
}; };
$.fn.djangoAdminSelect2 = function(options) { $.fn.djangoAdminSelect2 = function(options) {
var settings = $.extend({}, options); var settings = $.extend({}, options);
$.each(this, function(i, element) { $.each(this, function(i, element) {
var $element = $(element); var $element = $(element);
init($element, settings); init($element, settings);
}); });
return this; return this;
}; };
$(function() { $(function() {
// Initialize all autocomplete widgets except the one in the template // Initialize all autocomplete widgets except the one in the template
// form used when a new formset is added. // 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() { $(document).on('formset:added', (function() {
......
...@@ -33,22 +33,21 @@ depends on core.js for utility functions like removeChildren or quickElement ...@@ -33,22 +33,21 @@ depends on core.js for utility functions like removeChildren or quickElement
], ],
firstDayOfWeek: parseInt(get_format('FIRST_DAY_OF_WEEK')), firstDayOfWeek: parseInt(get_format('FIRST_DAY_OF_WEEK')),
isLeapYear: function(year) { 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) { getDaysInMonth: function(month, year) {
var days; var days;
if (month === 1 || month === 3 || month === 5 || month === 7 || month === 8 || month === 10 || month === 12) { if (month === 1 || month === 3 || month === 5 || month === 7 || month === 8 || month === 10 || month === 12) {
days = 31; days = 31;
} } else if (month === 4 || month === 6 || month === 9 || month === 11) {
else if (month === 4 || month === 6 || month === 9 || month === 11) {
days = 30; days = 30;
} } else if (month === 2 && CalendarNamespace.isLeapYear(year)) {
else if (month === 2 && CalendarNamespace.isLeapYear(year)) {
days = 29; days = 29;
} } else {
else {
days = 28; days = 28;
} }
return days; return days;
}, },
draw: function(month, year, div_id, callback, selected) { // month = 1-12, year = 1-9999 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 ...@@ -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 // The day variable above will be 1 instead of 2 in, say, US Pacific time
// zone. // zone.
var isSelectedMonth = false; var isSelectedMonth = false;
if (typeof selected !== 'undefined') { if (typeof selected !== 'undefined') {
isSelectedMonth = (selected.getUTCFullYear() === year && (selected.getUTCMonth() + 1) === month); isSelectedMonth = (selected.getUTCFullYear() === year && (selected.getUTCMonth() + 1) === month);
} }
...@@ -77,13 +77,16 @@ depends on core.js for utility functions like removeChildren or quickElement ...@@ -77,13 +77,16 @@ depends on core.js for utility functions like removeChildren or quickElement
month = parseInt(month); month = parseInt(month);
year = parseInt(year); year = parseInt(year);
var calDiv = document.getElementById(div_id); var calDiv = document.getElementById(div_id);
removeChildren(calDiv); removeChildren(calDiv);
var calTable = document.createElement('table'); var calTable = document.createElement('table');
quickElement('caption', calTable, CalendarNamespace.monthsOfYear[month - 1] + ' ' + year); quickElement('caption', calTable, CalendarNamespace.monthsOfYear[month - 1] + ' ' + year);
var tableBody = quickElement('tbody', calTable); var tableBody = quickElement('tbody', calTable);
// Draw days-of-week header // Draw days-of-week header
var tableRow = quickElement('tr', tableBody); var tableRow = quickElement('tr', tableBody);
for (var i = 0; i < 7; i++) { for (var i = 0; i < 7; i++) {
quickElement('th', tableRow, CalendarNamespace.daysOfWeek[(i + CalendarNamespace.firstDayOfWeek) % 7]); quickElement('th', tableRow, CalendarNamespace.daysOfWeek[(i + CalendarNamespace.firstDayOfWeek) % 7]);
} }
...@@ -105,11 +108,13 @@ depends on core.js for utility functions like removeChildren or quickElement ...@@ -105,11 +108,13 @@ depends on core.js for utility functions like removeChildren or quickElement
e.preventDefault(); e.preventDefault();
callback(y, m, this.textContent); callback(y, m, this.textContent);
} }
return onClick; return onClick;
} }
// Draw days of month // Draw days of month
var currentDay = 1; var currentDay = 1;
for (i = startingPos; currentDay <= days; i++) { for (i = startingPos; currentDay <= days; i++) {
if (i % 7 === 0 && currentDay !== 1) { if (i % 7 === 0 && currentDay !== 1) {
tableRow = quickElement('tr', tableBody); tableRow = quickElement('tr', tableBody);
...@@ -130,6 +135,7 @@ depends on core.js for utility functions like removeChildren or quickElement ...@@ -130,6 +135,7 @@ depends on core.js for utility functions like removeChildren or quickElement
var cell = quickElement('td', tableRow, '', 'class', todayClass); var cell = quickElement('td', tableRow, '', 'class', todayClass);
var link = quickElement('a', cell, currentDay, 'href', '#'); var link = quickElement('a', cell, currentDay, 'href', '#');
link.addEventListener('click', calendarMonth(year, month)); link.addEventListener('click', calendarMonth(year, month));
currentDay++; currentDay++;
} }
...@@ -168,7 +174,7 @@ depends on core.js for utility functions like removeChildren or quickElement ...@@ -168,7 +174,7 @@ depends on core.js for utility functions like removeChildren or quickElement
this.currentMonth = month; this.currentMonth = month;
this.currentYear = year; this.currentYear = year;
if(selected) { if (selected) {
this.selected = selected; this.selected = selected;
} }
...@@ -178,8 +184,7 @@ depends on core.js for utility functions like removeChildren or quickElement ...@@ -178,8 +184,7 @@ depends on core.js for utility functions like removeChildren or quickElement
if (this.currentMonth === 1) { if (this.currentMonth === 1) {
this.currentMonth = 12; this.currentMonth = 12;
this.currentYear--; this.currentYear--;
} } else {
else {
this.currentMonth--; this.currentMonth--;
} }
this.drawCurrent(); this.drawCurrent();
...@@ -188,8 +193,7 @@ depends on core.js for utility functions like removeChildren or quickElement ...@@ -188,8 +193,7 @@ depends on core.js for utility functions like removeChildren or quickElement
if (this.currentMonth === 12) { if (this.currentMonth === 12) {
this.currentMonth = 1; this.currentMonth = 1;
this.currentYear++; this.currentYear++;
} } else {
else {
this.currentMonth++; this.currentMonth++;
} }
this.drawCurrent(); this.drawCurrent();
......
...@@ -4,9 +4,11 @@ ...@@ -4,9 +4,11 @@
'use strict'; 'use strict';
$(document).ready(function() { $(document).ready(function() {
var modelName = $('#django-admin-form-add-constants').data('modelName'); var modelName = $('#django-admin-form-add-constants').data('modelName');
$('body').on('click', '.add-another', function(e) { $('body').on('click', '.add-another', function(e) {
e.preventDefault(); e.preventDefault();
var event = $.Event('django:add-another-related'); var event = $.Event('django:add-another-related');
$(this).trigger(event); $(this).trigger(event);
if (!event.isDefaultPrevented()) { if (!event.isDefaultPrevented()) {
showAddAnotherPopup(this); showAddAnotherPopup(this);
......
...@@ -6,20 +6,31 @@ ...@@ -6,20 +6,31 @@
$("fieldset.collapse").each(function(i, elem) { $("fieldset.collapse").each(function(i, elem) {
// Don't hide if fields in this fieldset have errors // Don't hide if fields in this fieldset have errors
if ($(elem).find("div.errors").length === 0) { 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") + i + '" class="collapse-toggle" href="#">' + gettext("Show") +
'</a>)'); '</a>)');
} }
}); });
// Add toggle to anchor tag // Add toggle to anchor tag
$("fieldset.collapse a.collapse-toggle").click(function(ev) { $("fieldset.collapse a.collapse-toggle").click(function(ev) {
if ($(this).closest("fieldset").hasClass("collapsed")) { if ($(this).closest("fieldset")
.hasClass("collapsed")) {
// Show // 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 { } else {
// Hide // 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; return false;
}); });
}); });
......
...@@ -8,15 +8,19 @@ var isIE = ((document.all) && (!isOpera)) && parseFloat(navigator.appVersion.spl ...@@ -8,15 +8,19 @@ var isIE = ((document.all) && (!isOpera)) && parseFloat(navigator.appVersion.spl
function quickElement() { function quickElement() {
'use strict'; 'use strict';
var obj = document.createElement(arguments[0]); var obj = document.createElement(arguments[0]);
if (arguments[2]) { if (arguments[2]) {
var textNode = document.createTextNode(arguments[2]); var textNode = document.createTextNode(arguments[2]);
obj.appendChild(textNode); obj.appendChild(textNode);
} }
var len = arguments.length; var len = arguments.length;
for (var i = 3; i < len; i += 2) { for (var i = 3; i < len; i += 2) {
obj.setAttribute(arguments[i], arguments[i + 1]); obj.setAttribute(arguments[i], arguments[i + 1]);
} }
arguments[1].appendChild(obj); arguments[1].appendChild(obj);
return obj; return obj;
} }
...@@ -35,6 +39,7 @@ function removeChildren(a) { ...@@ -35,6 +39,7 @@ function removeChildren(a) {
function findPosX(obj) { function findPosX(obj) {
'use strict'; 'use strict';
var curleft = 0; var curleft = 0;
if (obj.offsetParent) { if (obj.offsetParent) {
while (obj.offsetParent) { while (obj.offsetParent) {
curleft += obj.offsetLeft - ((isOpera) ? 0 : obj.scrollLeft); curleft += obj.offsetLeft - ((isOpera) ? 0 : obj.scrollLeft);
...@@ -47,12 +52,14 @@ function findPosX(obj) { ...@@ -47,12 +52,14 @@ function findPosX(obj) {
} else if (obj.x) { } else if (obj.x) {
curleft += obj.x; curleft += obj.x;
} }
return curleft; return curleft;
} }
function findPosY(obj) { function findPosY(obj) {
'use strict'; 'use strict';
var curtop = 0; var curtop = 0;
if (obj.offsetParent) { if (obj.offsetParent) {
while (obj.offsetParent) { while (obj.offsetParent) {
curtop += obj.offsetTop - ((isOpera) ? 0 : obj.scrollTop); curtop += obj.offsetTop - ((isOpera) ? 0 : obj.scrollTop);
...@@ -65,6 +72,7 @@ function findPosY(obj) { ...@@ -65,6 +72,7 @@ function findPosY(obj) {
} else if (obj.y) { } else if (obj.y) {
curtop += obj.y; curtop += obj.y;
} }
return curtop; return curtop;
} }
...@@ -75,10 +83,10 @@ function findPosY(obj) { ...@@ -75,10 +83,10 @@ function findPosY(obj) {
'use strict'; 'use strict';
Date.prototype.getTwelveHours = function() { Date.prototype.getTwelveHours = function() {
var hours = this.getHours(); var hours = this.getHours();
if (hours === 0) { if (hours === 0) {
return 12; return 12;
} } else {
else {
return hours <= 12 ? hours : hours - 12; return hours <= 12 ? hours : hours - 12;
} }
}; };
...@@ -140,27 +148,30 @@ function findPosY(obj) { ...@@ -140,27 +148,30 @@ function findPosY(obj) {
'%': '%' '%': '%'
}; };
var result = '', i = 0; var result = '', i = 0;
while (i < format.length) { while (i < format.length) {
if (format.charAt(i) === '%') { if (format.charAt(i) === '%') {
result = result + fields[format.charAt(i + 1)]; result = result + fields[format.charAt(i + 1)];
++i; ++i;
} } else {
else {
result = result + format.charAt(i); result = result + format.charAt(i);
} }
++i; ++i;
} }
return result; return result;
}; };
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// String object extensions // String object extensions
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
String.prototype.pad_left = function(pad_length, pad_string) { String.prototype.pad_left = function(pad_length, pad_string) {
var new_string = this; var new_string = this;
for (var i = 0; new_string.length < pad_length; i++) { for (var i = 0; new_string.length < pad_length; i++) {
new_string = pad_string + new_string; new_string = pad_string + new_string;
} }
return new_string; return new_string;
}; };
...@@ -169,20 +180,21 @@ function findPosY(obj) { ...@@ -169,20 +180,21 @@ function findPosY(obj) {
var date = this.split(/[.\-/]/); var date = this.split(/[.\-/]/);
var i = 0; var i = 0;
var day, month, year; var day, month, year;
while (i < split_format.length) { while (i < split_format.length) {
switch (split_format[i]) { switch (split_format[i]) {
case "%d": case "%d":
day = date[i]; day = date[i];
break; break;
case "%m": case "%m":
month = date[i] - 1; month = date[i] - 1;
break; break;
case "%Y": case "%Y":
year = date[i]; year = date[i];
break; break;
case "%y": case "%y":
year = date[i]; year = date[i];
break; break;
} }
++i; ++i;
} }
...@@ -199,14 +211,15 @@ function findPosY(obj) { ...@@ -199,14 +211,15 @@ function findPosY(obj) {
function getStyle(oElm, strCssRule) { function getStyle(oElm, strCssRule) {
'use strict'; 'use strict';
var strValue = ""; var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle) {
if (document.defaultView && document.defaultView.getComputedStyle) {
strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule); strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
} } else if (oElm.currentStyle) {
else if(oElm.currentStyle) {
strCssRule = strCssRule.replace(/\-(\w)/g, function(strMatch, p1) { strCssRule = strCssRule.replace(/\-(\w)/g, function(strMatch, p1) {
return p1.toUpperCase(); return p1.toUpperCase();
}); });
strValue = oElm.currentStyle[strCssRule]; strValue = oElm.currentStyle[strCssRule];
} }
return strValue; return strValue;
} }
...@@ -2,7 +2,8 @@ ...@@ -2,7 +2,8 @@
(function() { (function() {
'use strict'; 'use strict';
var initData = JSON.parse(document.getElementById('django-admin-popup-response-constants').dataset.popupResponse); var initData = JSON.parse(document.getElementById('django-admin-popup-response-constants').dataset.popupResponse);
switch(initData.action) {
switch (initData.action) {
case 'change': case 'change':
opener.dismissChangeRelatedObjectPopup(window, initData.value, initData.obj, initData.new_value); opener.dismissChangeRelatedObjectPopup(window, initData.value, initData.obj, initData.new_value);
break; break;
......
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
} }
var values = []; var values = [];
$.each(dependencies, function(i, field) { $.each(dependencies, function(i, field) {
field = $(field); field = $(field);
if (field.val().length > 0) { if (field.val().length > 0) {
...@@ -35,7 +36,9 @@ ...@@ -35,7 +36,9 @@
}); });
if (!prepopulatedField.val()) { if (!prepopulatedField.val()) {
$(dependencies.join(',')).keyup(populate).change(populate).focus(populate); $(dependencies.join(',')).keyup(populate)
.change(populate)
.focus(populate);
} }
}); });
}; };
......
(function($) { (function($) {
'use strict'; 'use strict';
var fields = $('#django-admin-prepopulated-fields-constants').data('prepopulatedFields'); var fields = $('#django-admin-prepopulated-fields-constants').data('prepopulatedFields');
$.each(fields, function(index, field) { $.each(fields, function(index, field) {
$('.empty-form .form-row .field-' + field.name + ', .empty-form.form-row .field-' + field.name).addClass('prepopulated_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.id).data('dependency_list', field.dependency_list)
field.dependency_ids, field.maxLength, field.allowUnicode .prepopulate(field.dependency_ids, field.maxLength, field.allowUnicode);
);
}); });
})(django.jQuery); })(django.jQuery);
...@@ -31,6 +31,7 @@ ...@@ -31,6 +31,7 @@
re: /^(\d+)\s*([ap])(?:.?m.?)?$/i, re: /^(\d+)\s*([ap])(?:.?m.?)?$/i,
handler: function(bits) { handler: function(bits) {
var hour = parseInt(bits[1]); var hour = parseInt(bits[1]);
if (hour === 12) { if (hour === 12) {
hour = 0; hour = 0;
} }
...@@ -38,6 +39,7 @@ ...@@ -38,6 +39,7 @@
if (hour === 12) { if (hour === 12) {
hour = 0; hour = 0;
} }
return (hour + 12) + ':00'; return (hour + 12) + ':00';
} else { } else {
if (hour < 10) { if (hour < 10) {
...@@ -54,6 +56,7 @@ ...@@ -54,6 +56,7 @@
handler: function(bits) { handler: function(bits) {
var hour = parseInt(bits[1]); var hour = parseInt(bits[1]);
var mins = parseInt(bits[2]); var mins = parseInt(bits[2]);
if (mins < 10) { if (mins < 10) {
mins = '0' + mins; mins = '0' + mins;
} }
...@@ -64,6 +67,7 @@ ...@@ -64,6 +67,7 @@
if (hour === 12) { if (hour === 12) {
hour = 0; hour = 0;
} }
return (hour + 12) + ':' + mins; return (hour + 12) + ':' + mins;
} else { } else {
if (hour < 10) { if (hour < 10) {
...@@ -95,10 +99,12 @@ ...@@ -95,10 +99,12 @@
var re = timeParsePatterns[i].re; var re = timeParsePatterns[i].re;
var handler = timeParsePatterns[i].handler; var handler = timeParsePatterns[i].handler;
var bits = re.exec(s); var bits = re.exec(s);
if (bits) { if (bits) {
return handler(bits); return handler(bits);
} }
} }
return s; return s;
} }
......
jQuery(document).ready(function($){ jQuery(document).ready(function($) {
var month_sel = $("select[name$='_month']"), var month_sel = $("select[name$='_month']"),
year_sel = $("select[name$='_year']"), year_sel = $("select[name$='_year']"),
default_month, default_year default_month, default_year;
var now = new Date() var now = new Date();
var current_month = now.getMonth() + 1 //jan = 0 var current_month = now.getMonth() + 1; //jan = 0
//Usually, export concerns previous month, so we select it as the default //Usually, export concerns previous month, so we select it as the default
if (current_month == 1){ if (current_month == 1) {
default_month = 12 default_month = 12;
default_year = now.getFullYear() - 1 default_year = now.getFullYear() - 1;
} } else {
else { default_month = current_month - 1;
default_month = current_month - 1 default_year = now.getFullYear();
default_year = now.getFullYear()
} }
month_sel.find("option[value='" + default_month + "']").attr('selected','selected'); month_sel.find("option[value='" + default_month + "']").attr('selected', 'selected');
year_sel.find("option[value='" + default_year + "']").attr('selected','selected'); year_sel.find("option[value='" + default_year + "']").attr('selected', 'selected');
function wait_for_odoo_export_file (export_id, url) { 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.') 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 , $.ajax({url : url + '?phase=1&export_id='+export_id,
dataType :'json' dataType :'json'
}) })
.done(function(rData){ .done(function(rData) {
if (rData.response && rData.response == true) { if (rData.response && rData.response == true) {
newWaitingMessage('Le document Odoo est terminé.<br/>Les ventes journalières sont compilées et les identifiants de coop. substitués.') newWaitingMessage('Le document Odoo est terminé.<br/>Les ventes journalières sont compilées et les identifiants de coop. substitués.');
$.ajax({url : url + '?phase=2&export_id='+export_id+ '&final_format=' + $('[name="final_format"]').val(), $.ajax({url : url + '?phase=2&export_id='+export_id+ '&final_format=' + $('[name="final_format"]').val(),
dataType :'json' dataType :'json'
}) })
.done(function(rData){ .done(function(rData) {
if (rData.response && rData.response.file_path) { if (rData.response && rData.response.file_path) {
var download_link = $('<a>').attr('href','/' + rData.response.file_path).text('Télécharger le fichier') var download_link = $('<a>').attr('href', '/' + rData.response.file_path)
$('form').hide() .text('Télécharger le fichier');
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') $('form').hide();
.append(preambule) if (rData.response.sells_total) {
.append(vente_ht) var preambule = $('<p>').html('A titre indicatif:');
.append(tva) var vente_ht = $('<p>').html('Ventes H.T: <strong>' + parseFloat(rData.response.sells_total).toFixed(2) + '</strong> € ');
.append(download_link) var tva = $('<p>').html('TVA sur ventes: <strong>' + parseFloat(rData.response.vat_total).toFixed(2) + '</strong> € ');
} else {
$('body').append(download_link)
}
}
closeWaiting()
})
}
}) $('body')
.append(preambule)
.append(vente_ht)
.append(tva)
.append(download_link);
} else {
$('body').append(download_link);
}
}
closeWaiting();
});
}
});
} }
$('form').submit(function(){ $('form').submit(function() {
var form = $(this) var form = $(this);
var month = month_sel.val() var month = month_sel.val();
var year = year_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) if (month > 0 && year > 0 && is_time_to('request_compta', 120000)) {
month = new String(month).pad('0', 2);
data = {'from': year + '-' + month + '-01', data = {'from': year + '-' + month + '-01',
'to': year + '-' + month + '-' + new Date(year, month, 0).getDate() 'to': year + '-' + month + '-' + new Date(year, month, 0).getDate()
} };
url = form.attr('action') url = form.attr('action');
post_form(url, data, function(error, rData){ post_form(url, data, function(error, rData) {
if (rData.response && !isNaN(rData.response)) if (rData.response && !isNaN(rData.response))
wait_for_odoo_export_file (rData.response, url) wait_for_odoo_export_file(rData.response, url);
else 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 { } else {
if ( month > 0 && year > 0) { if (month > 0 && year > 0) {
alert('Délai trop court entre 2 demandes...') alert('Délai trop court entre 2 demandes...');
} else { } 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 //always return false because form is processed through ajax call
return false return false;
}) });
}) });
var param_template = $('#templates #param'), var param_template = $('#templates #param'),
submit_btn = $('#templates #submit_button'), submit_btn = $('#templates #submit_button'),
main_content = $('#main_content') main_content = $('#main_content');
function save_module_settings() { function save_module_settings() {
var form_data = new FormData(main_content.get(0)) var form_data = new FormData(main_content.get(0));
var data = {} var data = {};
for(var pair of form_data.entries()) {
for (var pair of form_data.entries()) {
let val = pair[1], let val = pair[1],
key = pair[0] key = pair[0];
let elt = main_content.find('[name="' + key +'"]') let elt = main_content.find('[name="' + key +'"]');
data[key] = {title: elt.closest('.param').find('label').text(),
type: elt.get(0).type, data[key] = {title: elt.closest('.param').find('label')
value: val} .text(),
type: elt.get(0).type,
value: val};
} }
post_form('settings', {params: JSON.stringify(data)}, post_form(
function(err,result){ 'settings', {params: JSON.stringify(data)},
if (!err) { function(err, result) {
var succeeded = false if (!err) {
try { var succeeded = false;
if (result.res.save == true) {
display_msg_box('Enregistrement réussi !') try {
succeeded = true if (result.res.save == true) {
} display_msg_box('Enregistrement réussi !');
} catch(e) { succeeded = true;
console.log(e) }
} } catch (e) {
if (succeeded == false) display_msg_box('L\'enregistrement a échoué !', 'error') console.log(e);
} else { }
console.log(err) if (succeeded == false) display_msg_box('L\'enregistrement a échoué !', 'error');
} } else {
}) console.log(err);
}
}
);
} }
function get_module_settings() { function get_module_settings() {
$.ajax('settings') $.ajax('settings')
.done(function(rData){ .done(function(rData) {
try { try {
if (typeof rData.res.settings != "undefined"){ if (typeof rData.res.settings != "undefined") {
var added_elts = [] var added_elts = [];
for (let key in rData.res.settings) {
var param = $(param_template.clone().html()) for (let key in rData.res.settings) {
var input = null var param = $(param_template.clone().html());
let data = rData.res.settings[key] var input = null;
param.find('label').text(data.title).attr('for', key) let data = rData.res.settings[key];
if (data.type == 'textarea') {
param.find('input').remove() param.find('label').text(data.title)
input = param.find('textarea') .attr('for', key);
input.attr('name', key).text(data.value) if (data.type == 'textarea') {
} else { param.find('input').remove();
param.find('textarea').remove() input = param.find('textarea');
input = param.find('input') input.attr('name', key).text(data.value);
input.attr('name', key).attr('value', data.value) } else {
} param.find('textarea').remove();
input = param.find('input');
/* input.attr('name', key).attr('value', data.value);
}
/*
console.log(key) console.log(key)
console.log(data) console.log(data)
console.log(param) console.log(param)
*/ */
param.appendTo(main_content) param.appendTo(main_content);
added_elts.push(key) added_elts.push(key);
} }
if (added_elts.length > 0) { if (added_elts.length > 0) {
submit_btn.appendTo(main_content) submit_btn.appendTo(main_content);
}
submit_btn.click(save_module_settings);
} }
submit_btn.click(save_module_settings) } catch (e) {
console.log(e);
} }
} catch (e) {
console.log(e) });
}
})
} }
get_module_settings() get_module_settings();
\ No newline at end of file \ No newline at end of file
var results_table = null var results_table = null;
function coop_init_datatable(params,data, cols, action_btn) { function coop_init_datatable(params, data, cols, action_btn) {
var buttons = [] var buttons = [];
var columns = [] var columns = [];
$.each(cols,function(i,e){ $.each(cols, function(i, e) {
columns.push(e); columns.push(e);
}); });
var settings = { var settings = {
dom: '<lf<t>ip><"clear"><B>', dom: '<lf<t>ip><"clear"><B>',
lengthMenu : [[50,100,150,200,-1],[50,100,150,200,'Tout']], lengthMenu : [
pageLength : 50, [
buttons: buttons, 50,
100,
150,
200,
-1
],
[
50,
100,
150,
200,
'Tout'
]
],
pageLength : 50,
buttons: buttons,
columns: columns, columns: columns,
//select: select , //select: select ,
rowId : "_id", rowId : "_id",
data : data, data : data,
language: {url : '/static/js/datatables/french.json'} language: {url : '/static/js/datatables/french.json'}
} };
return $('#results').DataTable(settings) return $('#results').DataTable(settings);
} }
var viewJSErrors = function() { var viewJSErrors = function() {
$.get('/monitor/js_errors', {dataType: 'json'}) $.get('/monitor/js_errors', {dataType: 'json'})
.done(function(rData) { .done(function(rData) {
if (typeof rData.res.content != "undefined") { if (typeof rData.res.content != "undefined") {
if (results_table) results_table.destroy() if (results_table) results_table.destroy();
var data = [] var data = [];
var cols = [ var cols = [
{data: 'date', title: "Date"}, {data: 'date', title: "Date"},
{data: 'module', title: "Module"}, {data: 'module', title: "Module"},
{data: 'agent', title: "Signature nav."}, {data: 'agent', title: "Signature nav."},
{data: 'context', title: "Contexte"}, {data: 'context', title: "Contexte"},
{data: 'message', title: "Message"}, {data: 'message', title: "Message"}
] ];
rData.res.content.forEach(function(e){
var line = e rData.res.content.forEach(function(e) {
if (typeof e.data == 'object') { var line = e;
line.context = e.data.ctx
line.message = e.data.msg if (typeof e.data == 'object') {
delete e.data line.context = e.data.ctx;
} else { line.message = e.data.msg;
line.context = '?' delete e.data;
line.message = e.data } else {
} line.context = '?';
data.push(line) line.message = e.data;
}) }
console.log(data) data.push(line);
results_table = coop_init_datatable(null, data, cols); });
} console.log(data);
}) results_table = coop_init_datatable(null, data, cols);
} }
});
};
$(document).ready(function() { $(document).ready(function() {
if (coop_is_connected()) { if (coop_is_connected()) {
$('header').show() $('header').show();
$('.nav-list .js_errors').click(viewJSErrors) $('.nav-list .js_errors').click(viewJSErrors);
} }
}) });
\ No newline at end of file \ No newline at end of file
...@@ -3,24 +3,31 @@ ...@@ -3,24 +3,31 @@
var oidoc = { var oidoc = {
_id: '_design/index', _id: '_design/index',
views: { views: {
by_fp: { by_fp: {
map: function (doc) { emit(doc.fingerprint); }.toString() map: function (doc) {
}, emit(doc.fingerprint);
by_completed: { }.toString()
map: function (doc) { emit(doc.completed); }.toString() },
}, by_completed: {
by_odoo_id: { map: function (doc) {
map: function (doc) { emit(doc.odoo_id); }.toString() emit(doc.completed);
}.toString()
},
by_odoo_id: {
map: function (doc) {
emit(doc.odoo_id);
}.toString()
}
} }
}
}; };
// save it // save it
dbc.put(oidoc,function (err, result) {
if (!err) { dbc.put(oidoc, function (err, result) {
console.log('index enregistré'); if (!err) {
} else { console.log('index enregistré');
} else {
//console.log(err); //console.log(err);
} }
}); });
\ No newline at end of file
...@@ -5,87 +5,91 @@ IFCBarcodes = { ...@@ -5,87 +5,91 @@ IFCBarcodes = {
init : async function() { init : async function() {
// as it is a long time response task, restrict it // as it is a long time response task, restrict it
if (is_time_to('load_barcodes', 5000)) { if (is_time_to('load_barcodes', 5000)) {
openWaiting('Récupération des informations code-barres....') openWaiting('Récupération des informations code-barres....');
try { try {
let response = await fetch('/products/barcodes') let response = await fetch('/products/barcodes');
let bc_data = await response.json() let bc_data = await response.json();
closeModal()
closeModal();
if (typeof bc_data.res.error == "undefined") { if (typeof bc_data.res.error == "undefined") {
this.patterns = bc_data.res.patterns this.patterns = bc_data.res.patterns;
this.codes = bc_data.res.bc this.codes = bc_data.res.bc;
} else { } else {
this.errors.push(bc_data.error) this.errors.push(bc_data.error);
} }
} catch(e) { } catch (e) {
err = {msg: e.name + ' : ' + e.message, ctx: 'retrieve barcodes'} err = {msg: e.name + ' : ' + e.message, ctx: 'retrieve barcodes'};
console.error(err) console.error(err);
report_JS_error(err, 'products') report_JS_error(err, 'products');
closeModal() closeModal();
this.errors.push(JSON.stringify(err)) this.errors.push(JSON.stringify(err));
} }
} }
}, },
display_last_error: function() { display_last_error: function() {
alert(this.errors[this.errors.length - 1]) alert(this.errors[this.errors.length - 1]);
}, },
get_corresponding_odoo_product: function(bc) { get_corresponding_odoo_product: function(bc) {
//console.log('To analyze :' + bc) //console.log('To analyze :' + bc)
var odoo_product = null var odoo_product = null;
var index = 0, var index = 0,
pattern_found = false, pattern_found = false,
encoded_value = '' encoded_value = '';
// Let's find out if it matches a pattern // Let's find out if it matches a pattern
while (index < this.patterns.length -1 && pattern_found === false) { while (index < this.patterns.length -1 && pattern_found === false) {
var pattern = this.patterns[index] var pattern = this.patterns[index];
var significant_prefix = pattern.replace(/[^0-9]/g,'') //remove all but figures var significant_prefix = pattern.replace(/[^0-9]/g, ''); //remove all but figures
if (bc.indexOf(significant_prefix) === 0) { if (bc.indexOf(significant_prefix) === 0) {
// console.log(pattern) // console.log(pattern)
// console.log(bc) // console.log(bc)
//0493...{NNDDD} (pattern) //0493...{NNDDD} (pattern)
//0493213018809 (bc) //0493213018809 (bc)
pattern_found = true pattern_found = true;
pattern = pattern.replace(/[^0-9\.ND]/,'') pattern = pattern.replace(/[^0-9\.ND]/, '');
bc = bc.slice(0,-1) // remove original check figure bc = bc.slice(0, -1); // remove original check figure
odoo_bc = '' odoo_bc = '';
// Read pattern character by character // Read pattern character by character
for (var i = 0; i < pattern.length; i++) { for (var i = 0; i < pattern.length; i++) {
if (/[0-9]/.exec(pattern[i])) { if (/[0-9]/.exec(pattern[i])) {
odoo_bc += pattern[i] odoo_bc += pattern[i];
} else if (pattern[i].indexOf('.') === 0) { } else if (pattern[i].indexOf('.') === 0) {
odoo_bc += bc[i] odoo_bc += bc[i];
} else if (/[ND]/.exec(pattern[i])) { } else if (/[ND]/.exec(pattern[i])) {
odoo_bc += '0' odoo_bc += '0';
if (pattern[i] === 'D' && encoded_value.indexOf('.') < 0) if (pattern[i] === 'D' && encoded_value.indexOf('.') < 0)
encoded_value += '.' encoded_value += '.';
encoded_value += bc[i] encoded_value += bc[i];
} }
} }
// Add check digit at the end of odoo_bc to find out "normalized" code // 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 // let's seek "normalized" bc in codes array
for (code in this.codes) { for (code in this.codes) {
if (code == bc) { 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) //console.log(odoo_product)
return odoo_product return odoo_product;
} }
} };
init_barcodes = async function() { init_barcodes = async function() {
var result = null var result = null;
var ifcb = Object.create(IFCBarcodes) var ifcb = Object.create(IFCBarcodes);
await ifcb.init()
if (ifcb.errors.length > 0) await ifcb.init();
ifcb.display_last_error() if (ifcb.errors.length > 0)
else ifcb.display_last_error();
result = ifcb else
// console.log(result.patterns) result = ifcb;
return result // console.log(result.patterns)
} return result;
};
...@@ -7,149 +7,162 @@ var active_table = null, ...@@ -7,149 +7,162 @@ var active_table = null,
bc_scanner = $('#barcode_scanner'); bc_scanner = $('#barcode_scanner');
function getLocalSelected() { function getLocalSelected() {
var local_in_process = localStorage.getItem("selected_products") || "[]" var local_in_process = localStorage.getItem("selected_products") || "[]";
return JSON.parse(local_in_process)
return JSON.parse(local_in_process);
} }
function setLocalSelected(lip) { function setLocalSelected(lip) {
localStorage.setItem("selected_products",JSON.stringify(lip)) localStorage.setItem("selected_products", JSON.stringify(lip));
} }
function getLocalPdtDB() { 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") if (typeof (local_pdt_db.list) == "undefined")
local_pdt_db.list = [] local_pdt_db.list = [];
return local_pdt_db
return local_pdt_db;
} }
function setLocalPdtDB(lpdb) { function setLocalPdtDB(lpdb) {
localStorage.setItem("products_db",JSON.stringify(lpdb)) localStorage.setItem("products_db", JSON.stringify(lpdb));
} }
function display_in_search_results(matching) { function display_in_search_results(matching) {
var ul = $('<ul>'); var ul = $('<ul>');
$.each(matching, function(i,e){
var li = $('<li>').attr('data-index',e.index).text(e.doc.barcode + ' ' + e.doc.display_name) $.each(matching, function(i, e) {
ul.append(li) var li = $('<li>').attr('data-index', e.index)
}) .text(e.doc.barcode + ' ' + e.doc.display_name);
search_result.html(ul)
ul.append(li);
});
search_result.html(ul);
} }
function search_in_pdt_list(kwords) { function search_in_pdt_list(kwords) {
if (kwords.length > 3) { if (kwords.length > 3) {
var matching = [] var matching = [];
var is_bc = !isNaN(kwords) var is_bc = !isNaN(kwords);
if (!is_bc) if (!is_bc)
kwords = jQuery.fn.DataTable.ext.type.search.string(kwords.toLowerCase()) kwords = jQuery.fn.DataTable.ext.type.search.string(kwords.toLowerCase());
$.each(local_pdt_db.list, function(i,e) { $.each(local_pdt_db.list, function(i, e) {
if (is_bc) { if (is_bc) {
if (e.barcode && e.barcode.indexOf(kwords) === 0) { if (e.barcode && e.barcode.indexOf(kwords) === 0) {
matching.push({doc:e,index:i}) matching.push({doc:e, index:i});
} }
} else { } else {
var p_name = jQuery.fn.DataTable.ext.type.search.string(e.display_name) var p_name = jQuery.fn.DataTable.ext.type.search.string(e.display_name);
if (p_name.toLowerCase().indexOf(kwords) > -1) 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 > 0) {
if (matching.length == 1 && is_bc == true){ if (matching.length == 1 && is_bc == true) {
add_product_to_table(matching[0].index) add_product_to_table(matching[0].index);
} else { } else {
display_in_search_results(matching) display_in_search_results(matching);
} }
} }
} else { } else {
search_result.html('') search_result.html('');
} }
} }
$(document).pos(); $(document).pos();
$(document).on('scan.pos.barcode', function(event){ $(document).on('scan.pos.barcode', function(event) {
//access `event.code` - barcode data //access `event.code` - barcode data
var barcode = event.code var barcode = event.code;
if (barcode.length >=13) {
barcode = barcode.substring(barcode.length-13) if (barcode.length >=13) {
search_in_pdt_list(barcode) barcode = barcode.substring(barcode.length-13);
} else { search_in_pdt_list(barcode);
console.log($(':focus').attr('type')) } else {
console.log(new Date().getTime() + ' -> '+barcode) console.log($(':focus').attr('type'));
} console.log(new Date().getTime() + ' -> '+barcode);
}
});
});
function destocking_record() { function destocking_record() {
console.log('envoyer les informations à Django') console.log('envoyer les informations à Django');
} }
function init_table_interface (data) { function init_table_interface (data) {
if (active_table) if (active_table)
active_table.destroy() active_table.destroy();
var cols = [ var cols = [
{data: 'display_name', title: "Nom"}, {data: 'display_name', title: "Nom"},
{data: 'qty', title: "Quantité", defaultContent: ""} {data: 'qty', title: "Quantité", defaultContent: ""}
] ];
var action_btn = { var action_btn = {
text: 'Valider le déstockage', text: 'Valider le déstockage',
action : function(e,dt) { action : function(e, dt) {
if (dt.rows().indexes().length > 0) if (dt.rows().indexes().length > 0)
openModal('Valider le déstockage', destocking_record, 'Enregistrer'); openModal('Valider le déstockage', destocking_record, 'Enregistrer');
else else
alert("Impossible, il n'y a aucun produit !") alert("Impossible, il n'y a aucun produit !");
} }
}; };
var params = {no_search: true} var params = {no_search: true};
active_table = coop_init_datatable(params, data, '.pdt_liste_to_transfert', cols, action_btn); active_table = coop_init_datatable(params, data, '.pdt_liste_to_transfert', cols, action_btn);
} }
function add_product_to_table(p_index) { function add_product_to_table(p_index) {
var local_selected = getLocalSelected(); 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) if (selected_p.uom_id[0] == 1)
selected_p.qty = 1 selected_p.qty = 1;
console.log('p_index='+p_index) console.log('p_index='+p_index);
console.log(selected_p) console.log(selected_p);
local_selected.push(selected_p) local_selected.push(selected_p);
setLocalSelected(local_selected) setLocalSelected(local_selected);
search_result.html('') search_result.html('');
init_table_interface(local_selected) init_table_interface(local_selected);
} }
var need_to_load_odoo_products = true; 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 (local_pdt_db.list.length > 0) {
if (new Date().getTime() - local_pdt_db.created_at < 7200000) { 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 // if data have been retrieved less than 2h ago, no need to make ajax call
need_to_load_odoo_products = false; need_to_load_odoo_products = false;
loader.hide() loader.hide();
search_div.show() search_div.show();
} }
} }
if (need_to_load_odoo_products == true) { if (need_to_load_odoo_products == true) {
$.ajax('get_all_available_products').done(function(rData){ $.ajax('get_all_available_products').done(function(rData) {
local_pdt_db.list = rData local_pdt_db.list = rData;
local_pdt_db.created_at = new Date().getTime() local_pdt_db.created_at = new Date().getTime();
setLocalPdtDB(local_pdt_db) setLocalPdtDB(local_pdt_db);
loader.hide() loader.hide();
search_div.show() search_div.show();
}); });
} }
search_input.on('keyup focus', function() {
search_in_pdt_list($(this).val());
});
search_input.on('keyup focus', function(){ search_div.on('click', 'li', function() {
search_in_pdt_list($(this).val()) var p_index = $(this).data('index');
})
search_div.on('click', 'li', function(){ add_product_to_table(p_index);
var p_index = $(this).data('index') });
add_product_to_table(p_index)
})
if (local_selected.length > 0) { 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) { function products_shelf_label_print (products, callback) {
console.log('Demande impression etiquettes rayon') console.log('Demande impression etiquettes rayon');
params = {products: JSON.stringify(products)} params = {products: JSON.stringify(products)};
post_form('/products/shelf_labels', params, callback) post_form('/products/shelf_labels', params, callback);
} }
/* /*
$.ajax({ $.ajax({
......
...@@ -8,96 +8,101 @@ Informations affichées : ...@@ -8,96 +8,101 @@ Informations affichées :
var parent_location = '/shelfs', var parent_location = '/shelfs',
shelf, shelf,
table_products, table_products,
search_chars = [] search_chars = [];
/* UTILS */ /* UTILS */
// Round a decimal value // Round a decimal value
function round(value, decimals) { function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals); return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
} }
function back() { function back() {
document.location.href = parent_location document.location.href = parent_location;
} }
// Set search field with product name when barcode is read // Set search field with product name when barcode is read
function select_product_from_bc(barcode) { function select_product_from_bc(barcode) {
$.each(shelf_products, function(i,e) { $.each(shelf_products, function(i, e) {
if (e.barcode == barcode) { if (e.barcode == barcode) {
$('#search_input').val(e.name) $('#search_input').val(e.name);
table_products.search(jQuery.fn.DataTable.ext.type.search.string(e.name)).draw() table_products.search(jQuery.fn.DataTable.ext.type.search.string(e.name)).draw();
} }
}) });
} }
/* LIST HANDLING */ /* LIST HANDLING */
// Init Data & listeners // Init Data & listeners
function initList() { function initList() {
// Init table for items to process // Init table for items to process
table_products = $('#table_shelf_products').DataTable( { table_products = $('#table_shelf_products').DataTable({
data: shelf_products, data: shelf_products,
columns: [ columns: [
{data:"id", title: "id", visible: false}, {data:"id", title: "id", visible: false},
{data:"name", title:"Produit"}, {data:"name", title:"Produit"},
{ {
data:"qty_available", data:"qty_available",
title:"Stock théorique", title:"Stock théorique",
width: "10%", width: "10%",
render: function (data, type, full) { render: function (data, type, full) {
return round(data, 2) + ' ' + full.uom_id[1] return round(data, 2) + ' ' + full.uom_id[1];
} }
}, },
{ {
data:"last_inv_delta", data:"last_inv_delta",
title:"Delta (dernier inv.)", title:"Delta (dernier inv.)",
width: "10%", width: "10%",
className:"dt-body-center", className:"dt-body-center",
render: function (data, type, full, meta) { render: function (data, type, full, meta) {
if (type == "sort" || type == 'type') if (type == "sort" || type == 'type')
return data return data;
if (data == -99999999) { if (data == -99999999) {
return '/' return '/';
} else { } else {
return data return data;
} }
} }
}, },
{ {
data:"last_inv_losses", data:"last_inv_losses",
title:"Pertes (dernier inv.)", title:"Pertes (dernier inv.)",
width: "10%", width: "10%",
className:"dt-body-center", className:"dt-body-center",
render: function (data, type, full, meta) { render: function (data, type, full, meta) {
if (type == "sort" || type == 'type') if (type == "sort" || type == 'type')
return data return data;
if (data == -99999999) { if (data == -99999999) {
return '/' return '/';
} else { } else {
return data + ' €' return data + ' €';
} }
} }
}, }
], ],
rowId : "id", rowId : "id",
order: [[ 0, "asc" ]], order: [
paging: false, [
dom: 'lrtip', // Remove the search input from that table 0,
language: {url : '/static/js/datatables/french.json'} "asc"
}); ]
],
paging: false,
/* Listeners on table & search input */ dom: 'lrtip', // Remove the search input from that table
language: {url : '/static/js/datatables/french.json'}
// 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) /* Listeners on table & search input */
.draw()
}) // 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() { ...@@ -105,76 +110,78 @@ function initList() {
// Get shelf data from server if not in local storage // Get shelf data from server if not in local storage
function get_shelf_data() { function get_shelf_data() {
$.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } }); $.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });
$.ajax({ $.ajax({
type: 'GET', type: 'GET',
url: '../' + shelf.id, url: '../' + shelf.id,
dataType:"json", dataType:"json",
traditional: true, traditional: true,
contentType: "application/json; charset=utf-8", contentType: "application/json; charset=utf-8",
success: function(data) { success: function(data) {
shelf = data.res shelf = data.res;
init() init();
}, },
error: function(data) { error: function(data) {
if (typeof data.responseJSON != 'undefined' ) { if (typeof data.responseJSON != 'undefined') {
console.log(data.responseJSON) console.log(data.responseJSON);
} }
alert('Les données n\'ont pas pu être récupérées, réessayez plus tard.'); 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 // Init page : to be launched when shelf data is here
function init() { function init() {
// Set shelf name in DOM // Set shelf name in DOM
$('#shelf_name').text(shelf.name) $('#shelf_name').text(shelf.name);
// Products passed at page loading as 'shelf_products' // Products passed at page loading as 'shelf_products'
initList() initList();
// Barcode reader: listen for 13 digits read in a very short time // Barcode reader: listen for 13 digits read in a very short time
$('#search_input').keypress(function(e) { $('#search_input').keypress(function(e) {
if (e.which >= 48 && e.which <= 57) { if (e.which >= 48 && e.which <= 57) {
search_chars.push(String.fromCharCode(e.which)); search_chars.push(String.fromCharCode(e.which));
} }
if (search_chars.length >= 13) { if (search_chars.length >= 13) {
var barcode = search_chars.join(""); var barcode = search_chars.join("");
if (!isNaN(barcode)) {
search_chars = []; if (!isNaN(barcode)) {
setTimeout(function(){ search_chars = [];
select_product_from_bc(barcode); setTimeout(function() {
}, 300); select_product_from_bc(barcode);
} }, 300);
} }
}) }
});
} }
$(document).ready(function() { $(document).ready(function() {
// Get Route parameter // Get Route parameter
var pathArray = window.location.pathname.split('/') var pathArray = window.location.pathname.split('/');
shelf = {id: pathArray[pathArray.length-1]}
// Get shelf data from local storage shelf = {id: pathArray[pathArray.length-1]};
if (Modernizr.localstorage) {
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + shelf.id))
if (stored_shelf != null) { // Get shelf data from local storage
shelf = stored_shelf if (Modernizr.localstorage) {
init() 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 { } 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 () {
// listeners $('#search_input').val('');
// Cancel search table_products.search('').draw();
$('.cancel_search').on('click', function () { });
$('#search_input').val('')
table_products.search('').draw()
})
}); });
var shelfs_table = null var shelfs_table = null;
function init_datatable() { function init_datatable() {
return $('#shelfs').DataTable( { return $('#shelfs').DataTable({
data: shelfs, // data passed at page loading data: shelfs, // data passed at page loading
rowId: 'id', rowId: 'id',
columns:[ columns:[
{data: "id", title:"id", "visible": false}, {data: "id", title:"id", "visible": false},
{ {
data:"sort_order", data:"sort_order",
title:"Numéro", title:"Numéro",
width: "10%", width: "10%",
className:"dt-body-center" className:"dt-body-center"
}, },
{data:"name", title:"Nom"}, {data:"name", title:"Nom"},
{data:"description", title:"Description", orderable: false}, {data:"description", title:"Description", orderable: false},
{ {
data:"date_last_inventory", data:"date_last_inventory",
title:"Date dernier inventaire", title:"Date dernier inventaire",
render: function (data, type, full, meta) { render: function (data, type, full, meta) {
// Sort on data, not rendering // Sort on data, not rendering
if (type == "sort" || type == 'type') if (type == "sort" || type == 'type')
return data return data;
if (data == '0001-01-01') if (data == '0001-01-01')
return "Ce rayon n'a jamais été inventorié !" return "Ce rayon n'a jamais été inventorié !";
else { else {
var date = new Date(data) var date = new Date(data);
return date.toLocaleDateString('fr-FR')
}
} return date.toLocaleDateString('fr-FR');
}, }
{data:"p_nb", title:"Nb réfs", width: "5%", className:"dt-body-center"}, }
{ },
title:"", {data:"p_nb", title:"Nb réfs", width: "5%", className:"dt-body-center"},
className:"dt-body-center", {
width: "15%", title:"",
render: function (data, type, full, meta) { className:"dt-body-center",
return "<button class='btn--success do_export_sales_data'>Export Ventes</button>" 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, dom: 'rtip',
language: {url : '/static/js/datatables/french.json'} order: [
}) [
} 1,
"asc"
]
],
var getRowData = function(clicked) { iDisplayLength: 25,
var row = shelfs_table.row(clicked.parents('tr')) language: {url : '/static/js/datatables/french.json'}
return row.data() });
} }
function go_to_shelf_view() { var getRowData = function(clicked) {
openModal() var row = shelfs_table.row(clicked.parents('tr'));
var clicked = $(this)
var row_data = getRowData(clicked) return row.data();
};
// Use local storage to pass data to next page
if (Modernizr.localstorage) {
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + row_data.id))
function go_to_shelf_view() {
// Set local storage if key doesn't exist openModal();
if (stored_shelf == null) {
localStorage.setItem("shelf_" + row_data.id , JSON.stringify(row_data)) var clicked = $(this);
} var row_data = getRowData(clicked);
}
// Use local storage to pass data to next page
document.location.href = "shelf_view/" + row_data.id if (Modernizr.localstorage) {
} var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + row_data.id));
function get_shelfs_sales_data() { // Set local storage if key doesn't exist
try { if (stored_shelf == null) {
localStorage.setItem("shelf_" + row_data.id, JSON.stringify(row_data));
$.ajax({ }
type: 'GET', }
url: '/shelfs/get_shelves_sales_data',
dataType:"json", document.location.href = "shelf_view/" + row_data.id;
traditional: true, }
contentType: "application/json; charset=utf-8",
success: function(data) { function get_shelfs_sales_data() {
for (item of data.res) { try {
var row_data = shelfs_table.row('#'+item.id).data()
row_data.shelf_value = item.shelf_value $.ajax({
type: 'GET',
shelfs_table url: '/shelfs/get_shelves_sales_data',
.row( '#'+item.id ) dataType:"json",
.data( row_data ) traditional: true,
.draw() contentType: "application/json; charset=utf-8",
} success: function(data) {
}, for (item of data.res) {
error: function(data) { var row_data = shelfs_table.row('#'+item.id).data();
if (typeof data.responseJSON != 'undefined') {
console.log(data.responseJSON) row_data.shelf_value = item.shelf_value;
}
shelfs_table
.row('#'+item.id)
} .data(row_data)
}) .draw();
} catch (e) { }
err = {msg: e.toString(), ctx: 'get_shelfs_sales_data'} },
report_JS_error(err, 'shelfs') error: function(data) {
} if (typeof data.responseJSON != 'undefined') {
} console.log(data.responseJSON);
function export_sales_data(event) { }
event.stopImmediatePropagation()
var clicked = $(this)
var row_data = getRowData(clicked) }
console.log(row_data) });
} catch (e) {
} err = {msg: e.toString(), ctx: 'get_shelfs_sales_data'};
report_JS_error(err, 'shelfs');
$(document).ready(function() { }
shelfs_table = init_datatable() }
function export_sales_data(event) {
$('#shelfs').on('click', 'button.do_export_sales_data', export_sales_data) event.stopImmediatePropagation();
$('#shelfs').on('click', 'tbody td', go_to_shelf_view) var clicked = $(this);
var row_data = getRowData(clicked);
// Search input
$('#search_input').on('keyup', function () { console.log(row_data);
shelfs_table
.search(jQuery.fn.DataTable.ext.type.search.string(this.value)) }
.draw()
}) $(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 // Request a delay for the current member
function request_delay() { function request_delay() {
//Loading on //Loading on
openModal(); openModal();
var today = new Date(); var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate(); var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
$.ajaxSetup({headers: {"X-CSRFToken": getCookie('csrftoken')}}); $.ajaxSetup({headers: {"X-CSRFToken": getCookie('csrftoken')}});
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: '/shifts/request_delay', url: '/shifts/request_delay',
dataType: 'json', dataType: 'json',
timeout: 3000, timeout: 3000,
data: { data: {
idPartner: dataPartner.partner_id, idPartner: dataPartner.partner_id,
verif_token: dataPartner.verif_token, verif_token: dataPartner.verif_token,
start_date: date start_date: date
}, },
success: function(doc) { success: function(doc) {
document.location.reload(); document.location.reload();
}, },
error: function() { error: function() {
closeModal(); closeModal();
alert('Impossible de créer l\'extension. Je dois passer au Bureau des membres pour régler le problème.'); alert('Impossible de créer l\'extension. Je dois passer au Bureau des membres pour régler le problème.');
} }
}); });
} }
$(document).ready(function() { $(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 // Member can ask for 6 delays, which is 24 weeks after entering alert status
// 'date_alert_stop' field is begining of alert + 4 weeks // 'date_alert_stop' field is begining of alert + 4 weeks
var date_end_alert = new Date(dataPartner.date_alert_stop); var date_end_alert = new Date(dataPartner.date_alert_stop);
date_end_alert.setDate(date_end_alert.getDate()+20*7);
date_end_alert.setDate(date_end_alert.getDate()+20*7);
if (date_end_alert < new Date()) { if (date_end_alert < new Date()) {
$('#no_delay').removeAttr('hidden'); $('#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 { } 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; var myChart;
function get_ajax_data(product_id){ function get_ajax_data(product_id) {
$.ajax({ $.ajax({
type: 'GET', type: 'GET',
url: 'get_list_sale_breaking/' + product_id, url: 'get_list_sale_breaking/' + product_id,
dataType:"json", dataType:"json",
timeout: 3000, timeout: 3000,
beforeSend: function () { }, beforeSend: function () { },
complete: function () { }, complete: function () { },
success: function(data) { success: function(data) {
myChart.data = data['data']; myChart.data = data['data'];
myChart.update(); myChart.update();
}, },
error: function() { error: function() {
alert('Les données n\'ont pas pu être récupérées, réessayez plus tard.'); alert('Les données n\'ont pas pu être récupérées, réessayez plus tard.');
} }
}); });
} }
var config = { var config = {
type: 'bar', type: 'bar',
data: {}, data: {},
options: { options: {
title: { title: {
display: true, display: true,
text: 'Graph. des ventes' text: 'Graph. des ventes'
}, },
legend: { display: false } legend: { display: false }
} }
}; };
window.onload = function() { 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) { $('.modal').on('show.bs.modal', function (e) {
var button = $(e.relatedTarget) var button = $(e.relatedTarget);
var index = button.data('remote') var index = button.data('remote');
//$(this).find('.modal-content').load('remote' + index + '.html') //$(this).find('.modal-content').load('remote' + index + '.html')
get_ajax_data(index);
get_ajax_data(index);
})
}) });
});
/* Page de la commande: /* Page de la commande:
* Creation d'un nouvelle commande d'un fournisseur. * Creation d'un nouvelle commande d'un fournisseur.
* Liste des articles d'un fournisseur (Recherche des fournisseurs avec un prés saisi) * 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 * 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 * 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 * 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 table_article;
var dataSet =[] ; var dataSet =[];
var csrftoken; var csrftoken;
var four_id=0; var four_id=0;
// lance la recherche sur le nom des l'article // 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(); table_article.ajax.url('get_list_article_fournisseur/'+four_id+"/").load();
} }
// Initialise le table des articles // Initialise le table des articles
$(document).ready(function() { $(document).ready(function() {
table_article = $('#tableArticle').DataTable( { table_article = $('#tableArticle').DataTable({
"ajax": { "ajax": {
"url": "get_list_article_fournisseur/1712/", "url": "get_list_article_fournisseur/1712/",
"data": "" "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"
}, },
"aria": { "columns":[
"sortAscending": ": activate to sort column ascending", {data:"name_template", "title":"Article", "width": "50%"},
"sortDescending": ": activate to sort column descending" {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 //barcode-reader
$(document).ready(function() { $(document).ready(function() {
var pressed = false; var pressed = false;
var chars = []; var chars = [];
$(window).keypress(function(e) { $(window).keypress(function(e) {
if (e.which >= 48 && e.which <= 57) { if (e.which >= 48 && e.which <= 57) {
chars.push(String.fromCharCode(e.which)); chars.push(String.fromCharCode(e.which));
} }
if (pressed == false) { if (pressed == false) {
setTimeout(function(){ setTimeout(function() {
if (chars.length >= 13) { if (chars.length >= 13) {
var barcode = chars.join(""); var barcode = chars.join("");
if (!isNaN(barcode)) { if (!isNaN(barcode)) {
chars = []; chars = [];
pressed = false; pressed = false;
search_article_byBarcode(); search_article_byBarcode();
} }
} }
},300); }, 300);
} }
pressed = true; pressed = true;
}); });
}); });
$(document).ready(function() { $(document).ready(function() {
csrftoken = getCookie('csrftoken'); csrftoken = getCookie('csrftoken');
}); });
// Lancement de la rupture sur l'article choisie // 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] }; var jIdArcticle = { 'idArticle': selArctileData.id, 'uom_id' : selArctileData.uom_id[0] };
$.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } }); $.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } });
$.ajax({ $.ajax({
type: "PUT", type: "PUT",
url: "set_rupture" , url: "set_rupture",
//dataType: "json", //dataType: "json",
traditional: true, traditional: true,
contentType: "application/json; charset=utf-8", contentType: "application/json; charset=utf-8",
data: JSON.stringify(jIdArcticle), data: JSON.stringify(jIdArcticle),
success: function(data) { success: function(data) {
document.location.href = "/stock"; document.location.href = "/stock";
}, },
error: function(resultat, statut, erreur) { error: function(resultat, statut, erreur) {
alert('Erreur' + erreur); alert('Erreur' + erreur);
} }
}); });
} }
var selArctileData; var selArctileData;
...@@ -139,23 +148,22 @@ $(document).ready(function() { ...@@ -139,23 +148,22 @@ $(document).ready(function() {
var options = { var options = {
url : "get_liste_supplyer", url : "get_liste_supplyer",
list: { list: {
maxNumberOfElements: 8, maxNumberOfElements: 8,
match: { match: {
enabled: true enabled: true
}, },
sort: { sort: {
enabled: true enabled: true
}, },
onSelectItemEvent: function() { onSelectItemEvent: function() {
four_id = $("#template-custom").getSelectedItemData().id; four_id = $("#template-custom").getSelectedItemData().id;
}
} }
,
},
getValue: "display_name", getValue: "display_name",
template: { template: {
type: "display_name", type: "display_name"
//method: function(value, item) { //method: function(value, item) {
// return "<img src='" + item.icon + "' /> | " + item.type + " | " + value; // return "<img src='" + item.icon + "' /> | " + item.type + " | " + value;
//} //}
......
/* Module de rupture : Selection un article et le met en rupture à 0 dans les stockes: /* 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 */ * Ecran de rechreche d'un article sur le nom et sur le code barre */
var table_article; var table_article;
var dataSet =[] ; var dataSet =[];
var csrftoken; var csrftoken;
// lance la recherche sur le nom des l'article // lance la recherche sur le nom des l'article
function search_table_article(){ function search_table_article() {
table_article.ajax.url('get_list_article?rech='+$("#searchInput").val()).load(); table_article.ajax.url('get_list_article?rech='+$("#searchInput").val()).load();
} }
// Lance la recherche sur les codes barres // 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(); table_article.ajax.url('get_article_byBarcode?rech='+$("#searchInput").val()).load();
} }
// Initialise le table des articles // Initialise le table des articles
$(document).ready(function() { $(document).ready(function() {
table_article = $('#tableArticle').DataTable( { table_article = $('#tableArticle').DataTable({
"ajax": { "ajax": {
"url": "get_list_article?rech=", "url": "get_list_article?rech=",
"data": "" "data": ""
}, },
"columns":[ "columns":[
{ {
data:"image_small", data:"image_small",
"title":"Photo", "title":"Photo",
"render": function (data, type, full, meta) { "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">' debut = '<button id="page1" type="button" data-toggle="modal" data-target=".modal" data-remote=' + full.id + ' class="btn btn-primary">';
fin = "</button>" 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){
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%"}, "title":"Unité", "width":"5%"},
{data:"reception_status", {data:"reception_status",
"title":"Rupture", "className":"dt-body-center", "title":"Rupture", "className":"dt-body-center",
"render": function (data, type, full, meta) { "render": function (data, type, full, meta) {
if (full.qty_available > 0 ) { if (full.qty_available > 0) {
return "<div><button id='bt_change' href='#'>Rupture</button></div>"; return "<div><button id='bt_change' href='#'>Rupture</button></div>";
} else{ } else {
return "<div>--</div>"; 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 //barcode-reader
$(document).ready(function() { $(document).ready(function() {
var pressed = false; var pressed = false;
var chars = []; var chars = [];
$(window).keypress(function(e) { $(window).keypress(function(e) {
if (e.which >= 48 && e.which <= 57) { if (e.which >= 48 && e.which <= 57) {
chars.push(String.fromCharCode(e.which)); chars.push(String.fromCharCode(e.which));
} }
if (pressed == false) { if (pressed == false) {
setTimeout(function(){ setTimeout(function() {
if (chars.length >= 13) { if (chars.length >= 13) {
var barcode = chars.join(""); var barcode = chars.join("");
if (!isNaN(barcode)) { if (!isNaN(barcode)) {
chars = []; chars = [];
pressed = false; pressed = false;
search_article_byBarcode(); search_article_byBarcode();
} }
} }
},300); }, 300);
} }
pressed = true; pressed = true;
}); });
}); });
$(document).ready(function() { $(document).ready(function() {
csrftoken = getCookie('csrftoken'); csrftoken = getCookie('csrftoken');
}); });
// Lancement de la rupture sur l'article choisie // 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] }; var jIdArcticle = { 'idArticle': selArctileData.id, 'uom_id' : selArctileData.uom_id[0] };
$.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } }); $.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } });
$.ajax({ $.ajax({
type: "PUT", type: "PUT",
url: "set_rupture" , url: "set_rupture",
//dataType: "json", //dataType: "json",
traditional: true, traditional: true,
contentType: "application/json; charset=utf-8", contentType: "application/json; charset=utf-8",
data: JSON.stringify(jIdArcticle), data: JSON.stringify(jIdArcticle),
success: function(data) { success: function(data) {
document.location.href = "/stock/listArticleBreaking"; document.location.href = "/stock/listArticleBreaking";
}, },
error: function(resultat, statut, erreur) { error: function(resultat, statut, erreur) {
alert('Erreur' + erreur); alert('Erreur' + erreur);
} }
}); });
} }
var selArctileData; var selArctileData;
// Fenetre de validation sur l'article // Fenetre de validation sur l'article
$(document).on('click', 'button#bt_change', function () { $(document).on('click', 'button#bt_change', function () {
var row = table_article.row($(this).parents('tr')); var row = table_article.row($(this).parents('tr'));
...@@ -160,11 +169,11 @@ $(document).on('click', 'button#bt_change', function () { ...@@ -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="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>'; 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 - "); openModal(html, ruptureArticle, " - Ok - ");
} ); });
/* Module de rupture : Selection un article et le met en rupture à 0 dans les stockes: /* 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 */ * Ecran de rechreche d'un article sur le nom et sur le code barre */
// Initialise le table des articles // Initialise le table des articles
$(document).ready(function() { $(document).ready(function() {
table_article = $('#tableArticle').DataTable( { table_article = $('#tableArticle').DataTable({
"ajax": { "ajax": {
"url": "get_saleWitheNotSale", "url": "get_saleWitheNotSale",
"data": "" "data": ""
}, },
"columns":[ "columns":[
{data:"name", "title":"Article","width": "50%"}, {data:"name", "title":"Article", "width": "50%"},
{data:"qty", "title":"Qt. en vendu", "width":"15%" {data:"qty", "title":"Qt. en vendu", "width":"15%"
}, },
{data:"daySale", "title":"Jours de vente", "width":"15%" {data:"daySale", "title":"Jours de vente", "width":"15%"
} }
], ],
"searching": true, "searching": true,
"order": [[ 2, "desc" ]], "order": [
"iDisplayLength": 50, [
"language": { 2,
"emptyTable": "Pas de donnée", "desc"
"info": "Affiché : lignes _START_ à _END_ sur _TOTAL_", ]
"infoEmpty": "Affiché : 0 ligne", ],
"infoFiltered": "(filtré de _MAX_ lignes au total)", "iDisplayLength": 50,
"thousands": ",", "language": {
"lengthMenu": "Afficher _MENU_ lignes", "emptyTable": "Pas de donnée",
"loadingRecords": "Loading...", "info": "Affiché : lignes _START_ à _END_ sur _TOTAL_",
"processing": "Processing...", "infoEmpty": "Affiché : 0 ligne",
"search": "Rechercher un article :", "infoFiltered": "(filtré de _MAX_ lignes au total)",
"searchPlaceholder": "Référence, nom du fournisseur...", "thousands": ",",
"zeroRecords": "Aucun résultat", "lengthMenu": "Afficher _MENU_ lignes",
"paginate": { "loadingRecords": "Loading...",
"first": "Premier", "processing": "Processing...",
"last": "Dernier", "search": "Rechercher un article :",
"next": "Suivant", "searchPlaceholder": "Référence, nom du fournisseur...",
"previous": "Precedant" "zeroRecords": "Aucun résultat",
}, "paginate": {
"aria": { "first": "Premier",
"sortAscending": ": activate to sort column ascending", "last": "Dernier",
"sortDescending": ": activate to sort column descending" "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; var csrftoken;
$(document).ready(function() { $(document).ready(function() {
csrftoken = getCookie('csrftoken'); csrftoken = getCookie('csrftoken');
}); });
// Lancement de la rupture sur l'article choisie // Lancement de la rupture sur l'article choisie
function ruptureArticle(){ function ruptureArticle() {
var jIdArcticle = { 'idArticle': selArctileData.id , 'uom_id' : selArctileData.uom_id }; var jIdArcticle = { 'idArticle': selArctileData.id, 'uom_id' : selArctileData.uom_id };
actionButton("set_rupture",jIdArcticle, "/stock/stockQuantLastSale");
}; actionButton("set_rupture", jIdArcticle, "/stock/stockQuantLastSale");
function archiveArticle(){ }
function archiveArticle() {
var jIdArcticle = { 'idArticle': selArctileData.id}; var jIdArcticle = { 'idArticle': selArctileData.id};
actionButton("set_archive", jIdArcticle, "/stock/stockQuantLastSale"); actionButton("set_archive", jIdArcticle, "/stock/stockQuantLastSale");
}; }
function dontPurchase(){ function dontPurchase() {
var jIdArcticle = { 'idArticle': selArctileData.id}; var jIdArcticle = { 'idArticle': selArctileData.id};
actionButton("set_dontPurchase", jIdArcticle, "/stock/stockQuantLastSale"); actionButton("set_dontPurchase", jIdArcticle, "/stock/stockQuantLastSale");
}; }
function actionButton (vUrl,jIdArcticle, followPage){ function actionButton (vUrl, jIdArcticle, followPage) {
$.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } }); $.ajaxSetup({ headers: { "X-CSRFToken": csrftoken } });
$.ajax({ $.ajax({
type: "PUT", type: "PUT",
url: vUrl , url: vUrl,
//dataType: "json", //dataType: "json",
traditional: true, traditional: true,
contentType: "application/json; charset=utf-8", contentType: "application/json; charset=utf-8",
data: JSON.stringify(jIdArcticle), data: JSON.stringify(jIdArcticle),
success: function(data) { success: function(data) {
document.location.href = followPage; document.location.href = followPage;
}, },
error: function(resultat, statut, erreur) { error: function(resultat, statut, erreur) {
alert('Erreur' + erreur); alert('Erreur' + erreur);
} }
}); });
} }
var selArctileData; var selArctileData;
// Fenetre de validation sur l'article // Fenetre de validation sur l'article
$(document).on('click', 'button#bt_change', function () { $(document).on('click', 'button#bt_change', function () {
var row = table_article.row($(this).parents('tr')); var row = table_article.row($(this).parents('tr'));
var data = row.data(); var data = row.data();
html ='<div id="askTitle" >Vous êtes sur que cet article est en rupture de stock ? </div>'; 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>'; 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 - "); 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 row = table_article.row($(this).parents('tr'));
var data = row.data(); var data = row.data();
html ='<div id="askTitle" >Vous êtes sur que cet article doit être archivée ? </div>'; 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>'; 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 - "); openModal(html, archiveArticle, " - Ok - ");
} ); });
$(document).on('click', '#bt_dontPurchase', function () { $(document).on('click', '#bt_dontPurchase', function () {
if (!this.checked){ if (!this.checked) {
var row = table_article.row($(this).parents('tr')); var row = table_article.row($(this).parents('tr'));
var data = row.data(); 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>'; html ='<div id="askTitle" >Vous êtes sur que cet article ne doit plus être acheter ? </div>';
selArctileData = data ; html += '<div id="showData" ><div id="articleName" >'+data.name+'</div><div id="articleQty" >'+data.stockqt+ ' - '+data.uom_id + '</div></div>';
openModal(html, dontPurchase, " - Ok - "); selArctileData = data;
this.checked = true openModal(html, dontPurchase, " - Ok - ");
}else{ this.checked = true;
this.checked = false } else {
this.checked = false;
} }
} ); });
......
...@@ -3,59 +3,71 @@ try { ...@@ -3,59 +3,71 @@ try {
m_sel = $('[name="mm"]'), m_sel = $('[name="mm"]'),
j_sel = $('[name="jj"]'), j_sel = $('[name="jj"]'),
birthdate = $('[name="birthdate"]'), birthdate = $('[name="birthdate"]'),
save_btn = $('#save') save_btn = $('#save');
var make_save_button_active = function() { var make_save_button_active = function() {
if (! save_btn.hasClass('btn--primary')) { if (! save_btn.hasClass('btn--primary')) {
save_btn.addClass('btn--primary') save_btn.addClass('btn--primary');
save_btn.css({'cursor':'pointer'}) save_btn.css({'cursor':'pointer'});
} }
} };
var update_birthdate = function() { var update_birthdate = function() {
birthdate.val(y_sel.val() + '-' + m_sel.val() + '-' + j_sel.val()) birthdate.val(y_sel.val() + '-' + m_sel.val() + '-' + j_sel.val());
make_save_button_active() make_save_button_active();
} };
var init_birthdate_selects = function() {
let [
y,
m,
d
] = birthdate.val().split('-');
var init_birthdate_selects = function(){ var now = new Date();
let [y,m,d] = birthdate.val().split('-') 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--) { for (var i=100; i>0; i--) {
var opt = $('<option>').val(end_year-i).text(end_year-i) var opt = $('<option>').val(end_year-i)
if (end_year-i == y) opt.prop('selected', true) .text(end_year-i);
opt.appendTo(y_sel)
if (end_year-i == y) opt.prop('selected', true);
opt.appendTo(y_sel);
} }
for (var k=1; k<=12; k++) { for (var k=1; k<=12; k++) {
let mth = k.pad(2) let mth = k.pad(2);
var opt = $('<option>').val(mth).text(mth) var opt = $('<option>').val(mth)
if (m == mth) opt.prop('selected', true) .text(mth);
opt.appendTo(m_sel)
if (m == mth) opt.prop('selected', true);
opt.appendTo(m_sel);
} }
for (var l=1; l<=31; l++) { for (var l=1; l<=31; l++) {
let day = l.pad(2) let day = l.pad(2);
var opt = $('<option>').val(day).text(day) var opt = $('<option>').val(day)
if (d == day) opt.prop('selected', true) .text(day);
opt.appendTo(j_sel)
if (d == day) opt.prop('selected', true);
opt.appendTo(j_sel);
} }
y_sel.change(update_birthdate) y_sel.change(update_birthdate);
m_sel.change(update_birthdate) m_sel.change(update_birthdate);
j_sel.change(update_birthdate) j_sel.change(update_birthdate);
} };
var save_data = function() { var save_data = function() {
//Transmit only what has been changed //Transmit only what has been changed
var changed = {} var changed = {};
for (attr in original) { for (attr in original) {
var current_val = $('[name="' + attr + '"]').val() var current_val = $('[name="' + attr + '"]').val();
if (attr == 'sex') { if (attr == 'sex') {
current_val = $('[name="' + attr + '"]:checked').val() current_val = $('[name="' + attr + '"]:checked').val();
} }
if (current_val.trim() != original[attr]) { if (current_val.trim() != original[attr]) {
if (! (original[attr] == 'False' && current_val.length ==0)) if (! (original[attr] == 'False' && current_val.length ==0))
changed[attr] = current_val.trim() changed[attr] = current_val.trim();
} }
} }
// console.log(changed) // console.log(changed)
...@@ -63,9 +75,9 @@ try { ...@@ -63,9 +75,9 @@ try {
if ('firstname' in changed || 'lastname' in changed) { if ('firstname' in changed || 'lastname' in changed) {
changed['name'] = $('[name="firstname"]').val() changed['name'] = $('[name="firstname"]').val()
+ name_sep + name_sep
+ $('[name="lastname"]').val() + $('[name="lastname"]').val();
} }
delete changed['email'] delete changed['email'];
post_form( post_form(
'/website/update_info_perso', '/website/update_info_perso',
changed, changed,
...@@ -73,38 +85,39 @@ try { ...@@ -73,38 +85,39 @@ try {
if (typeof result.res.process != "undefined" && if (typeof result.res.process != "undefined" &&
typeof result.res.process.update != "undefined" && typeof result.res.process.update != "undefined" &&
result.res.process.update == true) { result.res.process.update == true) {
save_btn.removeClass('btn--primary') save_btn.removeClass('btn--primary');
save_btn.css({'cursor':'default'}) save_btn.css({'cursor':'default'});
for (attr in changed) { for (attr in changed) {
if (attr != 'name') if (attr != 'name')
original[attr] = changed[attr] original[attr] = changed[attr];
} }
alert('Modifications enregistrées !') alert('Modifications enregistrées !');
} else { } else {
alert('Une erreur est intervenue pendant l\'enregistrement') alert('Une erreur est intervenue pendant l\'enregistrement');
} }
} }
) );
} else { } else {
alert('Aucune modification significative détectée') alert('Aucune modification significative détectée');
} }
} };
if (typeof original.sex != "undefined") { if (typeof original.sex != "undefined") {
$("#" + original.sex + "_sex").prop('checked', true) $("#" + original.sex + "_sex").prop('checked', true);
} }
init_birthdate_selects() init_birthdate_selects();
$('input').keyup(make_save_button_active) $('input').keyup(make_save_button_active);
save_btn.click(function() { save_btn.click(function() {
if ($(this).hasClass('btn--primary') && is_time_to('save_perso_data')) { if ($(this).hasClass('btn--primary') && is_time_to('save_perso_data')) {
save_data(); save_data();
} }
}) });
} catch(error) { } catch (error) {
err_obj = {msg: error.name + ' : ' + error.message, ctx: 'info_perso'} err_obj = {msg: error.name + ' : ' + error.message, ctx: 'info_perso'};
report_JS_error(error, 'website') 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