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:[
...@@ -10,7 +10,7 @@ function init_datatable() { ...@@ -10,7 +10,7 @@ function init_datatable() {
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"},
...@@ -21,42 +21,47 @@ function init_datatable() { ...@@ -21,42 +21,47 @@ function init_datatable() {
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: [
[
1,
"asc"
]
],
iDisplayLength: 25, iDisplayLength: 25,
language: {url : '/static/js/datatables/french.json'} language: {url : '/static/js/datatables/french.json'}
}) });
} }
function go_to_inventory() { function go_to_inventory() {
openModal() openModal();
var clicked = $(this) var clicked = $(this);
var row_data = shelfs_table.row(clicked.parents('tr')).data() var row_data = shelfs_table.row(clicked.parents('tr')).data();
// Use local storage to pass data to next page // Use local storage to pass data to next page
if (Modernizr.localstorage) { if (Modernizr.localstorage) {
var stored_list = JSON.parse(localStorage.getItem('custom_list_' + row_data.id)) var stored_list = JSON.parse(localStorage.getItem('custom_list_' + row_data.id));
// Set local storage if key doesn't exist // Set local storage if key doesn't exist
if (stored_list == null) { if (stored_list == null) {
localStorage.setItem("custom_list_" + row_data.id , JSON.stringify(row_data)) localStorage.setItem("custom_list_" + row_data.id, JSON.stringify(row_data));
} }
} }
document.location.href = "custom_list_inventory/" + row_data.id document.location.href = "custom_list_inventory/" + row_data.id;
} }
$(document).ready(function() { $(document).ready(function() {
console.log(lists) console.log(lists);
shelfs_table = init_datatable() shelfs_table = init_datatable();
$(document).on('click', 'button.do_inventory', go_to_inventory) $(document).on('click', 'button.do_inventory', go_to_inventory);
}) });
var coop_page = $('#coop_page'); 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() {
...@@ -22,20 +27,21 @@ function display_current_coop_form() { ...@@ -22,20 +27,21 @@ function display_current_coop_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.hide();
chgt_shift_btn.off('click',open_shift_choice); chgt_shift_btn.off('click', open_shift_choice);
form.find('[name="firstname"]').val(current_coop.firstname); form.find('[name="firstname"]').val(current_coop.firstname);
form.find('[name="lastname"]').val(current_coop.lastname); form.find('[name="lastname"]').val(current_coop.lastname);
if (m_barcode.length > 0 && typeof current_coop.m_barcode != "undefined") { if (m_barcode.length > 0 && typeof current_coop.m_barcode != "undefined") {
m_barcode.val(current_coop.m_barcode) m_barcode.val(current_coop.m_barcode);
} }
//console.log(current_coop) //console.log(current_coop)
if (sex.length > 0 && typeof current_coop.sex != "undefined") { if (sex.length > 0 && typeof current_coop.sex != "undefined") {
$("#" + current_coop.sex + "_sex").prop('checked', true) $("#" + current_coop.sex + "_sex").prop('checked', true);
} }
// form.find('[name="barcode_base"]').val(current_coop.barcode_base); // form.find('[name="barcode_base"]').val(current_coop.barcode_base);
...@@ -64,16 +70,17 @@ function display_current_coop_form() { ...@@ -64,16 +70,17 @@ function display_current_coop_form() {
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) { if (phone_input.length > 0) {
phone_input.val(current_coop.phone || '') phone_input.val(current_coop.phone || '');
} }
// Checks // Checks
form.find('[name="checks_nb"]').hide(); form.find('[name="checks_nb"]').hide();
form.find('[id="checks_nb_label"]').hide(); form.find('[id="checks_nb_label"]').hide();
$('#checks').hide(); $('#checks').hide();
var check_details = $('#checks').find('.check_details'); var check_details = $('#checks').find('.check_details');
$(check_details).html(''); $(check_details).html('');
// Display checks number if paid by checks // Display checks number if paid by checks
if (current_coop.payment_meaning == "ch") { if (current_coop.payment_meaning == "ch") {
...@@ -93,10 +100,12 @@ function display_current_coop_form() { ...@@ -93,10 +100,12 @@ function display_current_coop_form() {
if (current_coop.shift_template) { if (current_coop.shift_template) {
var st = current_coop.shift_template.data; var st = current_coop.shift_template.data;
form.find('[name="week"]').val(weeks_name[st.week]); form.find('[name="week"]').val(weeks_name[st.week]);
form.find('[name="day"]').val(st.day); form.find('[name="day"]').val(st.day);
form.find('[name="hour"]').val(st.begin); form.find('[name="hour"]').val(st.begin);
var place = st.place; var place = st.place;
if (place == mag_place_string) { if (place == mag_place_string) {
place = 'Magasin'; place = 'Magasin';
} else if (place == office_place_string) { } else if (place == office_place_string) {
...@@ -112,17 +121,19 @@ function display_current_coop_form() { ...@@ -112,17 +121,19 @@ function display_current_coop_form() {
if (show_change_shift == true) { if (show_change_shift == true) {
chgt_shift_btn.show(); chgt_shift_btn.show();
chgt_shift_btn.on('click',open_shift_choice); chgt_shift_btn.on('click', open_shift_choice);
} }
if (typeof(coop_page) != "undefined"){coop_page.show();} if (typeof(coop_page) != "undefined") {
coop_page.show();
}
} }
$('#payment_meaning').change(function(){ $('#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,22 +7,22 @@ let vform = $('#coop_validation_form'), ...@@ -7,22 +7,22 @@ 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();
} }
...@@ -36,25 +36,32 @@ function show_coop_form() { ...@@ -36,25 +36,32 @@ 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'){
if (fname == 'valider') {
var form_data = new FormData(vform.get(0)), var form_data = new FormData(vform.get(0)),
has_empty_values = false; has_empty_values = false;
if (sex.length > 0) { 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()) { for (var pair of form_data.entries()) {
let val = pair[1], let val = pair[1],
key = pair[0] key = pair[0];
if ($('input[name="' + key +'"]').get(0).hasAttribute('required') && val.length == 0) {
has_empty_values = true if ($('input[name="' + key +'"]').get(0)
.hasAttribute('required') && val.length == 0) {
has_empty_values = true;
} }
} }
...@@ -62,27 +69,35 @@ function process_form_submission(event){ ...@@ -62,27 +69,35 @@ function process_form_submission(event){
if (has_empty_values == true) { if (has_empty_values == true) {
alert('Vous devez remplir tous les champs pour valider.'); alert('Vous devez remplir tous les champs pour valider.');
} else { } else {
form_data.set('firstname', form_data.set(
vform.find('input[name="firstname"]').val().toFormatedFirstName()); 'firstname',
form_data.set('lastname', vform.find('input[name="firstname"]').val()
vform.find('input[name="lastname"]').val().toFormatedLastName()); .toFormatedFirstName()
);
form_data.set(
'lastname',
vform.find('input[name="lastname"]').val()
.toFormatedLastName()
);
form_data.set('odoo_id', current_coop.odoo_id); form_data.set('odoo_id', current_coop.odoo_id);
form_data.set('shift_template', JSON.stringify(current_coop.shift_template)); 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('shares_euros', vform.find('input[name="shares_euros"]').val());
form_data.set('email',current_coop._id); form_data.set('email', current_coop._id);
form_data.set('shares_nb',current_coop.shares_nb); form_data.set('shares_nb', current_coop.shares_nb);
form_data.set('checks_nb', current_coop.checks_nb); form_data.set('checks_nb', current_coop.checks_nb);
form_data.set('country', current_coop.country); form_data.set('country', current_coop.country);
if (m_barcode.length > 0) { if (m_barcode.length > 0) {
form_data.set('m_barcode', current_coop.m_barcode) form_data.set('m_barcode', current_coop.m_barcode);
} }
openModal() openModal();
post_form('/members/coop_validated_data',form_data, post_form(
function(err,result){ '/members/coop_validated_data', form_data,
function(err, result) {
closeModal(); closeModal();
if (!err) { 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();
...@@ -91,24 +106,28 @@ function process_form_submission(event){ ...@@ -91,24 +106,28 @@ function process_form_submission(event){
} }
}); }
);
} }
} 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(
'/members/coop_warning_msg', data,
function(err, result) {
closeModal(); closeModal();
if (!err) { if (!err) {
$('#main_content').remove() $('#main_content').remove();
display_msg_box('Message enregistré ! Le bureau des membres est averti.'); 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,11 +44,13 @@ ...@@ -39,11 +44,13 @@
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) {
...@@ -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));
}); });
}); });
......
...@@ -37,20 +37,23 @@ ...@@ -37,20 +37,23 @@
reset(); reset();
} }
$(actionCheckboxes).prop("checked", checked) $(actionCheckboxes).prop("checked", checked)
.parent().parent().toggleClass(options.selectedClass, checked); .parent()
.parent()
.toggleClass(options.selectedClass, checked);
}, },
updateCounter = function() { updateCounter = function() {
var sel = $(actionCheckboxes).filter(":checked").length; var sel = $(actionCheckboxes).filter(":checked").length;
// data-actions-icnt is defined in the generated HTML // data-actions-icnt is defined in the generated HTML
// and contains the total amount of objects in the queryset // and contains the total amount of objects in the queryset
var actions_icnt = $('.action-counter').data('actionsIcnt'); var actions_icnt = $('.action-counter').data('actionsIcnt');
$(options.counterContainer).html(interpolate(
ngettext('%(sel)s of %(cnt)s selected', '%(sel)s of %(cnt)s selected', sel), { $(options.counterContainer).html(interpolate(ngettext('%(sel)s of %(cnt)s selected', '%(sel)s of %(cnt)s selected', sel), {
sel: sel, sel: sel,
cnt: actions_icnt cnt: actions_icnt
}, true)); }, true));
$(options.allToggle).prop("checked", function() { $(options.allToggle).prop("checked", function() {
var value; var value;
if (sel === actionCheckboxes.length) { if (sel === actionCheckboxes.length) {
value = true; value = true;
showQuestion(); showQuestion();
...@@ -58,20 +61,26 @@ ...@@ -58,20 +61,26 @@
value = false; value = false;
clearAcross(); clearAcross();
} }
return value; 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) {
$(this).parent()
.parent()
.toggleClass(options.selectedClass);
updateCounter(); updateCounter();
if ($(options.acrossInput).val() === 1) { if ($(options.acrossInput).val() === 1) {
showClear(); showClear();
} }
}); });
$(options.allToggle).show().click(function() { $(options.allToggle).show()
.click(function() {
checker($(this).prop("checked")); checker($(this).prop("checked"));
updateCounter(); updateCounter();
}); });
...@@ -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,15 +113,21 @@ ...@@ -100,15 +113,21 @@
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;
...@@ -119,13 +138,19 @@ ...@@ -119,13 +138,19 @@
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,6 +180,7 @@ function findPosY(obj) { ...@@ -169,6 +180,7 @@ 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":
...@@ -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;
} }
...@@ -24,8 +24,10 @@ ...@@ -24,8 +24,10 @@
var updateElementIndex = function(el, prefix, ndx) { var updateElementIndex = function(el, prefix, ndx) {
var id_regex = new RegExp("(" + prefix + "-(\\d+|__prefix__))"); var id_regex = new RegExp("(" + prefix + "-(\\d+|__prefix__))");
var replacement = prefix + "-" + ndx; var replacement = prefix + "-" + ndx;
if ($(el).prop("for")) { if ($(el).prop("for")) {
$(el).prop("for", $(el).prop("for").replace(id_regex, replacement)); $(el).prop("for", $(el).prop("for")
.replace(id_regex, replacement));
} }
if (el.id) { if (el.id) {
el.id = el.id.replace(id_regex, replacement); el.id = el.id.replace(id_regex, replacement);
...@@ -40,28 +42,34 @@ ...@@ -40,28 +42,34 @@
// only show the add button if we are allowed to add more items, // only show the add button if we are allowed to add more items,
// note that max_num = None translates to a blank string. // note that max_num = None translates to a blank string.
var showAddButton = maxForms.val() === '' || (maxForms.val() - totalForms.val()) > 0; var showAddButton = maxForms.val() === '' || (maxForms.val() - totalForms.val()) > 0;
$this.each(function(i) { $this.each(function(i) {
$(this).not("." + options.emptyCssClass).addClass(options.formCssClass); $(this).not("." + options.emptyCssClass)
.addClass(options.formCssClass);
}); });
if ($this.length && showAddButton) { if ($this.length && showAddButton) {
var addButton = options.addButton; var addButton = options.addButton;
if (addButton === null) { if (addButton === null) {
if ($this.prop("tagName") === "TR") { if ($this.prop("tagName") === "TR") {
// If forms are laid out as table rows, insert the // If forms are laid out as table rows, insert the
// "add" button in a new table row: // "add" button in a new table row:
var numCols = this.eq(-1).children().length; var numCols = this.eq(-1).children().length;
$parent.append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + '"><a href="#">' + options.addText + "</a></tr>"); $parent.append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + '"><a href="#">' + options.addText + "</a></tr>");
addButton = $parent.find("tr:last a"); addButton = $parent.find("tr:last a");
} else { } else {
// Otherwise, insert it immediately after the last form: // Otherwise, insert it immediately after the last form:
$this.filter(":last").after('<div class="' + options.addCssClass + '"><a href="#">' + options.addText + "</a></div>"); $this.filter(":last").after('<div class="' + options.addCssClass + '"><a href="#">' + options.addText + "</a></div>");
addButton = $this.filter(":last").next().find("a"); addButton = $this.filter(":last").next()
.find("a");
} }
} }
addButton.click(function(e) { addButton.click(function(e) {
e.preventDefault(); e.preventDefault();
var template = $("#" + options.prefix + "-empty"); var template = $("#" + options.prefix + "-empty");
var row = template.clone(true); var row = template.clone(true);
row.removeClass(options.emptyCssClass) row.removeClass(options.emptyCssClass)
.addClass(options.formCssClass) .addClass(options.formCssClass)
.attr("id", options.prefix + "-" + nextIndex); .attr("id", options.prefix + "-" + nextIndex);
...@@ -100,9 +108,13 @@ ...@@ -100,9 +108,13 @@
if (options.removed) { if (options.removed) {
options.removed(row); options.removed(row);
} }
$(document).trigger('formset:removed', [row, options.prefix]); $(document).trigger('formset:removed', [
row,
options.prefix
]);
// Update the TOTAL_FORMS form count. // Update the TOTAL_FORMS form count.
var forms = $("." + options.formCssClass); var forms = $("." + options.formCssClass);
$("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length); $("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length);
// Show add button again once we drop below max // Show add button again once we drop below max
if ((maxForms.val() === '') || (maxForms.val() - forms.length) > 0) { if ((maxForms.val() === '') || (maxForms.val() - forms.length) > 0) {
...@@ -114,18 +126,24 @@ ...@@ -114,18 +126,24 @@
var updateElementCallback = function() { var updateElementCallback = function() {
updateElementIndex(this, options.prefix, i); updateElementIndex(this, options.prefix, i);
}; };
for (i = 0, formCount = forms.length; i < formCount; i++) { for (i = 0, formCount = forms.length; i < formCount; i++) {
updateElementIndex($(forms).get(i), options.prefix, i); updateElementIndex($(forms).get(i), options.prefix, i);
$(forms.get(i)).find("*").each(updateElementCallback); $(forms.get(i)).find("*")
.each(updateElementCallback);
} }
}); });
// If a post-add callback was supplied, call it with the added form: // If a post-add callback was supplied, call it with the added form:
if (options.added) { if (options.added) {
options.added(row); options.added(row);
} }
$(document).trigger('formset:added', [row, options.prefix]); $(document).trigger('formset:added', [
row,
options.prefix
]);
}); });
} }
return this; return this;
}; };
...@@ -148,9 +166,13 @@ ...@@ -148,9 +166,13 @@
$.fn.tabularFormset = function(options) { $.fn.tabularFormset = function(options) {
var $rows = $(this); var $rows = $(this);
var alternatingRows = function(row) { var alternatingRows = function(row) {
$($rows.selector).not(".add-row").removeClass("row1 row2") $($rows.selector).not(".add-row")
.filter(":even").addClass("row1").end() .removeClass("row1 row2")
.filter(":odd").addClass("row2"); .filter(":even")
.addClass("row1")
.end()
.filter(":odd")
.addClass("row2");
}; };
var reinitDateTimeShortCuts = function() { var reinitDateTimeShortCuts = function() {
...@@ -167,10 +189,12 @@ ...@@ -167,10 +189,12 @@
if (typeof SelectFilter !== 'undefined') { if (typeof SelectFilter !== 'undefined') {
$('.selectfilter').each(function(index, value) { $('.selectfilter').each(function(index, value) {
var namearr = value.name.split('-'); var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], false); SelectFilter.init(value.id, namearr[namearr.length - 1], false);
}); });
$('.selectfilterstacked').each(function(index, value) { $('.selectfilterstacked').each(function(index, value) {
var namearr = value.name.split('-'); var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], true); SelectFilter.init(value.id, namearr[namearr.length - 1], true);
}); });
} }
...@@ -182,8 +206,10 @@ ...@@ -182,8 +206,10 @@
input = field.find('input, select, textarea'), input = field.find('input, select, textarea'),
dependency_list = input.data('dependency_list') || [], dependency_list = input.data('dependency_list') || [],
dependencies = []; dependencies = [];
$.each(dependency_list, function(i, field_name) { $.each(dependency_list, function(i, field_name) {
dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea').attr('id')); dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea')
.attr('id'));
}); });
if (dependencies.length) { if (dependencies.length) {
input.prepopulate(dependencies, input.attr('maxlength')); input.prepopulate(dependencies, input.attr('maxlength'));
...@@ -215,9 +241,12 @@ ...@@ -215,9 +241,12 @@
$.fn.stackedFormset = function(options) { $.fn.stackedFormset = function(options) {
var $rows = $(this); var $rows = $(this);
var updateInlineLabel = function(row) { var updateInlineLabel = function(row) {
$($rows.selector).find(".inline_label").each(function(i) { $($rows.selector).find(".inline_label")
.each(function(i) {
var count = i + 1; var count = i + 1;
$(this).html($(this).html().replace(/(#\d+)/g, "#" + count));
$(this).html($(this).html()
.replace(/(#\d+)/g, "#" + count));
}); });
}; };
...@@ -234,10 +263,12 @@ ...@@ -234,10 +263,12 @@
if (typeof SelectFilter !== "undefined") { if (typeof SelectFilter !== "undefined") {
$(".selectfilter").each(function(index, value) { $(".selectfilter").each(function(index, value) {
var namearr = value.name.split('-'); var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], false); SelectFilter.init(value.id, namearr[namearr.length - 1], false);
}); });
$(".selectfilterstacked").each(function(index, value) { $(".selectfilterstacked").each(function(index, value) {
var namearr = value.name.split('-'); var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], true); SelectFilter.init(value.id, namearr[namearr.length - 1], true);
}); });
} }
...@@ -249,8 +280,10 @@ ...@@ -249,8 +280,10 @@
input = field.find('input, select, textarea'), input = field.find('input, select, textarea'),
dependency_list = input.data('dependency_list') || [], dependency_list = input.data('dependency_list') || [],
dependencies = []; dependencies = [];
$.each(dependency_list, function(i, field_name) { $.each(dependency_list, function(i, field_name) {
dependencies.push('#' + row.find('.form-row .field-' + field_name).find('input, select, textarea').attr('id')); dependencies.push('#' + row.find('.form-row .field-' + field_name).find('input, select, textarea')
.attr('id'));
}); });
if (dependencies.length) { if (dependencies.length) {
input.prepopulate(dependencies, input.attr('maxlength')); input.prepopulate(dependencies, input.attr('maxlength'));
...@@ -282,7 +315,8 @@ ...@@ -282,7 +315,8 @@
$(".js-inline-admin-formset").each(function() { $(".js-inline-admin-formset").each(function() {
var data = $(this).data(), var data = $(this).data(),
inlineOptions = data.inlineFormset; inlineOptions = data.inlineFormset;
switch(data.inlineType) {
switch (data.inlineType) {
case "stacked": case "stacked":
$(inlineOptions.name + "-group .inline-related").stackedFormset(inlineOptions.options); $(inlineOptions.name + "-group .inline-related").stackedFormset(inlineOptions.options);
break; break;
......
...@@ -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');
$('form').hide();
if (rData.response.sells_total) { if (rData.response.sells_total) {
var preambule = $('<p>').html('A titre indicatif:') 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 vente_ht = $('<p>').html('Ventes H.T: <strong>' + parseFloat(rData.response.sells_total).toFixed(2) + '</strong> € ');
var tva = $('<p>').html('TVA sur ventes: <strong>' + parseFloat(rData.response.vat_total).toFixed(2) + '</strong> € ') var tva = $('<p>').html('TVA sur ventes: <strong>' + parseFloat(rData.response.vat_total).toFixed(2) + '</strong> € ');
$('body') $('body')
.append(preambule) .append(preambule)
.append(vente_ht) .append(vente_ht)
.append(tva) .append(tva)
.append(download_link) .append(download_link);
} else { } else {
$('body').append(download_link) $('body').append(download_link);
} }
} }
closeWaiting() 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(),
data[key] = {title: elt.closest('.param').find('label')
.text(),
type: elt.get(0).type, type: elt.get(0).type,
value: val} value: val};
} }
post_form('settings', {params: JSON.stringify(data)}, post_form(
function(err,result){ 'settings', {params: JSON.stringify(data)},
function(err, result) {
if (!err) { if (!err) {
var succeeded = false var succeeded = false;
try { try {
if (result.res.save == true) { if (result.res.save == true) {
display_msg_box('Enregistrement réussi !') display_msg_box('Enregistrement réussi !');
succeeded = true succeeded = true;
} }
} catch(e) { } catch (e) {
console.log(e) console.log(e);
} }
if (succeeded == false) display_msg_box('L\'enregistrement a échoué !', 'error') if (succeeded == false) display_msg_box('L\'enregistrement a échoué !', 'error');
} else { } else {
console.log(err) 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) { for (let key in rData.res.settings) {
var param = $(param_template.clone().html()) var param = $(param_template.clone().html());
var input = null var input = null;
let data = rData.res.settings[key] let data = rData.res.settings[key];
param.find('label').text(data.title).attr('for', key)
param.find('label').text(data.title)
.attr('for', key);
if (data.type == 'textarea') { if (data.type == 'textarea') {
param.find('input').remove() param.find('input').remove();
input = param.find('textarea') input = param.find('textarea');
input.attr('name', key).text(data.value) input.attr('name', key).text(data.value);
} else { } else {
param.find('textarea').remove() param.find('textarea').remove();
input = param.find('input') input = param.find('input');
input.attr('name', key).attr('value', data.value) input.attr('name', key).attr('value', data.value);
} }
/* /*
...@@ -59,19 +68,19 @@ function get_module_settings() { ...@@ -59,19 +68,19 @@ function get_module_settings() {
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) { } catch (e) {
console.log(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);
}); });
...@@ -13,7 +13,22 @@ function coop_init_datatable(params,data, cols, action_btn) { ...@@ -13,7 +13,22 @@ function coop_init_datatable(params,data, cols, action_btn) {
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 : [
[
50,
100,
150,
200,
-1
],
[
50,
100,
150,
200,
'Tout'
]
],
pageLength : 50, pageLength : 50,
buttons: buttons, buttons: buttons,
...@@ -22,47 +37,49 @@ function coop_init_datatable(params,data, cols, action_btn) { ...@@ -22,47 +37,49 @@ function coop_init_datatable(params,data, cols, action_btn) {
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){
var line = e
if (typeof e.data == 'object') { if (typeof e.data == 'object') {
line.context = e.data.ctx line.context = e.data.ctx;
line.message = e.data.msg line.message = e.data.msg;
delete e.data delete e.data;
} else { } else {
line.context = '?' line.context = '?';
line.message = e.data line.message = e.data;
} }
data.push(line) data.push(line);
}) });
console.log(data) console.log(data);
results_table = coop_init_datatable(null, data, cols); 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
...@@ -6,18 +6,25 @@ var oidoc = { ...@@ -6,18 +6,25 @@ 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);
}.toString()
}, },
by_completed: { by_completed: {
map: function (doc) { emit(doc.completed); }.toString() map: function (doc) {
emit(doc.completed);
}.toString()
}, },
by_odoo_id: { by_odoo_id: {
map: function (doc) { emit(doc.odoo_id); }.toString() map: function (doc) {
emit(doc.odoo_id);
}.toString()
} }
} }
}; };
// save it // save it
dbc.put(oidoc,function (err, result) {
dbc.put(oidoc, function (err, result) {
if (!err) { if (!err) {
console.log('index enregistré'); console.log('index enregistré');
} else { } else {
......
...@@ -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()
await ifcb.init();
if (ifcb.errors.length > 0) if (ifcb.errors.length > 0)
ifcb.display_last_error() ifcb.display_last_error();
else else
result = ifcb result = ifcb;
// console.log(result.patterns) // console.log(result.patterns)
return result 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) { if (barcode.length >=13) {
barcode = barcode.substring(barcode.length-13) barcode = barcode.substring(barcode.length-13);
search_in_pdt_list(barcode) search_in_pdt_list(barcode);
} else { } else {
console.log($(':focus').attr('type')) console.log($(':focus').attr('type'));
console.log(new Date().getTime() + ' -> '+barcode) 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_input.on('keyup focus', function() {
search_in_pdt_list($(this).val()) search_in_pdt_list($(this).val());
}) });
search_div.on('click', 'li', function() {
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({
......
...@@ -4,7 +4,7 @@ var order = { ...@@ -4,7 +4,7 @@ var order = {
callback_update = false, callback_update = false,
callback_report = false, callback_report = false,
selection_type = null, selection_type = null,
saved_groups = [] saved_groups = [];
/* UTILS */ /* UTILS */
...@@ -38,13 +38,13 @@ function group_goto(i) { ...@@ -38,13 +38,13 @@ function group_goto(i) {
* Set local storage for given order * Set local storage for given order
*/ */
function set_local_storage(order_data) { function set_local_storage(order_data) {
console.log(order_data) console.log(order_data);
if (Modernizr.localstorage) { if (Modernizr.localstorage) {
var stored_order = JSON.parse(localStorage.getItem('order_' + order_data.id)); var stored_order = JSON.parse(localStorage.getItem('order_' + order_data.id));
// Set local storage if key doesn't exist // Set local storage if key doesn't exist
if (stored_order == null) { if (stored_order == null) {
localStorage.setItem("order_" + order_data.id , JSON.stringify(order_data)); localStorage.setItem("order_" + order_data.id, JSON.stringify(order_data));
} }
} }
} }
...@@ -60,8 +60,9 @@ function validatePrices() { ...@@ -60,8 +60,9 @@ function validatePrices() {
var update_data = { var update_data = {
'update_type' : 'br_valid', 'update_type' : 'br_valid',
'orders' : {} 'orders' : {}
} };
update_data.orders[order['id']] = { 'po' : [] }
update_data.orders[order['id']] = { 'po' : [] };
$.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } }); $.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });
$.ajax({ $.ajax({
...@@ -77,7 +78,7 @@ function validatePrices() { ...@@ -77,7 +78,7 @@ function validatePrices() {
reload(); reload();
}, },
error: function() { error: function() {
closeModal() closeModal();
alert('Erreur dans la validation des prix'); alert('Erreur dans la validation des prix');
} }
}); });
...@@ -105,10 +106,10 @@ function validatePrices() { ...@@ -105,10 +106,10 @@ function validatePrices() {
reload(); reload();
}, },
error: function() { error: function() {
closeModal() closeModal();
alert('Erreur dans l\'envoi du rapport.'); alert('Erreur dans l\'envoi du rapport.');
err = {msg: 'Erreur dans l\'envoi du rapport.', ctx: 'validatePrices'} err = {msg: 'Erreur dans l\'envoi du rapport.', ctx: 'validatePrices'};
report_JS_error(err, 'reception') report_JS_error(err, 'reception');
} }
}); });
} }
...@@ -151,25 +152,25 @@ function group_action() { ...@@ -151,25 +152,25 @@ function group_action() {
grouped_orders.push(group_ids); grouped_orders.push(group_ids);
// store grouped orders array // store grouped orders array
localStorage.setItem('grouped_orders' , JSON.stringify(grouped_orders)); localStorage.setItem('grouped_orders', JSON.stringify(grouped_orders));
} }
// Go to products page of order with smallest id // Go to products page of order with smallest id
goto(min_id) goto(min_id);
} else if (pswd == null) { } else if (pswd == null) {
} else { } else {
alert('Mauvais mot de passe !') alert('Mauvais mot de passe !');
} }
} }
$(document).ready(function() { $(document).ready(function() {
// Set date format for DataTable so date ordering can work // Set date format for DataTable so date ordering can work
$.fn.dataTable.moment( 'D/M/Y' ); $.fn.dataTable.moment('D/M/Y');
var saved_grouped_orders = JSON.parse(localStorage.getItem('grouped_orders')); var saved_grouped_orders = JSON.parse(localStorage.getItem('grouped_orders'));
var table_orders = $('#orders').DataTable( { var table_orders = $('#orders').DataTable({
ajax: "get_list_orders", ajax: "get_list_orders",
columns:[ columns:[
{ {
...@@ -177,7 +178,7 @@ $(document).ready(function() { ...@@ -177,7 +178,7 @@ $(document).ready(function() {
title:"Sélectionner", title:"Sélectionner",
className:"dt-body-center", className:"dt-body-center",
render: function (data, type, full, meta) { render: function (data, type, full, meta) {
return '<input type="checkbox" id="select_bc_'+data+'" value="'+data+'">' return '<input type="checkbox" id="select_bc_'+data+'" value="'+data+'">';
}, },
width: "4%", width: "4%",
orderable: false orderable: false
...@@ -222,56 +223,65 @@ $(document).ready(function() { ...@@ -222,56 +223,65 @@ $(document).ready(function() {
} }
], ],
dom: 'rtip', dom: 'rtip',
order: [[ 1, "asc" ]], order: [
[
1,
"asc"
]
],
iDisplayLength: 25, iDisplayLength: 25,
language: {url : '/static/js/datatables/french.json'}, language: {url : '/static/js/datatables/french.json'},
initComplete: function(settings, json) { // After data is loaded initComplete: function(settings, json) { // After data is loaded
// if there are grouped orders // if there are grouped orders
if (saved_grouped_orders != null) { if (saved_grouped_orders != null) {
$('#groups_items').append("<ul>") $('#groups_items').append("<ul>");
// for each group // for each group
for (group of saved_grouped_orders) { for (group of saved_grouped_orders) {
var g = [] var g = [];
// for each order in group // for each order in group
for (group_element_id of group) { for (group_element_id of group) {
// Look for order in datatable // Look for order in datatable
for (var i = 0; i < table_orders.rows().data().length; i++) { for (var i = 0; i < table_orders.rows().data().length; i++) {
if (group_element_id == table_orders.rows(i).data()[0].id) { if (group_element_id == table_orders.rows(i).data()[0].id) {
var order = table_orders.rows(i).data()[0]; var order = table_orders.rows(i).data()[0];
g.push(order)
g.push(order);
// remove raw from table // remove raw from table
table_orders.rows( i ).remove().draw(); table_orders.rows(i).remove()
.draw();
} }
} }
} }
// Display group // Display group
document.getElementById("container_groups").hidden = false; document.getElementById("container_groups").hidden = false;
var group_row = "<ul> <li> Commandes de " var group_row = "<ul> <li> Commandes de ";
for (i in g) { for (i in g) {
if (i == g.length-1) { // last element of list if (i == g.length-1) { // last element of list
group_row += "<b>" + g[i].partner + "</b> du " + g[i].date_order + " : " group_row += "<b>" + g[i].partner + "</b> du " + g[i].date_order + " : ";
} else { } else {
group_row += "<b>" + g[i].partner + "</b> du " + g[i].date_order + ", " group_row += "<b>" + g[i].partner + "</b> du " + g[i].date_order + ", ";
} }
} }
if (g[0].reception_status == 'False') { if (g[0].reception_status == 'False') {
group_row += "<button class='btn--primary' onClick='group_goto(" + saved_groups.length + ")'>Compter les produits</button>" group_row += "<button class='btn--primary' onClick='group_goto(" + saved_groups.length + ")'>Compter les produits</button>";
} else { } else {
group_row += "<button class='btn--success' onClick='group_goto(" + saved_groups.length + ")'>Mettre à jour les prix</button>" group_row += "<button class='btn--success' onClick='group_goto(" + saved_groups.length + ")'>Mettre à jour les prix</button>";
} }
group_row += "</li>" group_row += "</li>";
$('#groups_items').append(group_row) $('#groups_items').append(group_row);
saved_groups.push(g) saved_groups.push(g);
} }
} }
$('#groups_items').append("</ul>") $('#groups_items').append("</ul>");
} }
}); });
...@@ -308,7 +318,7 @@ $(document).ready(function() { ...@@ -308,7 +318,7 @@ $(document).ready(function() {
$(this.parentElement).toggleClass('selected'); $(this.parentElement).toggleClass('selected');
document.getElementById("select_bc_"+row_data.id).checked = false; document.getElementById("select_bc_"+row_data.id).checked = false;
alert('Vous ne pouvez pas grouper des commandes qui ont un statut différent.') alert('Vous ne pouvez pas grouper des commandes qui ont un statut différent.');
} else { } else {
//display 'group action' button //display 'group action' button
document.getElementById("group_action").hidden = false; document.getElementById("group_action").hidden = false;
...@@ -338,12 +348,12 @@ $(document).ready(function() { ...@@ -338,12 +348,12 @@ $(document).ready(function() {
// Use local storage to pass order data to next page // Use local storage to pass order data to next page
set_local_storage(row_data); set_local_storage(row_data);
goto(row_data.id) goto(row_data.id);
} }
} }
// If 'update prices' step, click on before-last cell -> validate all prices // If 'update prices' step, click on before-last cell -> validate all prices
else if (this.cellIndex == 3 && row_data.reception_status == "qty_valid") { else if (this.cellIndex == 3 && row_data.reception_status == "qty_valid") {
order = row_data order = row_data;
openModal($('#modal_no_prices').html(), validatePrices, 'Confirmer', false); openModal($('#modal_no_prices').html(), validatePrices, 'Confirmer', false);
} }
}); });
...@@ -353,7 +363,7 @@ $(document).ready(function() { ...@@ -353,7 +363,7 @@ $(document).ready(function() {
table_orders table_orders
.search(jQuery.fn.DataTable.ext.type.search.string(this.value)) .search(jQuery.fn.DataTable.ext.type.search.string(this.value))
.draw(); .draw();
} ); });
}); });
...@@ -8,7 +8,7 @@ Informations affichées : ...@@ -8,7 +8,7 @@ Informations affichées :
var parent_location = '/shelfs', var parent_location = '/shelfs',
shelf, shelf,
table_products, table_products,
search_chars = [] search_chars = [];
/* UTILS */ /* UTILS */
...@@ -18,17 +18,17 @@ function round(value, decimals) { ...@@ -18,17 +18,17 @@ function round(value, 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 */
...@@ -36,7 +36,7 @@ function select_product_from_bc(barcode) { ...@@ -36,7 +36,7 @@ function select_product_from_bc(barcode) {
// 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},
...@@ -46,7 +46,7 @@ function initList() { ...@@ -46,7 +46,7 @@ function initList() {
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];
} }
}, },
{ {
...@@ -56,12 +56,12 @@ function initList() { ...@@ -56,12 +56,12 @@ function initList() {
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;
} }
} }
}, },
...@@ -72,18 +72,23 @@ function initList() { ...@@ -72,18 +72,23 @@ function initList() {
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: [
[
0,
"asc"
]
],
paging: false, paging: false,
dom: 'lrtip', // Remove the search input from that table dom: 'lrtip', // Remove the search input from that table
language: {url : '/static/js/datatables/french.json'} language: {url : '/static/js/datatables/french.json'}
...@@ -96,8 +101,8 @@ function initList() { ...@@ -96,8 +101,8 @@ function initList() {
$('#search_input').on('keyup', function () { $('#search_input').on('keyup', function () {
table_products table_products
.search(jQuery.fn.DataTable.ext.type.search.string(this.value)) // search without accents (see DataTable plugin) .search(jQuery.fn.DataTable.ext.type.search.string(this.value)) // search without accents (see DataTable plugin)
.draw() .draw();
}) });
} }
...@@ -113,25 +118,25 @@ function get_shelf_data() { ...@@ -113,25 +118,25 @@ function get_shelf_data() {
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) {
...@@ -140,41 +145,43 @@ function init() { ...@@ -140,41 +145,43 @@ function init() {
} }
if (search_chars.length >= 13) { if (search_chars.length >= 13) {
var barcode = search_chars.join(""); var barcode = search_chars.join("");
if (!isNaN(barcode)) { if (!isNaN(barcode)) {
search_chars = []; search_chars = [];
setTimeout(function(){ setTimeout(function() {
select_product_from_bc(barcode); select_product_from_bc(barcode);
}, 300); }, 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]}
shelf = {id: pathArray[pathArray.length-1]};
// Get shelf data from local storage // Get shelf data from local storage
if (Modernizr.localstorage) { if (Modernizr.localstorage) {
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + shelf.id)) var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + shelf.id));
if (stored_shelf != null) { if (stored_shelf != null) {
shelf = stored_shelf shelf = stored_shelf;
init() init();
} else { } else {
// Get shelf info if not coming from shelves list // Get shelf info if not coming from shelves list
get_shelf_data() get_shelf_data();
} }
} else { } else {
get_shelf_data() get_shelf_data();
} }
// listeners // listeners
// Cancel search // Cancel search
$('.cancel_search').on('click', function () { $('.cancel_search').on('click', function () {
$('#search_input').val('') $('#search_input').val('');
table_products.search('').draw() 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:[
...@@ -20,13 +20,15 @@ function init_datatable() { ...@@ -20,13 +20,15 @@ function init_datatable() {
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');
} }
} }
}, },
...@@ -36,14 +38,14 @@ function init_datatable() { ...@@ -36,14 +38,14 @@ function init_datatable() {
title:"Valeur théorique du rayon", title:"Valeur théorique du rayon",
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 == -1) { // Code: server send empty field -> loading if (data == -1) { // Code: server send empty field -> loading
return '<i class="fas fa-spinner fa-spin"></i>' return '<i class="fas fa-spinner fa-spin"></i>';
} else if (data == -2) { // Code: error getting data from server } else if (data == -2) { // Code: error getting data from server
return '/' return '/';
} else { } else {
return data + ' €' return data + ' €';
} }
}, },
width: "5%", width: "5%",
...@@ -56,12 +58,12 @@ function init_datatable() { ...@@ -56,12 +58,12 @@ function init_datatable() {
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 + ' %';
} }
} }
}, },
...@@ -72,12 +74,12 @@ function init_datatable() { ...@@ -72,12 +74,12 @@ function init_datatable() {
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 + ' %';
} }
} }
}, },
...@@ -88,17 +90,22 @@ function init_datatable() { ...@@ -88,17 +90,22 @@ function init_datatable() {
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_shelf_inventory'>Inventaire en rayon</button>" return "<button class='btn--primary do_shelf_inventory'>Inventaire en rayon</button>";
else else
return "<button class='btn--success do_shelf_inventory'>Inventaire en réserve</button>" return "<button class='btn--success do_shelf_inventory'>Inventaire en réserve</button>";
} }
} }
], ],
dom: 'rtip', dom: 'rtip',
order: [[ 1, "asc" ]], order: [
[
1,
"asc"
]
],
iDisplayLength: 25, iDisplayLength: 25,
language: {url : '/static/js/datatables/french.json'} language: {url : '/static/js/datatables/french.json'}
}) });
} }
function get_shelfs_extra_data() { function get_shelfs_extra_data() {
...@@ -112,94 +119,98 @@ function get_shelfs_extra_data() { ...@@ -112,94 +119,98 @@ function get_shelfs_extra_data() {
contentType: "application/json; charset=utf-8", contentType: "application/json; charset=utf-8",
success: function(data) { success: function(data) {
for (item of data.res) { for (item of data.res) {
var row_data = shelfs_table.row('#'+item.id).data() var row_data = shelfs_table.row('#'+item.id).data();
row_data.shelf_value = item.shelf_value
row_data.shelf_value = item.shelf_value;
shelfs_table shelfs_table
.row( '#'+item.id ) .row('#'+item.id)
.data( row_data ) .data(row_data)
.draw() .draw();
} }
}, },
error: function(data) { error: function(data) {
if (typeof data.responseJSON != 'undefined') { if (typeof data.responseJSON != 'undefined') {
console.log(data.responseJSON) console.log(data.responseJSON);
} }
set_null_to_extra_data() set_null_to_extra_data();
} }
}) });
} catch (e) { } catch (e) {
console.log(e) console.log(e);
set_null_to_extra_data() set_null_to_extra_data();
} }
} }
function set_null_to_extra_data() { function set_null_to_extra_data() {
shelfs_table.rows().every( function ( rowIdx, tableLoop, rowLoop ) { shelfs_table.rows().every(function (rowIdx, tableLoop, rowLoop) {
var d = this.data() var d = this.data();
d.shelf_value = -2
this.invalidate() // invalidate the data DataTables has cached for this row
} );
shelfs_table.draw() d.shelf_value = -2;
this.invalidate(); // invalidate the data DataTables has cached for this row
});
shelfs_table.draw();
} }
var getRowData = function(clicked) { var getRowData = function(clicked) {
var row = shelfs_table.row(clicked.parents('tr')) var row = shelfs_table.row(clicked.parents('tr'));
return row.data()
}
return row.data();
};
function go_to_shelf_inventory() { function go_to_shelf_inventory() {
openModal() openModal();
var clicked = $(this) var clicked = $(this);
var row_data = getRowData(clicked) var row_data = getRowData(clicked);
// Use local storage to pass data to next page // Use local storage to pass data to next page
if (Modernizr.localstorage) { if (Modernizr.localstorage) {
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + row_data.id)) var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + row_data.id));
// Set local storage if key doesn't exist // Set local storage if key doesn't exist
if (stored_shelf == null) { if (stored_shelf == null) {
localStorage.setItem("shelf_" + row_data.id , JSON.stringify(row_data)) localStorage.setItem("shelf_" + row_data.id, JSON.stringify(row_data));
} }
} }
document.location.href = "shelf_inventory/" + row_data.id document.location.href = "shelf_inventory/" + row_data.id;
} }
function go_to_shelf_view() { function go_to_shelf_view() {
openModal() openModal();
var clicked = $(this) var clicked = $(this);
var row_data = getRowData(clicked) var row_data = getRowData(clicked);
// Use local storage to pass data to next page // Use local storage to pass data to next page
if (Modernizr.localstorage) { if (Modernizr.localstorage) {
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + row_data.id)) var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + row_data.id));
// Set local storage if key doesn't exist // Set local storage if key doesn't exist
if (stored_shelf == null) { if (stored_shelf == null) {
localStorage.setItem("shelf_" + row_data.id , JSON.stringify(row_data)) localStorage.setItem("shelf_" + row_data.id, JSON.stringify(row_data));
} }
} }
document.location.href = "shelf_view/" + row_data.id document.location.href = "shelf_view/" + row_data.id;
} }
$(document).ready(function() { $(document).ready(function() {
shelfs_table = init_datatable() shelfs_table = init_datatable();
get_shelfs_extra_data() get_shelfs_extra_data();
$(document).on('click', 'button.do_shelf_inventory', go_to_shelf_inventory) $(document).on('click', 'button.do_shelf_inventory', go_to_shelf_inventory);
$('#shelfs').on('click', 'tbody td', go_to_shelf_view) $('#shelfs').on('click', 'tbody td', go_to_shelf_view);
// Search input // Search input
$('#search_input').on('keyup', function () { $('#search_input').on('keyup', function () {
shelfs_table shelfs_table
.search(jQuery.fn.DataTable.ext.type.search.string(this.value)) .search(jQuery.fn.DataTable.ext.type.search.string(this.value))
.draw() .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:[
...@@ -20,13 +20,15 @@ function init_datatable() { ...@@ -20,13 +20,15 @@ function init_datatable() {
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');
} }
} }
}, },
...@@ -36,43 +38,50 @@ function init_datatable() { ...@@ -36,43 +38,50 @@ function init_datatable() {
className:"dt-body-center", className:"dt-body-center",
width: "15%", width: "15%",
render: function (data, type, full, meta) { render: function (data, type, full, meta) {
return "<button class='btn--success do_export_sales_data'>Export Ventes</button>" return "<button class='btn--success do_export_sales_data'>Export Ventes</button>";
} }
} }
], ],
dom: 'rtip', dom: 'rtip',
order: [[ 1, "asc" ]], order: [
[
1,
"asc"
]
],
iDisplayLength: 25, iDisplayLength: 25,
language: {url : '/static/js/datatables/french.json'} language: {url : '/static/js/datatables/french.json'}
}) });
} }
var getRowData = function(clicked) { var getRowData = function(clicked) {
var row = shelfs_table.row(clicked.parents('tr')) var row = shelfs_table.row(clicked.parents('tr'));
return row.data()
}
return row.data();
};
function go_to_shelf_view() { function go_to_shelf_view() {
openModal() openModal();
var clicked = $(this) var clicked = $(this);
var row_data = getRowData(clicked) var row_data = getRowData(clicked);
// Use local storage to pass data to next page // Use local storage to pass data to next page
if (Modernizr.localstorage) { if (Modernizr.localstorage) {
var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + row_data.id)) var stored_shelf = JSON.parse(localStorage.getItem('shelf_' + row_data.id));
// Set local storage if key doesn't exist // Set local storage if key doesn't exist
if (stored_shelf == null) { if (stored_shelf == null) {
localStorage.setItem("shelf_" + row_data.id , JSON.stringify(row_data)) localStorage.setItem("shelf_" + row_data.id, JSON.stringify(row_data));
} }
} }
document.location.href = "shelf_view/" + row_data.id document.location.href = "shelf_view/" + row_data.id;
} }
function get_shelfs_sales_data() { function get_shelfs_sales_data() {
...@@ -86,47 +95,49 @@ function get_shelfs_sales_data() { ...@@ -86,47 +95,49 @@ function get_shelfs_sales_data() {
contentType: "application/json; charset=utf-8", contentType: "application/json; charset=utf-8",
success: function(data) { success: function(data) {
for (item of data.res) { for (item of data.res) {
var row_data = shelfs_table.row('#'+item.id).data() var row_data = shelfs_table.row('#'+item.id).data();
row_data.shelf_value = item.shelf_value
row_data.shelf_value = item.shelf_value;
shelfs_table shelfs_table
.row( '#'+item.id ) .row('#'+item.id)
.data( row_data ) .data(row_data)
.draw() .draw();
} }
}, },
error: function(data) { error: function(data) {
if (typeof data.responseJSON != 'undefined') { if (typeof data.responseJSON != 'undefined') {
console.log(data.responseJSON) console.log(data.responseJSON);
} }
} }
}) });
} catch (e) { } catch (e) {
err = {msg: e.toString(), ctx: 'get_shelfs_sales_data'} err = {msg: e.toString(), ctx: 'get_shelfs_sales_data'};
report_JS_error(err, 'shelfs') report_JS_error(err, 'shelfs');
} }
} }
function export_sales_data(event) { function export_sales_data(event) {
event.stopImmediatePropagation() event.stopImmediatePropagation();
var clicked = $(this) var clicked = $(this);
var row_data = getRowData(clicked) var row_data = getRowData(clicked);
console.log(row_data)
console.log(row_data);
} }
$(document).ready(function() { $(document).ready(function() {
shelfs_table = init_datatable() shelfs_table = init_datatable();
$('#shelfs').on('click', 'button.do_export_sales_data', export_sales_data) $('#shelfs').on('click', 'button.do_export_sales_data', export_sales_data);
$('#shelfs').on('click', 'tbody td', go_to_shelf_view) $('#shelfs').on('click', 'tbody td', go_to_shelf_view);
// Search input // Search input
$('#search_input').on('keyup', function () { $('#search_input').on('keyup', function () {
shelfs_table shelfs_table
.search(jQuery.fn.DataTable.ext.type.search.string(this.value)) .search(jQuery.fn.DataTable.ext.type.search.string(this.value))
.draw() .draw();
}) });
}) });
...@@ -33,6 +33,7 @@ $(document).ready(function() { ...@@ -33,6 +33,7 @@ $(document).ready(function() {
// 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()) {
...@@ -41,10 +42,10 @@ $(document).ready(function() { ...@@ -41,10 +42,10 @@ $(document).ready(function() {
$('#delay').removeAttr('hidden'); $('#delay').removeAttr('hidden');
} }
} else if (dataPartner.cooperative_state == "unsubscribed") { } else if (dataPartner.cooperative_state == "unsubscribed") {
$('#unsubscribed').show() $('#unsubscribed').show();
} else if (dataPartner.cooperative_state == "exempted") { } else if (dataPartner.cooperative_state == "exempted") {
$('#exempted').show() $('#exempted').show();
} else { } else {
$('body').append('Merci de prendre contact avec le Bureau des membres pour examiner votre situation.') $('body').append('Merci de prendre contact avec le Bureau des membres pour examiner votre situation.');
} }
}); });
var myChart; var myChart;
function get_ajax_data(product_id){ function get_ajax_data(product_id) {
$.ajax({ $.ajax({
type: 'GET', type: 'GET',
...@@ -33,20 +33,21 @@ var config = { ...@@ -33,20 +33,21 @@ var config = {
}, },
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);
}) });
}) });
...@@ -5,36 +5,38 @@ ...@@ -5,36 +5,38 @@
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();
} }
function archiveArticle(){ function archiveArticle() {
var jIdArcticle = { 'idArticle': selArctileData.product_id}; var jIdArcticle = { 'idArticle': selArctileData.product_id};
actionButton("set_archive", jIdArcticle, "/stock/listArticleBreaking"); actionButton("set_archive", jIdArcticle, "/stock/listArticleBreaking");
}; }
function dontPurchase(){ function dontPurchase() {
var jIdArcticle = { 'idArticle': selArctileData.product_id}; var jIdArcticle = { 'idArticle': selArctileData.product_id};
actionButton("set_dontPurchase", jIdArcticle, "/stock/listArticleBreaking"); actionButton("set_dontPurchase", jIdArcticle, "/stock/listArticleBreaking");
}; }
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",
...@@ -52,7 +54,7 @@ function actionButton (vUrl,jIdArcticle, followPage){ ...@@ -52,7 +54,7 @@ function actionButton (vUrl,jIdArcticle, followPage){
// 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_breaking", "url": "get_list_article_breaking",
"data": "" "data": ""
...@@ -63,38 +65,41 @@ $(document).ready(function() { ...@@ -63,38 +65,41 @@ $(document).ready(function() {
"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.product_id + ' class="btn btn-primary">' debut = '<button id="page1" type="button" data-toggle="modal" data-target=".modal" data-remote=' + full.product_id + ' class="btn btn-primary">';
fin = "</button>" fin = "</button>";
return debut + "<img src='data:image/png;base64," + data + "'>" + fin; return debut + "<img src='data:image/png;base64," + data + "'>" + fin;
} }
}, },
{data:"name", "title":"Article","width": "50%"}, {data:"name", "title":"Article", "width": "50%"},
{data:"create_date", {data:"create_date",
"render":function (data, type, row){ "render":function (data, type, row) {
my = new Date (data) my = new Date(data);
return my.toLocaleDateString() +" " + my.toLocaleTimeString(); return my.toLocaleDateString() +" " + my.toLocaleTimeString();
}, },
"title":"Date","width":"15%"}, "title":"Date", "width":"15%"},
{data:"create_date", {data:"create_date",
"render":function (data, type, row){ "render":function (data, type, row) {
my = new Date (data) my = new Date(data);
var today = new Date(); var today = new Date();
dif = new Number((today - my)/86400000).toFixed(2); dif = new Number((today - my)/86400000).toFixed(2);
return dif; return dif;
}, },
"title":"Durée","width":"5%"}, "title":"Durée", "width":"5%"},
{data:"purchase_ok", "width":"5%", {data:"purchase_ok", "width":"5%",
"title":"Achetable", "className":"dt-body-center", "title":"Achetable", "className":"dt-body-center",
"render": function (data, type, full, meta) { "render": function (data, type, full, meta) {
if (data == true){ if (data == true) {
return '<div><input type="checkbox" id="bt_dontPurchase" checked><div>';} return '<div><input type="checkbox" id="bt_dontPurchase" checked><div>';
else{ } else {
return '<div><input type="checkbox" id="bt_dontPurchase" ><div>';} return '<div><input type="checkbox" id="bt_dontPurchase" ><div>';
}
} }
}, },
{data:"reception_status", {data:"reception_status",
...@@ -107,7 +112,12 @@ $(document).ready(function() { ...@@ -107,7 +112,12 @@ $(document).ready(function() {
], ],
"searching": true, "searching": true,
"order": [[ 0, "desc" ]], "order": [
[
0,
"desc"
]
],
"iDisplayLength": 25, "iDisplayLength": 25,
"language": { "language": {
"emptyTable": "Pas de donnée", "emptyTable": "Pas de donnée",
...@@ -133,12 +143,14 @@ $(document).ready(function() { ...@@ -133,12 +143,14 @@ $(document).ready(function() {
} }
} }
}); });
}); });
/* Listener */ /* Listener */
$(document).on('click','#dp_Search',function(){search_table_article();}); $(document).on('click', '#dp_Search', function() {
search_table_article();
});
//barcode-reader //barcode-reader
...@@ -146,15 +158,17 @@ $(document).on('click','#dp_Search',function(){search_table_article();}); ...@@ -146,15 +158,17 @@ $(document).on('click','#dp_Search',function(){search_table_article();});
$(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;
...@@ -162,7 +176,7 @@ $(document).ready(function() { ...@@ -162,7 +176,7 @@ $(document).ready(function() {
} }
} }
},300); }, 300);
} }
pressed = true; pressed = true;
}); });
...@@ -179,28 +193,30 @@ var selArctileData; ...@@ -179,28 +193,30 @@ var selArctileData;
$(document).on('click', 'button#bt_archive', function () { $(document).on('click', 'button#bt_archive', function () {
var row = table_article.row($(this).parents('tr')); var 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>'; html += '<div id="showData" ><div id="articleName" >'+data.name+'</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="askTitle" >Vous êtes sur que cet article ne doit plus être acheter ? </div>';
html += '<div id="showData" ><div id="articleName" >'+data.name+'</div><div id="articleQty" >'+data.create_date+ '</div></div>'; html += '<div id="showData" ><div id="articleName" >'+data.name+'</div><div id="articleQty" >'+data.create_date+ '</div></div>';
selArctileData = data ; selArctileData = data;
openModal(html, dontPurchase, " - Ok - "); openModal(html, dontPurchase, " - Ok - ");
this.checked = true this.checked = true;
}else{ } else {
this.checked = false this.checked = false;
} }
} ); });
...@@ -10,12 +10,12 @@ ...@@ -10,12 +10,12 @@
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();
...@@ -24,21 +24,26 @@ function search_table_article(){ ...@@ -24,21 +24,26 @@ function search_table_article(){
// 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":[ "columns":[
{data:"name_template", "title":"Article","width": "50%"}, {data:"name_template", "title":"Article", "width": "50%"},
{data:"stock_qty", "title":"En Stock", "width": "10%"}, {data:"stock_qty", "title":"En Stock", "width": "10%"},
{data:"average", "title":"Moyen de vente", "width": "10%"}, {data:"average", "title":"Moyen de vente", "width": "10%"},
{data:"average_breaking", "title":"Moyenne vent rupture", "width": "10%"}, {data:"average_breaking", "title":"Moyenne vent rupture", "width": "10%"}
], ],
"searching": false, "searching": false,
"order": [[ 0, "desc" ]], "order": [
[
0,
"desc"
]
],
"iDisplayLength": 25, "iDisplayLength": 25,
"language": { "language": {
"emptyTable": "Pas de donnée", "emptyTable": "Pas de donnée",
...@@ -64,12 +69,14 @@ $(document).ready(function() { ...@@ -64,12 +69,14 @@ $(document).ready(function() {
} }
} }
}); });
}); });
/* Listener */ /* Listener */
$(document).on('click','#dp_Search',function(){search_table_article();}); $(document).on('click', '#dp_Search', function() {
search_table_article();
});
//barcode-reader //barcode-reader
...@@ -77,15 +84,17 @@ $(document).on('click','#dp_Search',function(){search_table_article();}); ...@@ -77,15 +84,17 @@ $(document).on('click','#dp_Search',function(){search_table_article();});
$(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;
...@@ -94,7 +103,7 @@ $(document).ready(function() { ...@@ -94,7 +103,7 @@ $(document).ready(function() {
} }
},300); }, 300);
} }
pressed = true; pressed = true;
}); });
...@@ -105,7 +114,7 @@ $(document).ready(function() { ...@@ -105,7 +114,7 @@ $(document).ready(function() {
}); });
// 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] };
...@@ -113,7 +122,7 @@ function ruptureArticle(test){ ...@@ -113,7 +122,7 @@ function ruptureArticle(test){
$.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",
...@@ -128,7 +137,7 @@ function ruptureArticle(test){ ...@@ -128,7 +137,7 @@ function ruptureArticle(test){
} }
}); });
} }
var selArctileData; var selArctileData;
...@@ -150,12 +159,11 @@ $(document).ready(function() { ...@@ -150,12 +159,11 @@ $(document).ready(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;
//} //}
......
...@@ -5,23 +5,23 @@ ...@@ -5,23 +5,23 @@
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": ""
...@@ -32,26 +32,26 @@ $(document).ready(function() { ...@@ -32,26 +32,26 @@ $(document).ready(function() {
"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; return debut + "<img src='data:image/png;base64," + data + "'>" + fin;
} }
}, },
{data:"name", "title":"Article","width": "50%"}, {data:"name", "title":"Article", "width": "50%"},
{data:"qty_available", "title":"En Stock", "width": "10%"}, {data:"qty_available", "title":"En Stock", "width": "10%"},
{data:"uom_id", {data:"uom_id",
"render":function (data, type, row){ "render":function (data, type, row) {
return data[1]; 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>";
} }
} }
...@@ -59,7 +59,12 @@ $(document).ready(function() { ...@@ -59,7 +59,12 @@ $(document).ready(function() {
], ],
"searching": false, "searching": false,
"order": [[ 0, "desc" ]], "order": [
[
0,
"desc"
]
],
"iDisplayLength": 25, "iDisplayLength": 25,
"language": { "language": {
"emptyTable": "Pas de donnée", "emptyTable": "Pas de donnée",
...@@ -85,12 +90,14 @@ $(document).ready(function() { ...@@ -85,12 +90,14 @@ $(document).ready(function() {
} }
} }
}); });
}); });
/* Listener */ /* Listener */
$(document).on('click','#dp_Search',function(){search_table_article();}); $(document).on('click', '#dp_Search', function() {
search_table_article();
});
//barcode-reader //barcode-reader
...@@ -98,15 +105,17 @@ $(document).on('click','#dp_Search',function(){search_table_article();}); ...@@ -98,15 +105,17 @@ $(document).on('click','#dp_Search',function(){search_table_article();});
$(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;
...@@ -115,7 +124,7 @@ $(document).ready(function() { ...@@ -115,7 +124,7 @@ $(document).ready(function() {
} }
},300); }, 300);
} }
pressed = true; pressed = true;
}); });
...@@ -126,14 +135,14 @@ $(document).ready(function() { ...@@ -126,14 +135,14 @@ $(document).ready(function() {
}); });
// 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",
...@@ -148,7 +157,7 @@ function ruptureArticle(test){ ...@@ -148,7 +157,7 @@ function ruptureArticle(test){
} }
}); });
} }
var selArctileData; var selArctileData;
...@@ -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 - ");
} ); });
...@@ -6,14 +6,14 @@ ...@@ -6,14 +6,14 @@
// 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%"
...@@ -24,7 +24,12 @@ $(document).ready(function() { ...@@ -24,7 +24,12 @@ $(document).ready(function() {
], ],
"searching": true, "searching": true,
"order": [[ 2, "desc" ]], "order": [
[
2,
"desc"
]
],
"iDisplayLength": 50, "iDisplayLength": 50,
"language": { "language": {
"emptyTable": "Pas de donnée", "emptyTable": "Pas de donnée",
...@@ -50,12 +55,14 @@ $(document).ready(function() { ...@@ -50,12 +55,14 @@ $(document).ready(function() {
} }
} }
}); });
}); });
/* Listener */ /* Listener */
$(document).on('click','#dp_Search',function(){search_table_article();}); $(document).on('click', '#dp_Search', function() {
search_table_article();
});
var csrftoken; var csrftoken;
...@@ -65,25 +72,28 @@ $(document).ready(function() { ...@@ -65,25 +72,28 @@ $(document).ready(function() {
// 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",
...@@ -105,36 +115,39 @@ var selArctileData; ...@@ -105,36 +115,39 @@ var selArctileData;
$(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="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="showData" ><div id="articleName" >'+data.name+'</div><div id="articleQty" >'+data.stockqt+ ' - '+data.uom_id + '</div></div>';
selArctileData = data ; selArctileData = data;
openModal(html, dontPurchase, " - Ok - "); openModal(html, dontPurchase, " - Ok - ");
this.checked = true this.checked = true;
}else{ } else {
this.checked = false this.checked = false;
} }
} ); });
......
...@@ -6,30 +6,32 @@ ...@@ -6,30 +6,32 @@
// 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_date_last_sale", "url": "get_list_date_last_sale",
"data": "" "data": ""
}, },
"columns":[ "columns":[
{data:"name", "title":"Article","width": "50%"}, {data:"name", "title":"Article", "width": "50%"},
{data:"maxdate", {data:"maxdate",
"render":function (data, type, row){ "render":function (data, type, row) {
my = new Date (data) my = new Date(data);
return my.toLocaleDateString() +" " + my.toLocaleTimeString(); return my.toLocaleDateString() +" " + my.toLocaleTimeString();
}, },
"title":"Date","width":"15%"}, "title":"Date", "width":"15%"},
{data:"maxdate", {data:"maxdate",
"render":function (data, type, row){ "render":function (data, type, row) {
my = new Date (data) my = new Date(data);
var today = new Date(); var today = new Date();
dif = new Number((today - my)/86400000).toFixed(2); dif = new Number((today - my)/86400000).toFixed(2);
return dif; return dif;
}, },
"title":"Durée","width":"5%"}, "title":"Durée", "width":"5%"},
{data:"stockqt", "title":"Qt. en Stock", "width":"5%" {data:"stockqt", "title":"Qt. en Stock", "width":"5%"
}, },
...@@ -37,10 +39,11 @@ $(document).ready(function() { ...@@ -37,10 +39,11 @@ $(document).ready(function() {
"title":"Achetable", "className":"dt-body-center", "title":"Achetable", "className":"dt-body-center",
"render": function (data, type, full, meta) { "render": function (data, type, full, meta) {
if (data == true){ if (data == true) {
return '<div><input type="checkbox" id="bt_dontPurchase" checked><div>';} return '<div><input type="checkbox" id="bt_dontPurchase" checked><div>';
else{ } else {
return '<div><input type="checkbox" id="bt_dontPurchase" ><div>';} return '<div><input type="checkbox" id="bt_dontPurchase" ><div>';
}
} }
}, },
{data:"reception_status", "width":"5%", {data:"reception_status", "width":"5%",
...@@ -60,7 +63,12 @@ $(document).ready(function() { ...@@ -60,7 +63,12 @@ $(document).ready(function() {
], ],
"searching": true, "searching": true,
"order": [[ 2, "desc" ]], "order": [
[
2,
"desc"
]
],
"iDisplayLength": 50, "iDisplayLength": 50,
"language": { "language": {
"emptyTable": "Pas de donnée", "emptyTable": "Pas de donnée",
...@@ -86,12 +94,14 @@ $(document).ready(function() { ...@@ -86,12 +94,14 @@ $(document).ready(function() {
} }
} }
}); });
}); });
/* Listener */ /* Listener */
$(document).on('click','#dp_Search',function(){search_table_article();}); $(document).on('click', '#dp_Search', function() {
search_table_article();
});
var csrftoken; var csrftoken;
...@@ -101,25 +111,28 @@ $(document).ready(function() { ...@@ -101,25 +111,28 @@ $(document).ready(function() {
// 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",
...@@ -141,36 +154,39 @@ var selArctileData; ...@@ -141,36 +154,39 @@ var selArctileData;
$(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="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="showData" ><div id="articleName" >'+data.name+'</div><div id="articleQty" >'+data.stockqt+ ' - '+data.uom_id + '</div></div>';
selArctileData = data ; selArctileData = data;
openModal(html, dontPurchase, " - Ok - "); openModal(html, dontPurchase, " - Ok - ");
this.checked = true this.checked = true;
}else{ } else {
this.checked = false 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);
y_sel.change(update_birthdate) opt.appendTo(j_sel);
m_sel.change(update_birthdate)
j_sel.change(update_birthdate)
} }
y_sel.change(update_birthdate);
m_sel.change(update_birthdate);
j_sel.change(update_birthdate);
};
var save_data = function() { 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