Commit a13e7d36 by François C.

Merge branch 'dev_cooperatic' of…

Merge branch 'dev_cooperatic' of gl.cooperatic.fr:cooperatic-foodcoops/third-party into dev_cooperatic
parents a8a2e1a9 6f50979a
......@@ -111,6 +111,10 @@ class CagetteEnvelops(models.Model):
def delete_envelop(self, envelop):
return self.c_db.delete(envelop)
def archive_envelop(self, envelop):
envelop['archive'] = True
return self.c_db.dbc.update([envelop])
def generate_envelop_display_id(self):
"""Generate a unique incremental id to display"""
c_db = CouchDB(arg_db='envelops')
......@@ -172,7 +176,7 @@ class CagetteEnvelops(models.Model):
else:
# Get the oldest check envelops, limited by the number of checks
docs = []
for item in c_db.dbc.view('index/by_type', key='ch', include_docs=True, limit=payment_data['checks_nb']):
for item in c_db.dbc.view('index/by_type_not_archive', key='ch', include_docs=True, limit=payment_data['checks_nb']):
docs.append(item.doc)
# If only 1 check to save
......
#cash, #ch {
margin-top: 15px;
}
.envelop_section {
margin-bottom: 10px;
}
......@@ -8,12 +12,72 @@
margin-bottom: 15px;
}
#cash_envelops {
#cash_envelops, #ch_envelops, #archive_cash_envelops, #archive_ch_envelops {
margin-top: 30px;
}
#ch_envelops {
margin-top: 30px;
.update_envelop_button, .delete_envelop_button, .envelop_comment {
margin: 0 0 15px 15px;
}
.envelop_content_list {
margin: 20px 0 15px 0;
}
/* Update envelop modal */
.envelop_lines {
margin: 20px 0;
display: flex;
flex-direction: column;
align-items: center;
}
.update_envelop_line {
margin: 5px 0;
width: 60%;
display: flex;
position: relative;
}
.deleted_line_through {
border-bottom: 1px solid #d9534f;
position: absolute;
content: "";
width: 100%;
height: 50%;
display: none;
}
.update_envelop_line div {
flex: 50% 1 0;
}
.line_partner_name_container {
display: flex;
justify-content: flex-start;
align-items: center;
}
.line_partner_name {
text-align: left;
padding: 0 5px;
}
.line_partner_input_container {
display: flex;
align-items: center;
}
.delete_envelop_line_icon {
margin-left: 10px;
color: #d9534f;
cursor: pointer;
}
.envelop_comments {
width: 60%;
margin-bottom: 20px;
}
/* Accordion style */
......@@ -23,7 +87,6 @@
color: #212529;
cursor: pointer;
padding: 18px;
/* width: 80%; */
text-align: left;
border: none;
outline: none;
......@@ -32,7 +95,6 @@
.archive_button {
padding: 18px;
/* width: 20%; */
}
hr {
......
var cash_envelops = [];
var archive_cash_envelops = [];
var ch_envelops = [];
var archive_ch_envelops = [];
var envelop_to_update = null;
function reset() {
$('#cash_envelops').empty();
$('#ch_envelops').empty();
$('#archive_cash_envelops').empty();
$('#archive_ch_envelops').empty();
archive_cash_envelops = [];
archive_ch_envelops = [];
cash_envelops = [];
ch_envelops = [];
}
......@@ -12,7 +19,9 @@ function toggle_error_alert() {
$('#envelop_cashing_error').toggle(250);
}
function toggle_success_alert() {
function toggle_success_alert(message) {
$('#envelop_cashing_success').find(".success_alert_content")
.text(message);
$('#envelop_cashing_success').toggle(250);
}
......@@ -20,9 +29,56 @@ function toggle_deleted_alert() {
$('#envelop_deletion_success').toggle(250);
}
// Set an envelop content on the document
/**
* Get an envelop from the cash or cheque lists dependings on the params
* @param {String} type
* @param {String} index
* @returns
*/
function get_envelop_from_type_index(type, index) {
if (type === "cash") {
return cash_envelops[index];
} else {
return ch_envelops[index];
}
}
/**
* Define a name for an envelop depending on its type, with or with its type
* @param {Object} envelop
* @param {String} name_type short | long
* @returns
*/
function get_envelop_name(envelop, name_type = 'short') {
let envelop_name = "";
if (envelop.type === "cash") {
let split_id = envelop._id.split('_');
let envelop_date = split_id[3].padStart(2, '0') + "/" + split_id[2].padStart(2, '0') + "/" + split_id[1];
envelop_name = `Enveloppe${(name_type === "short") ? "" : " de liquide"} du ${envelop_date}`;
} else if (envelop.type == "ch") {
envelop_name = `Enveloppe${(name_type === "short") ? "" : " de chèques"} #${envelop.display_id}`;
}
return envelop_name;
}
/**
* Set the envelops contents on the document (could use a little cleanup someday: don't generate html in js, etc...)
* @param {Object} envelop
* @param {String} envelop_name
* @param {Int} envelop_content_id
* @param {Int} envelop_index
*/
function set_envelop_dom(envelop, envelop_name, envelop_content_id, envelop_index) {
var envelops_section = $('#' + envelop.type + '_envelops');
var envelops_section ="";
if (!envelop.archive)
envelops_section = $('#' + envelop.type + '_envelops');
else
envelops_section = $('#archive_' + envelop.type + '_envelops');
// Calculate envelop total amount
var total_amount = 0;
......@@ -35,16 +91,18 @@ function set_envelop_dom(envelop, envelop_name, envelop_content_id, envelop_inde
+ '<div class="flex-container">';
// Allow checking for all cash and first check envelops
if (envelop.type == 'cash' || envelop.type == 'ch' && envelop_index == 0) {
if ((envelop.type == 'cash' || envelop.type == 'ch' && envelop_index == 0) && !envelop.archive) {
new_html += '<button class="accordion w80">' + envelop_name + ' - <i>' + total_amount + '€</i></button>'
+ '<button class="btn--success archive_button item-fluid" onClick="openModal(\'<h3>Êtes-vous sûr ?</h3>\', function() {archive_envelop(\'' + envelop.type + '\', ' + envelop_index + ');}, \'Encaisser\')">Encaisser</button>';
+ '<button class="btn--success archive_button item-fluid" onClick="openModal(\'<h3>Êtes-vous sûr ?</h3>\', function() {archive_envelop(\'' + envelop.type + '\', ' + envelop_index + ');}, \'Encaisser\', false)">Encaisser</button>';
} else if (envelop.archive && envelop.canceled) {
new_html += '<button class="accordion w100">' + envelop_name + ' - <i>' + total_amount + '€ (Enveloppe supprimée) </i></button>';
} else {
new_html += '<button class="accordion w100">' + envelop_name + ' - <i>' + total_amount + '€</i></button>';
}
new_html += '</div>'
+ '<div class="panel panel_' + envelop_content_id + '"><ol id="' + envelop_content_id + '"></ol></div>'
+ '</div>';
+ '<div class="panel panel_' + envelop_content_id + '"><ol class="envelop_content_list" id="' + envelop_content_id + '"></ol></div>'
+ '</div>';
$(new_html).appendTo(envelops_section);
......@@ -54,7 +112,7 @@ function set_envelop_dom(envelop, envelop_name, envelop_content_id, envelop_inde
var content = envelop.envelop_content[node].partner_name + ' : ' + envelop.envelop_content[node].amount + '€';
if ('payment_id' in envelop.envelop_content[node]) {
content += " - déjà comptabilisé.";
content += " -- paiement comptabilisé.";
}
var textnode = document.createTextNode(content); // Create a text node
......@@ -64,38 +122,101 @@ function set_envelop_dom(envelop, envelop_name, envelop_content_id, envelop_inde
}
let envelop_panel = $(`.panel_${envelop_content_id}`);
envelop_panel.append('<button class="btn--danger delete_envelop_button item-fluid" onClick="openModal(\'<h3>Supprimer enveloppe ?</h3>\', function() {delete_envelop(\'' + envelop.type + '\', ' + envelop_index + ');}, \'Supprimer\')">Supprimer l\'enveloppe</button>');
if (envelop.comments) envelop_panel.append(`<p class="envelop_comment"> <b>Commentaire :</b> ${envelop.comments}</p>`);
if (!envelop.archive) {
let envelop_panel = $(`.panel_${envelop_content_id}`);
envelop_panel.append(`<button class="btn--danger delete_envelop_button item-fluid" id="update_envelop_${envelop.type}_${envelop_index}">Supprimer l'enveloppe</button>`);
envelop_panel.append(`<button class="btn--primary update_envelop_button item-fluid" id="update_envelop_${envelop.type}_${envelop_index}">Modifier</button>`);
$(".update_envelop_button").off("click");
$(".update_envelop_button").on("click", function() {
let el_id = $(this).attr("id")
.split("_");
envelop_to_update = {
type: el_id[2],
index: el_id[3],
lines_to_delete: []
};
set_update_envelop_modal();
});
$(".delete_envelop_button").off("click");
$(".delete_envelop_button").on("click", function() {
let el_id = $(this).attr("id")
.split("_");
let type = el_id[2];
let index = el_id[3];
let envelop = get_envelop_from_type_index(type, index);
openModal(
"<h3>Supprimer l'enveloppe ?</h3>",
function() {
archive_canceled_envelop(envelop);
},
'Supprimer'
);
});
}
}
// Set the envelops data according to their type
/**
* Given the raw list of envelop documents, generate the cash and cheque lists
* @param {Array} envelops
*/
function set_envelops(envelops) {
var cash_index = 0;
var ch_index = 0;
var archive_cash_index = 0;
var archive_ch_index = 0;
reset();
for (var i= 0; i < envelops.length; i++) {
var envelop = envelops[i].doc;
if (envelop.type == "cash") {
//If the envelop is archived and more than 1 year old we delete it
if (envelop.archive && (new Date()-new Date(envelop.creation_date))/ (1000 * 3600 * 24 * 365)>1) {
delete_envelop(envelop);
} else if (envelop.type == "cash" && envelop.archive != true) {
cash_envelops.push(envelop);
let split_id = envelop._id.split('_');
let envelop_date = split_id[3] + "/" + split_id[2] + "/" + split_id[1];
let envelop_name = 'Enveloppe du ' + envelop_date;
let envelop_name = get_envelop_name(envelop);
let envelop_content_id = 'content_cash_list_' + cash_index;
set_envelop_dom(envelop, envelop_name, envelop_content_id, cash_index);
cash_index += 1;
} else if (envelop.type == "ch") {
} else if (envelop.type == "cash" && envelop.archive == true) {
archive_cash_envelops.push(envelop);
let envelop_name = get_envelop_name(envelop);
let envelop_content_id = 'content_archive_cash_list_' + archive_cash_index;
set_envelop_dom(envelop, envelop_name, envelop_content_id, archive_cash_index);
archive_cash_index += 1;
} else if (envelop.type == "ch" && envelop.archive != true) {
ch_envelops.push(envelop);
let envelop_name = 'Enveloppe #' + envelop.display_id;
let envelop_name = get_envelop_name(envelop);
let envelop_content_id = 'content_ch_list_' + ch_index;
set_envelop_dom(envelop, envelop_name, envelop_content_id, ch_index);
ch_index += 1;
} else if (envelop.type == "ch" && envelop.archive == true) {
archive_ch_envelops.push(envelop);
let envelop_name = get_envelop_name(envelop);
let envelop_content_id = 'content_archive_ch_list_' + archive_ch_index;
set_envelop_dom(envelop, envelop_name, envelop_content_id, archive_ch_index);
archive_ch_index += 1;
}
}
......@@ -125,18 +246,123 @@ function set_envelops(envelops) {
}
}
function delete_envelop(type, index) {
if (is_time_to('delete_envelop', 1000)) {
openModal();
/**
* Generate content & set listeners for the modal to update an envelop
*/
function set_update_envelop_modal() {
let envelop = get_envelop_from_type_index(envelop_to_update.type, envelop_to_update.index);
let envelop_name = get_envelop_name(envelop, 'long');
let modal_update_envelop = $('#templates #modal_update_envelop');
modal_update_envelop.find(".envelop_name").text(envelop_name);
modal_update_envelop.find(".envelop_lines").empty();
let update_line_template = $('#templates #update_envelop_line_template');
let cpt = 1;
for (let partner_id in envelop.envelop_content) {
let line = envelop.envelop_content[partner_id];
update_line_template.find(".update_envelop_line").attr('id', `update_line_${partner_id}`);
update_line_template.find(".line_number").html(`${cpt}.&nbsp;`);
update_line_template.find(".line_partner_name").text(line.partner_name);
modal_update_envelop.find(".envelop_lines").append(update_line_template.html());
var envelop = null;
if (type == "cash") {
envelop = cash_envelops[index];
} else {
envelop = ch_envelops[index];
cpt += 1;
}
openModal(
modal_update_envelop.html(),
() => {
update_envelop();
},
'Mettre à jour',
true,
true,
() => {
envelop_to_update = null;
}
);
// Elements needs to be on the document so value & listeners can be set
for (let partner_id in envelop.envelop_content) {
let line = envelop.envelop_content[partner_id];
$(`#update_line_${partner_id}`).find('.line_partner_amount')
.val(line.amount);
}
modal.find('.envelop_comments').val((envelop.comments !== undefined) ? envelop.comments : '');
$(".delete_envelop_line_icon").off("click");
$(".delete_envelop_line_icon").on("click", function() {
let line_id = $(this).closest(".update_envelop_line")
.attr("id")
.split("_");
let partner_id = line_id[line_id.length-1];
envelop_to_update.lines_to_delete.push(partner_id);
$(this).hide();
$(this).closest(".update_envelop_line")
.find(".deleted_line_through")
.show();
});
}
/**
* Update an envelop in couchdb
*/
function update_envelop() {
if (is_time_to('update_envelop', 1000)) {
let envelop = get_envelop_from_type_index(envelop_to_update.type, envelop_to_update.index);
// Update lines amounts
let amount_inputs = modal.find('.line_partner_amount');
amount_inputs.each(function (i, e) {
let line_id = $(e).closest(".update_envelop_line")
.attr("id")
.split("_");
let partner_id = line_id[line_id.length-1];
envelop.envelop_content[partner_id].amount = parseInt($(e).val());
});
// Delete lines
for (let partner_id of envelop_to_update.lines_to_delete) {
delete(envelop.envelop_content[partner_id]);
}
// Envelop comments
envelop.comments = modal.find('.envelop_comments').val();
dbc.put(envelop, function callback(err, result) {
envelop_to_update = null;
if (!err && result !== undefined) {
get_envelops();
toggle_success_alert("Enveloppe modifiée !");
} else {
alert("Erreur lors de la mise à jour de l'enveloppe. Si l'erreur persiste contactez un administrateur svp.");
console.log(err);
}
});
}
}
/**
* archive and canceled an envelop from couchdb.
* @param {Object} envelop
*/
function archive_canceled_envelop(envelop) {
if (is_time_to('archive_canceled_envelop', 1000)) {
envelop.archive = true;
envelop.canceled = true;
envelop._deleted = true;
dbc.put(envelop, function callback(err, result) {
if (!err && result !== undefined) {
toggle_deleted_alert();
......@@ -150,18 +376,39 @@ function delete_envelop(type, index) {
}
}
/**
* Delete an envelop from couchdb.
* @param {Object} envelop
*/
function delete_envelop(envelop) {
if (is_time_to('delete_envelop', 1000)) {
envelop._deleted = true;
dbc.put(envelop, function callback(err, result) {
if (!err && result !== undefined) {
get_envelops();
} else {
alert("Erreur lors de la suppression de l'enveloppe... Essaye de recharger la page et réessaye.");
console.log(err);
}
});
}
}
/**
* Send the request to save an envelop payments in Odoo. The envelop will be deleted from couchdb.
* @param {String} type
* @param {String} index
*/
function archive_envelop(type, index) {
if (is_time_to('archive_envelop', 1000)) {
if (is_time_to('archive_envelop', 5000)) {
$('#envelop_cashing_error').hide();
$('#envelop_cashing_success').hide();
// Loading on
openModal();
if (type == "cash") {
envelop = cash_envelops[index];
} else {
envelop = ch_envelops[index];
}
let envelop = get_envelop_from_type_index(type, index);
// Proceed to envelop cashing
$.ajax({
......@@ -204,7 +451,7 @@ function archive_envelop(type, index) {
}
if (display_success_alert) {
toggle_success_alert();
toggle_success_alert("Enveloppe encaissée !");
}
},
error: function() {
......@@ -212,10 +459,14 @@ function archive_envelop(type, index) {
alert('Erreur serveur. Merci de ne pas ré-encaisser l\'enveloppe qui a causé l\'erreur.');
}
});
} else {
alert("Par sécurité, il faut attendre 5s entre l'encaissement de deux enveloppes.");
}
}
// Get all the envelops from couch db
/**
* Get all the envelops from couchdb
*/
function get_envelops() {
dbc.allDocs({
include_docs: true,
......@@ -229,20 +480,20 @@ function get_envelops() {
});
}
// Hande change in couc db
sync.on('change', function (info) {
// handle change
if (info.direction == 'pull') {
get_envelops();
}
}).on('error', function (err) {
// handle error
console.log('erreur sync');
console.log(err);
});
$(document).ready(function() {
if (typeof must_identify == "undefined" || coop_is_connected()) {
get_envelops();
// Hande change in couc db
sync.on('change', function (info) {
// handle change
if (info.direction == 'pull') {
get_envelops();
}
}).on('error', function (err) {
// handle error
console.log('erreur sync');
console.log(err);
});
}
});
......@@ -27,7 +27,7 @@ def archive_envelop(request):
res_envelop = ""
envelop = json.loads(request.body.decode())
# save each partner payment
for partner_id in envelop['envelop_content']:
# If payment_id in payment details: payment already saved. Skip saving.
......@@ -52,7 +52,7 @@ def archive_envelop(request):
# Immediately save a token than this payment has been saved
# If an error occurs, this payment won't be saved again
envelop['envelop_content'][partner_id]['payment_id'] = res['payment_id']
updated_envelop = m.c_db.updateDoc(envelop);
updated_envelop = m.c_db.updateDoc(envelop)
envelop['_rev'] = updated_envelop['_rev']
else:
# Handling error when saving payment, return data to display error message
......@@ -75,8 +75,8 @@ def archive_envelop(request):
coop_logger.error("Cannot attach payment error message to member : %s", str(e))
try:
# Delete envelop from couchdb
res_envelop = m.delete_envelop(envelop)
# archive envelop from couchdb
res_envelop = m.archive_envelop(envelop)
except Exception as e:
res_envelop = "error"
......
......@@ -368,8 +368,8 @@ class CagetteInventory(models.Model):
return {'missed': missed, 'unchanged': unchanged, 'done': done}
@staticmethod
def update_stock_with_shelf_inventory_data(inventory_data):
"""Updates Odoo stock after a shelf inventory"""
def update_products_stock(inventory_data):
""" Updates Odoo stock after a shelf inventory or another action"""
TWOPLACES = Decimal(10) ** -2
api = OdooAPI()
......
......@@ -94,7 +94,7 @@ def do_custom_list_inventory(request):
full_inventory_data = CagetteInventory.get_full_inventory_data(inventory_data)
# Proceed with inventory
res['inventory'] = CagetteInventory.update_stock_with_shelf_inventory_data(full_inventory_data)
res['inventory'] = CagetteInventory.update_products_stock(full_inventory_data)
# remove file
CagetteInventory.remove_custom_inv_file(inventory_data['id'])
......
......@@ -53,9 +53,17 @@ class Command(BaseCommand):
byTypeMapFunction = '''function(doc) {
emit(doc.type);
}'''
byTypeNotArchiveMapFunction = '''function(doc) {
if(doc.archive != true){
emit(doc.type);
}
}'''
views = {
"by_type": {
"map": byTypeMapFunction
},
"by_type_not_archive": {
"map": byTypeNotArchiveMapFunction
}
}
self.createView(dbConn, "index", views)
......
......@@ -84,7 +84,7 @@ class CagetteMember(models.Model):
'point_qty': pts
}
"""
try:
return self.o_api.create('shift.counter.event', data)
except Exception as e:
......@@ -152,7 +152,7 @@ class CagetteMember(models.Model):
if (password == d + m + y):
if coop_id is None:
coop_id = coop['id']
data['id'] = coop_id
data['id'] = coop_id
auth_token_seed = fp + coop['create_date']
data['auth_token'] = hashlib.sha256(auth_token_seed.encode('utf-8')).hexdigest()
data['token'] = hashlib.sha256(coop['create_date'].encode('utf-8')).hexdigest()
......@@ -508,7 +508,7 @@ class CagetteMember(models.Model):
stype = shift_template['data']['type']
res['shift'] = \
m.create_coop_shift_subscription(shift_t_id, stype)
m.add_first_point(stype)
# m.add_first_point(stype) # Not needed anymore
# Update couchdb do with new data
try:
......@@ -729,6 +729,9 @@ class CagetteMember(models.Model):
cond = [['barcode', '=', str(key)]]
else:
cond = [['name', 'ilike', str(key)]]
cond.append('|')
cond.append(['is_member', '=', True])
cond.append(['is_associated_people', '=', True])
# cond.append(['cooperative_state', '!=', 'unsubscribed'])
fields = CagetteMember.m_default_fields
if not shift_id is None:
......@@ -740,13 +743,14 @@ class CagetteMember(models.Model):
keep_it = False
if not shift_id is None and len(shift_id) > 0:
# Only member registred to shift_id will be returned
cond = [['id', '=', m['tmpl_reg_line_ids'][0]]]
fields = ['shift_template_id']
shift_templ_res = api.search_read('shift.template.registration.line', cond, fields)
if (len(shift_templ_res) > 0
and
int(shift_templ_res[0]['shift_template_id'][0]) == int(shift_id)):
keep_it = True
if len(m['tmpl_reg_line_ids']) > 0:
cond = [['id', '=', m['tmpl_reg_line_ids'][0]]]
fields = ['shift_template_id']
shift_templ_res = api.search_read('shift.template.registration.line', cond, fields)
if (len(shift_templ_res) > 0
and
int(shift_templ_res[0]['shift_template_id'][0]) == int(shift_id)):
keep_it = True
else:
keep_it = True
if keep_it is True:
......@@ -762,7 +766,7 @@ class CagetteMember(models.Model):
# member = CagetteMember(m['id'], m['email'])
# m['next_shifts'] = member.get_next_shift()
if not m['parent_name'] is False:
m['name'] += ' / ' + m['parent_name']
m['name'] += ' (en binôme avec ' + m['parent_name'] + ')'
del m['parent_name']
members.append(m)
......@@ -842,7 +846,7 @@ class CagetteMember(models.Model):
def update_member_makeups(self, member_data):
api = OdooAPI()
res = {}
f = { 'makeups_to_do': int(member_data["target_makeups_nb"]) }
res_item = api.update('res.partner', [self.id], f)
res = {
......@@ -1202,7 +1206,7 @@ class CagetteServices(models.Model):
for m in s['members']:
for a in associated:
if int(a['parent_id'][0]) == int(m['partner_id'][0]):
m['partner_id'][1] += ' / ' + a['name']
m['partner_id'][1] += ' en binôme avec ' + a['name']
return services
......@@ -1459,4 +1463,3 @@ class CagetteUser(models.Model):
pass
return answer
......@@ -72,3 +72,6 @@ h1 .member_name {font-weight: bold;}
#member_advice {background: #FFF; color: red;}
.easy_shift_validate {text-align: center; margin-top: 3em;}
.button_is_member {background-color: #439D44; color: #fff;}
.button_is_associated_people {background: #0275D8; color: #fff;}
......@@ -62,6 +62,7 @@ var html_elts = {
real_capture : $('#real_capture'),
multi_results : $('#multi_results_preview'),
cooperative_state : $('#cooperative_state'),
status_explanation: $('#status_explanation'),
next_shifts : $('#next_shifts')
};
......@@ -91,8 +92,13 @@ function fill_member_slide(member) {
}
html_elts.image_medium.html('<img src="'+img_src+'" width="128" />');
html_elts.cooperative_state.html(member.cooperative_state);
if (member.cooperative_state == 'Désinscrit(e)' || member.cooperative_state == 'Rattrapage') coop_info.addClass('b_red');
else if (member.cooperative_state == 'En alerte' || member.cooperative_state == 'Délai accordé') coop_info.addClass('b_orange');
if (member.cooperative_state == 'Rattrapage') {
var explanation = "Tu as dû manquer un service! Pour pouvoir faire tes courses aujourd'hui, tu dois d'abord sélectionner un rattrapage sur ton espace membre.";
html_elts.status_explanation.html(explanation);
}
if (member.cooperative_state == 'Désinscrit(e)') coop_info.addClass('b_red');
else if (member.cooperative_state == 'En alerte' || member.cooperative_state == 'Délai accordé' || member.cooperative_state == 'Rattrapage') coop_info.addClass('b_orange');
if (member.shifts.length > 0) {
html_elts.next_shifts.append('Prochains services : ');
......@@ -141,9 +147,17 @@ function preview_results() {
for (i in results) {
if (results[i].is_member != false || results[i].is_associated_people != false) {
var m = $('<button>').attr('data-i', i)
.text(results[i].name);
if (results[i].is_member != false) {
var m = $('<button class="button_is_member">').attr('data-i', i)
.text(results[i].barcode_base + ' - ' + results[i].name);
html_elts.multi_results.append(m);
}
if (results[i].is_associated_people != false) {
m = $('<button class="button_is_associated_people"></button_is_member>').attr('data-i', i)
.text('B ' + results[i].barcode_base + ' - ' + results[i].name);
html_elts.multi_results.append(m);
}
......
......@@ -96,14 +96,7 @@ function process_form_submission(event) {
closeModal();
if (!err) {
var msg = "Vous êtes maintenant enregistré ! ";
msg += "<a href='" + em_url + "'>Cliquez ici</a> ";
msg += "pour découvrir l'espace membre";
$('p.intro').remove();
vform.remove();
display_msg_box(msg);
window.location.href = em_url;
}
}
......
......@@ -36,7 +36,7 @@ class CagetteMembersSpace(models.Model):
try:
cond = [
['partner_id', '=', partner_id],
['create_date', '>', date_from],
['date_begin', '>', date_from],
['date_begin', '<', today],
['state', '!=', 'draft'],
['state', '!=', 'open'],
......@@ -88,10 +88,10 @@ class CagetteMembersSpace(models.Model):
res = res + []
# Add amnesty line
is_amnesty = getattr(settings, 'AMNISTIE_DATE', 'false')
is_amnesty = getattr(settings, 'AMNISTIE_DATE', False)
company_code = getattr(settings, 'COMPANY_CODE', '')
if is_amnesty and company_code == "lacagette":
amnesty={}
amnesty = {}
amnesty['is_amnesty'] = True
amnesty['create_date'] = is_amnesty
amnesty['date_begin'] = is_amnesty
......@@ -107,7 +107,7 @@ class CagetteMembersSpace(models.Model):
paginated_res = res[offset:end_index]
except Exception as e:
print(str(e))
coop_logger.error("get_shifts_history : %s", str(e))
return paginated_res
\ No newline at end of file
function init_faq() {
$("#unsuscribe_form_link_btn").prop("href", unsuscribe_form_link);
$("#unsuscribe_form_link_btn2").prop("href", unsuscribe_form_link);
......@@ -20,6 +19,10 @@ function init_faq() {
$("#request_form_link_btn").prop("href", request_form_link);
}
$(document).on('click', "#shift_exchange_btn", () => {
goto('echange-de-services');
});
$(document).on('click', '.accordion', function() {
/* Toggle between adding and removing the "active" class,
to highlight the button that controls the panel */
......@@ -33,8 +36,4 @@ $(document).on('click', '.accordion', function() {
} else {
panel.style.display = "block";
}
$("#shift_exchange_btn").on("click", () => {
goto('echange-de-services');
});
});
\ No newline at end of file
});
......@@ -91,8 +91,10 @@ function add_or_change_shift(new_shift_id) {
selected_shift = null;
if (error.status === 400) {
alert(`Désolé ! Le service que vous souhaitez échanger démarre dans moins de 24h. ` +
`Il n'est plus possible de l'échanger.`);
alert(`Désolé ! Le service que tu souhaites échanger démarre dans moins de 24h. ` +
`Afin de faciliter la logistique des services, il n'est plus possible de l'échanger. ` +
`Si tu ne peux vraiment pas venir, tu seras noté.e absent.e à ton service. ` +
`Tu devras alors sélectionner un service de rattrapage sur ton espace membre.`);
} else {
alert(`Une erreur est survenue. ` +
`Il est néanmoins possible que la requête ait abouti, ` +
......@@ -234,7 +236,7 @@ function init_calendar_page() {
};
}
const hidden_days = $.map(days_to_hide.split(", "), Number);
const hidden_days = days_to_hide.length > 0 ? $.map(days_to_hide.split(", "), Number) : [];
const calendarEl = document.getElementById('calendar');
......@@ -337,11 +339,107 @@ function init_calendar_page() {
calendar.render();
}
function init_read_only_calendar_page() {
let template_explanations = $("#calendar_explaination_template");
if (vw <= 992) {
$(".loading-calendar").show();
$("#calendar_explaination_area").hide();
$("#calendar_explaination_button").on("click", () => {
openModal(
template_explanations.html(),
closeModal,
"J'ai compris"
);
})
.show();
} else {
$("#calendar_explaination_button").hide();
$("#calendar_explaination_area").html(template_explanations.html())
.show();
}
if (incoming_shifts !== null) {
init_shifts_list();
} else {
load_partner_shifts(partner_data.concerned_partner_id)
.then(init_shifts_list);
}
if (should_select_makeup()) {
$(".makeups_nb").text(partner_data.makeups_to_do);
$("#need_to_select_makeups_message").show();
}
let default_initial_view = "";
let header_toolbar = {};
if (vw <= 768) {
default_initial_view = 'listWeek';
header_toolbar = {
left: 'title',
center: 'listWeek,timeGridDay',
right: 'prev,next today'
};
} else if (vw <=992) {
default_initial_view = 'listWeek';
header_toolbar = {
left: 'title',
center: 'dayGridMonth,listWeek,timeGridDay',
right: 'prev,next today'
};
} else {
default_initial_view = 'dayGridMonth';
header_toolbar = {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,listWeek,timeGridDay'
};
}
const hidden_days = days_to_hide.length > 0 ? $.map(days_to_hide.split(", "), Number) : [];
const calendarEl = document.getElementById('read_only_calendar');
console.log(calendarEl)
calendar = new FullCalendar.Calendar(calendarEl, {
locale: 'fr',
initialView: default_initial_view,
headerToolbar: header_toolbar,
buttonText: {
list: "Semaine"
},
eventTimeFormat: {
hour: '2-digit',
minute: '2-digit'
},
allDaySlot: false,
contentHeight: "auto",
eventDisplay: "block",
hiddenDays: hidden_days,
events: '/shifts/get_list_shift_calendar/' + partner_data.concerned_partner_id,
eventDidMount: function() {
// Calendar is hidden at first on mobile to hide header change when data is loaded
$(".loading-calendar").hide();
$("#calendar").show();
if (vw <= 992) {
$(".fc .fc-header-toolbar").addClass("resp-header-toolbar");
} else {
$(".fc .fc-header-toolbar").removeClass("resp-header-toolbar");
}
}
});
calendar.render();
}
function init_shifts_exchange() {
$(".shifts_exchange_page_content").hide();
vw = window.innerWidth;
if (partner_data.cooperative_state === 'unsubscribed') {
if (partner_data.cooperative_state === 'unsubscribed' || partner_data.cooperative_state === 'gone') {
$("#unsuscribed_content").show();
$(".unsuscribed_form_link")
......@@ -371,9 +469,9 @@ function init_shifts_exchange() {
} else if (
partner_data.comite === "True") {
let msg_template = $("#comite_template");
$(".comite_content_msg").html(msg_template.html());
$("#comite_content").show();
init_read_only_calendar_page();
} else if (partner_data.cooperative_state === 'suspended'
&& partner_data.date_delay_stop === 'False') {
$("#suspended_content .makeups_nb").text(partner_data.makeups_to_do);
......@@ -401,4 +499,4 @@ function init_shifts_exchange() {
vw = window.innerWidth;
init_calendar_page();
});
}
\ No newline at end of file
}
......@@ -16,7 +16,8 @@ const possible_cooperative_state = {
alert: "En alerte",
up_to_date: "À jour",
unsubscribed: "Désinscrit.e des créneaux",
delay: "En délai"
delay: "En délai",
gone: "Parti.e"
};
/* - Data */
......@@ -177,7 +178,7 @@ function init_my_info_data() {
$(".delay_date_stop").text(f_date_delay_stop);
$(".delay_date_stop_container").show();
} else if (partner_data.cooperative_state === 'unsubscribed') {
} else if (partner_data.cooperative_state === 'unsubscribed' || partner_data.cooperative_state === 'gone') {
$(".member_shift_name").text('X');
$(".unsuscribed_form_link")
......
......@@ -12,5 +12,5 @@ urlpatterns = [
url(r'^faqBDM$', views.faqBDM),
url(r'^no_content$', views.no_content),
url(r'^get_shifts_history$', views.get_shifts_history),
url('/*$', views.index), # Urls unknown from the server will redirect to index
url(r'^.*', views.index) # Urls unknown from the server will redirect to index
]
/* Comments : */
/* - Screens */
/* -- Sections */
/* - Common */
.page_body{
position: relative;
}
......@@ -9,8 +15,6 @@
right: 0;
}
/* - Common */
.pill {
border-radius: 30px;
min-width: 200px;
......@@ -155,6 +159,14 @@
min-height: 45px;
}
#do_inventory {
border-top: 1px solid #004aa6;
}
#refresh_order {
border-top: 1px solid #004aa6;
border-bottom: 1px solid #004aa6;
}
/* -- Order data */
#order_data_container {
font-size: 1.8rem;
......@@ -185,10 +197,27 @@
min-width: 200px;
}
#date_planned_input, #coverage_days_input, #stats_date_period_select {
#date_planned_input, #coverage_days_input, #targeted_amount_input, #percent_adjust_input, #stats_date_period_select {
border-radius: 3px;
}
#coverage_form > div {
display:block;
float:left;
}
#coverage_form .input-wrapper {
margin-right: 3px;
}
#coverage_days_input, #targeted_amount_input, #percent_adjust_input {
display: block;
}
#coverage_days_input, #targeted_amount_input {
margin-bottom: 3px;
}
/* -- Table */
#products_table_filter{
text-align: right !important;
......@@ -216,6 +245,10 @@
margin-left: 5px;
}
.main.fa-info-circle {
color: #0275d8;
cursor: pointer;
}
.custom_cell_content {
display: flex;
flex-direction: column;
......@@ -288,7 +321,7 @@
justify-content: center;
align-items: center;
flex-wrap: wrap;
margin: 30px 0 20px 0;
margin: 15px 0;
position: -webkit-sticky;
position: sticky;
top: 140px;
......@@ -296,8 +329,8 @@
}
.supplier_pill {
background-color: #a0daff;
border: 1px solid #6ea8cc;
background-color: #ffebcd;
border: 2px solid black;
}
.pill_supplier_name {
......@@ -338,6 +371,36 @@
width: 90%;
}
/* -- Product actions modal*/
.npa-options {
width: fit-content;
text-align: left;
margin: auto;
}
.npa-options label {
display: block;
}
.modal_product_actions_section {
margin: 1em 0;
}
.modal_product_actions_section .tooltip {
margin-left: 5px;
}
.modal_product_actions_title {
font-weight: bold;
font-size: 2.2rem;
margin-bottom: 10px;
}
.checkbox_action_disabled {
cursor: not-allowed;
opacity: .5;
}
/* - Orders created screen */
.order_created_header {
......@@ -382,4 +445,12 @@
background-color: #e7e9ed;
width: 100%;
padding: 15px;
}
/* - Miscellaneous */
footer {
display: none;
}
\ No newline at end of file
......@@ -16,6 +16,7 @@ var dbc = null,
order_doc = {
_id: null,
coverage_days: null,
targeted_amount: null,
stats_date_period: '',
last_update: {
timestamp: null,
......@@ -29,7 +30,7 @@ var dbc = null,
var clicked_order_pill = null;
var timerId;
/* - UTILS */
/**
......@@ -43,6 +44,7 @@ function reset_data() {
order_doc = {
_id: null,
coverage_days: null,
targeted_amount: null,
stats_date_period: '',
last_update : {
timestamp: null,
......@@ -116,6 +118,11 @@ function _compute_stats_date_from() {
return val;
}
function debounceFunction(func, delay = 1000) {
clearTimeout(timerId);
timerId = setTimeout(func, delay);
}
/* - PRODUCTS */
/**
......@@ -165,7 +172,7 @@ function add_product() {
res.default_code = ' ';
products.unshift(res);
update_main_screen({'sort_order_dir':'desc'});
update_cdb_order();
debounceFunction(update_cdb_order);
} else {
alert("L'article n'a pas toutes les caractéristiques pour être ajouté.");
}
......@@ -183,39 +190,105 @@ function add_product() {
return 0;
}
function compute_purchase_qty_for_coverage(product, coeff, stock, incoming_qty, daily_conso, days) {
let purchase_qty_for_coverage = null;
purchase_qty_for_coverage = days * daily_conso - stock - incoming_qty + product.minimal_stock;
purchase_qty_for_coverage = (purchase_qty_for_coverage < 0) ? 0 : purchase_qty_for_coverage;
// Reduce to nb of packages to purchase
purchase_package_qty_for_coverage = purchase_qty_for_coverage / product.suppliersinfo[0].package_qty;
if (coeff != 1) {
purchase_package_qty_for_coverage *= coeff;
}
// return Round up to unit for all products
return Math.ceil(purchase_package_qty_for_coverage);
}
function compute_and_affect_product_supplier_quantities(coeff, days) {
for (const [
key,
product
] of Object.entries(products)) {
if ('suppliersinfo' in product && product.suppliersinfo.length > 0) {
let purchase_qty_for_coverage = null;
// Durée couverture produit = (stock + qté entrante + qté commandée ) / conso quotidienne
const stock = product.qty_available;
const incoming_qty = product.incoming_qty;
const daily_conso = product.daily_conso;
purchase_package_qty_for_coverage = compute_purchase_qty_for_coverage(product, coeff, stock, incoming_qty, daily_conso, days);
// Set qty to purchase for first supplier only
products[key].suppliersinfo[0].qty = purchase_package_qty_for_coverage;
}
}
}
/**
* Compute the qty to buy for each product, depending the coverage days.
* Set the computed qty for the first supplier only.
*/
function compute_products_coverage_qties() {
if (order_doc.coverage_days != null) {
for (const [
key,
product
] of Object.entries(products)) {
if ('suppliersinfo' in product && product.suppliersinfo.length > 0) {
let purchase_qty_for_coverage = null;
// Durée couverture produit = (stock + qté entrante + qté commandée ) / conso quotidienne
const stock = product.qty_available;
const incoming_qty = product.incoming_qty;
const daily_conso = product.daily_conso;
purchase_qty_for_coverage = order_doc.coverage_days * daily_conso - stock - incoming_qty;
purchase_qty_for_coverage = (purchase_qty_for_coverage < 0) ? 0 : purchase_qty_for_coverage;
// Reduce to nb of packages to purchase
purchase_package_qty_for_coverage = purchase_qty_for_coverage / product.suppliersinfo[0].package_qty;
// Round up to unit for all products
purchase_package_qty_for_coverage = Math.ceil(purchase_package_qty_for_coverage);
// Set qty to purchase for first supplier only
products[key].suppliersinfo[0].qty = purchase_package_qty_for_coverage;
return new Promise((resolve) => {
const pc_adjust = $('#percent_adjust_input').val();
let coeff = 1;
if (!isNaN(parseFloat(pc_adjust))) {
coeff = (1 + parseFloat(pc_adjust) /100);
}
order_doc.coeff = coeff;
if (order_doc.coverage_days != null) {
compute_and_affect_product_supplier_quantities(coeff, order_doc.coverage_days);
resolve();
} else if (order_doc.targeted_amount != null) {
const small_step = 0.1,
max_iter = 182; // Assume that no more than 1/2 year coverage is far enough
let go_on = true,
iter = 0,
days = 1,
step = 1;
//Let's compute the nearst amount, by changing days quantity
while(go_on == true && iter < max_iter) {
order_total_value = 0;
compute_and_affect_product_supplier_quantities(coeff, days);
_compute_total_values_by_supplier();
for (let supplier of selected_suppliers) {
order_total_value += supplier.total_value;
}
let order_total_value_f = parseFloat(order_total_value),
targeted_amount_f = parseFloat(order_doc.targeted_amount);
if (order_total_value_f >= targeted_amount_f) {
if (order_total_value_f != targeted_amount_f && iter < max_iter) {
step = small_step; // we have gone too far, let's go back, using small step
days -= step;
}
/* console.log(iter)
console.log(order_total_value_f + '/' + targeted_amount_f)
console.log(days)
console.log(go_on)*/
} else {
if (step == small_step) {
// amount was above the target, let's compute again with the previous value
go_on = false;
compute_and_affect_product_supplier_quantities(coeff, days + step);
} else {
days += step;
}
}
iter++;
}
resolve();
}
}
/* console.log(rder_doc.coverage_days);
console.log(order_doc.targeted_amount)*/
});
}
/**
......@@ -227,7 +300,7 @@ function check_products_data() {
if (suppliers_id.length > 0) {
$.notify(
"Vérfication des informations produits...",
"Vérification des informations produits...",
{
globalPosition:"top left",
className: "info"
......@@ -250,8 +323,12 @@ function check_products_data() {
traditional: true,
contentType: "application/json; charset=utf-8",
success: function(data) {
let loaded_products_ids = products.map(p => p.id);
// Going through products fetched from server
for (let product of data.res.products) {
const p_index = products.findIndex(p => p.id == product.id);
const p_id = product.id;
const p_index = products.findIndex(p => p.id == p_id);
if (p_index === -1) {
// Add product if it wasn't fetched before (made available since last access to order)
......@@ -272,9 +349,41 @@ function check_products_data() {
}
}
}
// Remove fetched product id from loaded products list
const loaded_p_index = loaded_products_ids.indexOf(p_id);
if (loaded_p_index > -1) {
loaded_products_ids.splice(loaded_p_index, 1);
}
}
$('.notifyjs-wrapper').trigger('notify-hide');
/**
* If loaded p_ids are remaining:
* these products were loaded but don't match the conditions to be fetched anymore.
* Remove them.
*/
if (loaded_products_ids.length > 0) {
for (pid of loaded_products_ids) {
const p_index = products.findIndex(p => p.id == pid);
const p_name = products[p_index].name;
products.splice(p_index, 1);
$.notify(
`Produit "${p_name}" retiré de la commande.\nIl a probablement été passé en archivé ou en NPA sur un autre poste.`,
{
globalPosition:"top left",
className: "info",
autoHideDelay: 12000,
clickToHide: false
}
);
}
}
resolve();
},
error: function(data) {
......@@ -335,7 +444,7 @@ function update_product_ref(input_el, p_id, p_index) {
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: () => {
update_cdb_order();
debounceFunction(update_cdb_order);
$(".actions_buttons_area .right_action_buttons").notify(
"Référence sauvegardée !",
......@@ -413,7 +522,7 @@ function add_supplier() {
save_supplier_products(supplier, data.res.products);
update_main_screen();
$("#supplier_input").val("");
update_cdb_order();
debounceFunction(update_cdb_order);
closeModal();
},
error: function(data) {
......@@ -449,7 +558,7 @@ function remove_supplier(supplier_id) {
products = products.filter(product => product.suppliersinfo.length > 0);
update_main_screen();
update_cdb_order();
debounceFunction(update_cdb_order);
}
......@@ -516,7 +625,7 @@ function save_supplier_product_association(product, supplier, cell) {
products_table.row(row).data(new_row_data)
.draw();
update_cdb_order();
debounceFunction(update_cdb_order);
closeModal();
},
error: function(data) {
......@@ -570,7 +679,7 @@ function end_supplier_product_association(product, supplier) {
// Update table
display_products();
update_cdb_order();
debounceFunction(update_cdb_order);
closeModal();
},
error: function(data) {
......@@ -677,67 +786,102 @@ function _compute_total_values_by_supplier() {
/* - PRODUCT */
/**
* Update 'purchase_ok' of a product
*
* @param {int} p_id product id
* @param {Boolean} npa value to set purchase_ok to
*/
function set_product_npa(p_id, npa) {
openModal();
const data = {
product_tmpl_id: p_id,
purchase_ok: !npa
function commit_actions_on_product(product, inputs) {
let actions = {
npa: [],
to_archive: false,
minimal_stock: 0,
id: product.id,
name: product.name
};
// Fetch supplier products
inputs.each(function (i, e) {
const input = $(e);
if (input.attr('name') == 'npa-actions') {
if (input.prop('checked') == true) {
actions.npa.push(input.val());
}
} else if (input.attr('name') == "minimal_stock") {
actions.minimal_stock = input.val();
} else if (input.attr('name') == "archive-action") {
if (input.prop('checked') == true && product.incoming_qty === 0) {
actions.to_archive = true;
}
}
});
openModal();
$.ajax({
type: "POST",
url: "/products/update_product_purchase_ok",
url: "/products/commit_actions_on_product",
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
data: JSON.stringify(actions),
success: () => {
const index = products.findIndex(p => p.id == p_id);
const index = products.findIndex(p => p.id == product.id);
// Give time for modal to fade
setTimeout(function() {
$(".actions_buttons_area .right_action_buttons").notify(
"Produit passé en NPA !",
{
elementPosition:"bottom right",
className: "success",
arrowShow: false
}
);
}, 500);
products[index].minimal_stock = actions.minimal_stock;
// Remove NPA products
products.splice(index, 1);
update_main_screen();
update_cdb_order();
if (actions.npa.length > 0 || actions.to_archive === true) {
// Remove NPA & archived products
products.splice(index, 1);
debounceFunction(update_cdb_order);
}
closeModal();
check_products_data()
.then(() => {
update_cdb_order();
update_main_screen();
closeModal();
// Give time for modal to fade
setTimeout(function() {
$(".actions_buttons_area .right_action_buttons").notify(
"Actions enregistrées !",
{
elementPosition:"bottom right",
className: "success",
arrowShow: false
}
);
}, 500);
});
},
error: function(data) {
let msg = "erreur serveur lors de la sauvegarde du NPA".
msg += ` (product_tmpl_id: ${p_id})`;
let msg = "erreur serveur lors de la sauvegarde".
msg += ` (product_tmpl_id: ${product.id})`;
err = {msg: msg, ctx: 'set_product_npa'};
err = {msg: msg, ctx: 'commit_actions_on_product'};
if (typeof data.responseJSON != 'undefined' && typeof data.responseJSON.error != 'undefined') {
err.msg += ' : ' + data.responseJSON.error;
}
report_JS_error(err, 'orders');
closeModal();
alert('Erreur lors de la sauvegarde de la donnée. Veuillez ré-essayer plus tard.');
update_main_screen();
try {
if (data.responseJSON.code === "archiving_with_incoming_qty") {
alert("Ce produit a des quantités entrantes, vous ne pouvez pas l'archiver.");
} else if (data.responseJSON.code === "error_stock_update") {
alert('Erreur lors de la mise à zéro du stock du produit archivé. Les actions ont bien été réalisées.');
} else {
alert('Erreur lors de la sauvegarde des données. Veuillez ré-essayer plus tard.');
}
} catch (error) {
alert('Erreur lors de la sauvegarde des données. Veuillez ré-essayer plus tard.');
}
check_products_data()
.then(() => {
update_cdb_order();
update_main_screen();
closeModal();
});
}
});
}
/* - INVENTORY */
/**
......@@ -1148,7 +1292,7 @@ function goto_main_screen(doc) {
check_products_data()
.then(() => {
update_cdb_order();
debounceFunction(update_cdb_order);
update_main_screen();
switch_screen();
});
......@@ -1316,8 +1460,8 @@ function prepare_datatable_columns() {
{
data: "id",
title: `<div id="table_header_select_all" class="txtcenter">
<span class="select_all_text">Sélectionner</span>
<label for="select_all_products_cb">- Tout</label>
<!--<span class="select_all_text">Sélectionner</span>-->
<label for="select_all_products_cb">Tout</label>
<input type="checkbox" class="select_product_cb" id="select_all_products_cb" name="select_all_products_cb" value="all">
</div>`,
className: "dt-body-center",
......@@ -1442,12 +1586,11 @@ function prepare_datatable_columns() {
});
columns.push({
data: "purchase_ok",
title: `NPA`,
title: ``,
className: "dt-body-center",
orderable: false,
render: function (data) {
return `<input type="checkbox" class="product_npa_cb" value="purchase_ok" ${data ? '' : 'checked'}>`;
return `<button type="button" class="btn--primary product_actions">Actions</button>`;
},
width: "4%"
});
......@@ -1478,7 +1621,7 @@ function display_products(params) {
const data = prepare_datatable_data();
const columns = prepare_datatable_columns();
let sort_order_dir = "asc";
let sort_order_dir = "desc";
if (params != undefined && typeof params.sort_order_dir != "undefined") {
sort_order_dir = params.sort_order_dir;
......@@ -1488,10 +1631,11 @@ function display_products(params) {
columns: columns,
order: [
[
6, // Order by default by first supplier
5, // Order by default by first supplier
sort_order_dir
]
],
stateSave: true,
orderClasses: false,
aLengthMenu: [
[
......@@ -1594,22 +1738,94 @@ function display_products(params) {
products_table.row($(this).closest('tr')).data(new_row_data)
.draw();
update_cdb_order();
debounceFunction(update_cdb_order);
display_total_values();
} else {
$(this).val('');
}
}
})
.on('change', 'tbody td .product_qty_input', function () {
// Since data change is saved on blur, set focus on change in case of arrows pressed
$(this).focus();
})
.on('keypress', 'tbody td .product_qty_input', function(e) {
if (e.which == 13) {
// Validate on Enter pressed
if (e.which == 13) {
$(this).blur();
}
})
.on('keydown', 'tbody td .product_qty_input', function(e) {
if (e.which == 38) {
e.preventDefault();
// On arrow up pressed, focus next row input
let next_input = $(this).closest("tr")
.prev()
.find(".product_qty_input");
next_input.focus();
// Scroll to a position where the target input is not hidden by the sticky suppliers container
const suppliers_container_top_offset =
$("#suppliers_container").offset().top
- $(window).scrollTop()
+ $("#suppliers_container").outerHeight();
const next_input_top_offset = next_input.offset().top - $(window).scrollTop();
if (next_input_top_offset < suppliers_container_top_offset) {
window.scrollTo({
top: $(window).scrollTop() - $("#suppliers_container").outerHeight()
});
}
} else if (e.which == 40) {
e.preventDefault();
// On arrow down pressed, focus previous row input
$(this).closest("tr")
.next()
.find(".product_qty_input")
.focus();
} else if (e.which == 13) {
e.preventDefault();
// On enter pressed, focus previous row input
$(this).closest("tr")
.next()
.find(".product_qty_input")
.focus();
}
})
.on('click', 'tbody td .product_actions', function(e) {
// Save / unsave selected row
const p_id = products_table.row($(this).closest('tr')).data().id;
const product = products.find(p => p.id == p_id);
let modal_product_actions = $('#templates #modal_product_actions');
modal_product_actions.find(".product_name").text(product.name);
const product_can_be_archived = product.incoming_qty === 0;
if (product_can_be_archived == true) {
modal_product_actions.find('input[name="archive-action"]').prop("disabled", false);
modal_product_actions.find('input[name="archive-action"]').closest("label")
.removeClass("checkbox_action_disabled");
} else {
modal_product_actions.find('input[name="archive-action"]').prop("disabled", true);
modal_product_actions.find('input[name="archive-action"]').closest("label")
.addClass("checkbox_action_disabled");
}
openModal(
modal_product_actions.html(),
() => {
if (is_time_to('validate_product_actions')) {
commit_actions_on_product(product, modal.find('input'));
}
},
'Valider',
false
);
modal.find('input[name="minimal_stock"]').val(product.minimal_stock);
});
// Associate product to supplier on click on 'X' in the table
......@@ -1741,34 +1957,7 @@ function display_products(params) {
}
});
// Set product is NPA (Ne Pas Acheter)
$('#products_table').on('click', 'tbody td .product_npa_cb', function () {
// Save / unsave selected row
const p_id = products_table.row($(this).closest('tr')).data().id;
const npa = this.checked;
const product = products.find(p => p.id == p_id);
let modal_product_npa = $('#templates #modal_product_npa');
modal_product_npa.find(".product_name").text(product.name);
modal_product_npa.find(".product_npa").text(npa ? 'Ne Pas Acheter' : 'Peut Être Acheté');
openModal(
modal_product_npa.html(),
() => {
if (is_time_to('validate_set_product_npa')) {
set_product_npa(p_id, npa);
}
},
'Valider',
false,
true,
() => {
this.checked = !this.checked;
}
);
});
return 0;
}
......@@ -1853,6 +2042,14 @@ function update_main_screen(params) {
} else {
$("#coverage_days_input").val('');
}
if (order_doc.targeted_amount !== null) {
$('#targeted_amount_input').val(order_doc.targeted_amount);
} else {
$('#targeted_amount_input').val('');
}
if (order_doc.coeff && order_doc.coeff != 1) {
$("#percent_adjust_input").val(-Math.ceil((1 - order_doc.coeff) * 100));
}
if (order_doc.stats_date_period !== undefined && order_doc.stats_date_period !== null) {
$("#stats_date_period_select").val(order_doc.stats_date_period);
......@@ -1861,6 +2058,9 @@ function update_main_screen(params) {
}
}
function display_average_consumption_explanation() {
openModal($('#explanations').html());
}
/**
* Update DOM display on the order selection screen
*/
......@@ -2047,18 +2247,28 @@ $(document).ready(function() {
$("#coverage_form").on("submit", function(e) {
e.preventDefault();
if (is_time_to('submit_coverage_form', 1000)) {
let val = $("#coverage_days_input").val();
val = parseInt(val);
let days_val = $("#coverage_days_input").val(),
amount_val = $('#targeted_amount_input').val();
days_val = parseInt(days_val);
amount_val = parseInt(amount_val);
if (isNaN(days_val)) days_val = null;
if (isNaN(amount_val)) amount_val = null;
if (days_val !== null || amount_val !== null) {
order_doc.coverage_days = days_val;
order_doc.targeted_amount = amount_val;
compute_products_coverage_qties()
.then(() => {
debounceFunction(update_cdb_order);
update_main_screen();
})
if (!isNaN(val)) {
order_doc.coverage_days = val;
compute_products_coverage_qties();
update_cdb_order();
update_main_screen();
} else {
$("#coverage_days_input").val(order_doc.coverage_days);
alert(`Valeur non valide pour le nombre de jours de couverture !`);
$("#coverage_days_input").val(order_doc.coverage_days || '');
$('#targeted_amount_input').val(order_doc.targeted_amount || '');
alert("Ni le nombre de jours de couverture, ni le montant à atteindre sont correctement renseignés")
}
}
});
......@@ -2112,10 +2322,13 @@ $(document).ready(function() {
check_products_data()
.then(() => {
compute_products_coverage_qties();
update_main_screen();
update_cdb_order();
closeModal();
compute_products_coverage_qties()
.then(() => {
update_main_screen();
debounceFunction(update_cdb_order);
closeModal();
})
});
}
});
......@@ -2126,6 +2339,19 @@ $(document).ready(function() {
}
});
$("#refresh_order").on("click", function() {
if (is_time_to('refresh_order', 1000)) {
openModal();
check_products_data()
.then(() => {
debounceFunction(update_cdb_order);
update_main_screen();
$("#toggle_action_buttons").click();
closeModal();
});
}
});
$("#delete_order_button").on("click", function() {
if (is_time_to('press_delete_order_button', 1000)) {
let modal_remove_order = $('#templates #modal_remove_order');
......@@ -2220,6 +2446,8 @@ $(document).ready(function() {
return 0;
});
$(document).on("click", ".average_consumption_explanation_icon", display_average_consumption_explanation);
$.datepicker.regional['fr'] = {
monthNames: [
'Janvier',
......@@ -2355,6 +2583,21 @@ $(document).ready(function() {
alert('Erreur lors de la récupération des articles, rechargez la page plus tard');
}
});
$(document).on('click', '.accordion', function() {
/* Toggle between adding and removing the "active" class,
to highlight the button that controls the panel */
this.classList.toggle("active");
/* Toggle between hiding and showing the active panel */
var panel = this.nextElementSibling;
if (panel.style.display === "block") {
panel.style.display = "none";
} else {
panel.style.display = "block";
}
});
} else {
$('#not_connected_content').show();
}
......
from outils.common_imports import *
from outils.for_view_imports import *
from outils.common import OdooAPI
from orders.models import Order, Orders, CagetteSuppliers
from products.models import CagetteProduct, CagetteProducts
......@@ -20,7 +21,9 @@ def helper(request):
'couchdb_server': settings.COUCHDB['url'],
'db': settings.COUCHDB['dbs']['orders'],
'odoo_server': settings.ODOO['url'],
'metabase_url': getattr(settings, 'ORDERS_HELPER_METABASE_URL', '')
'metabase_url': getattr(settings, 'ORDERS_HELPER_METABASE_URL', ''),
'nb_past_days_to_compute_sales_average': OdooAPI().get_system_param('lacagette_products.nb_past_days_to_compute_sales_average'),
'nb_of_consecutive_non_sale_days_considered_as_break': OdooAPI().get_system_param('lacagette_products.nb_of_consecutive_non_sale_days_considered_as_break')
}
template = loader.get_template('orders/helper.html')
......
......@@ -47,7 +47,7 @@ class OdooAPI:
order='id ASC'):
"""Main api request, retrieving data according search conditions."""
fields_and_context = {'fields': fields,
'context': {'lang': 'fr_FR','tz':'Europe/Paris'},
'context': {'lang': 'fr_FR', 'tz': 'Europe/Paris'},
'limit': limit,
'offset': offset,
'order': order
......@@ -59,8 +59,11 @@ class OdooAPI:
def update(self, entity, ids, fields):
"""Update entities which have ids, with new fields values."""
context = {
'context': {'lang': 'fr_FR', 'tz': 'Europe/Paris'}
}
return self.models.execute_kw(self.db, self.uid, self.passwd,
entity, 'write', [ids, fields])
entity, 'write', [ids, fields], context)
def create(self, entity, fields):
"""Create entity instance with given fields values."""
......@@ -74,6 +77,18 @@ class OdooAPI:
def authenticate(self, login, password):
return self.common.authenticate(self.db, login, password, {})
def get_system_param(self, key):
value = ''
try:
res = self.search_read('ir.config_parameter',
[['key', '=', key]],
['value'])
if res:
value = res[0]['value']
except Exception as e:
coop_logger.error('get_system_param: (%s) %s', key, str(e))
return value
class CouchDB:
"""Class to handle interactions with CouchDB"""
......
# coding: utf-8
"""Interact with Odoo by python code
Before launching script, launch the following command:
export DJANGO_SETTINGS_MODULE='scripts_settings'
(a file named scripts_settings.py is present in this directory)
"""
#
import sys, getopt, os
sys.path.append(os.path.abspath('../..'))
from outils.common import OdooAPI
import datetime
def main():
"""For coops in alert state, reajust points counter so they get to 0 after adding their makeups to their actual calculated total"""
api = OdooAPI()
cond = [
'|',
'|',
'|',
['cooperative_state','=', 'alert'],
['cooperative_state','=', 'unsubscribed'],
['cooperative_state','=', 'suspended'],
['cooperative_state','=', 'delay']
]
fields = ['id', 'name', 'makeups_to_do', 'cooperative_state']
res = api.search_read('res.partner', cond, fields)
cpt = 0
for p in res:
# Get real points count
cond = [['partner_id','=', p["id"]], ['type','=', 'standard']]
fields = ['point_qty', 'name']
res_counter_event = api.search_read('shift.counter.event', cond, fields)
total_pts = 0
for item in res_counter_event:
total_pts += item['point_qty']
# Get future makeups
cond = [
['name','=', p["name"]],
['shift_type','=', 'standard'],
['is_makeup','=', True],
['date_begin', '>=', datetime.datetime.now().isoformat()]
]
fields = ['id']
res_shift_reg = api.search_read('shift.registration', cond, fields)
final_theoric_pts = total_pts + p['makeups_to_do'] + len(res_shift_reg)
if final_theoric_pts < 0:
cpt += 1
print(p["name"])
print('theoric total : ' + str(final_theoric_pts))
print('>> total_pts : ' + str(total_pts))
print('>> makeups_to_do : ' + str(p['makeups_to_do']))
print('>> nb future makeups : ' + str(len(res_shift_reg)))
"""
For unsubscribed people,
adding a point and going through run_process_target_status may lead them to be suspended
whereas they're not subscribed to any shift.
Adding a fake point will lead odoo to reset Unsuscribed status.
"""
add_second_corrective_pt = p['cooperative_state'] == 'unsubscribed'
# Add/remove points so their final theoric points is 0
points_to_add = -final_theoric_pts
fields = {
'name': "Correction de l'historique de points",
'shift_id': False,
'type': 'standard',
'partner_id': p['id'],
'point_qty': points_to_add
}
api.create('shift.counter.event', fields)
print('===> Pts ajoutés : ' + str(points_to_add))
if add_second_corrective_pt is True:
api.execute('res.partner', 'run_process_target_status', [])
fields = {
'name': "Correction de l'historique - Sécurité pour les désinscrit.es",
'shift_id': False,
'type': 'standard',
'partner_id': p['id'],
'point_qty': 0
}
api.create('shift.counter.event', fields)
print('===> Pt correctif pour désinscrits')
print('--------')
print('Nb de personnes concernées : ' + str(cpt))
if __name__ == "__main__":
main()
\ No newline at end of file
......@@ -148,6 +148,10 @@ footer { position: fixed;
width: 230px !important;
}
.tooltip .tooltip-xl {
width: 320px !important;
}
.tooltip .tt_twolines {
top: -15px !important;
}
......@@ -193,4 +197,17 @@ footer { position: fixed;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QYFAhkSsdes/QAAA8dJREFUOMvVlGtMW2UYx//POaWHXg6lLaW0ypAtw1UCgbniNOLcVOLmAjHZolOYlxmTGXVZdAnRfXQm+7SoU4mXaOaiZsEpC9FkiQs6Z6bdCnNYruM6KNBw6YWewzl9z+sHImEWv+vz7XmT95f/+3/+7wP814v+efDOV3/SoX3lHAA+6ODeUFfMfjOWMADgdk+eEKz0pF7aQdMAcOKLLjrcVMVX3xdWN29/GhYP7SvnP0cWfS8caSkfHZsPE9Fgnt02JNutQ0QYHB2dDz9/pKX8QjjuO9xUxd/66HdxTeCHZ3rojQObGQBcuNjfplkD3b19Y/6MrimSaKgSMmpGU5WevmE/swa6Oy73tQHA0Rdr2Mmv/6A1n9w9suQ7097Z9lM4FlTgTDrzZTu4StXVfpiI48rVcUDM5cmEksrFnHxfpTtU/3BFQzCQF/2bYVoNbH7zmItbSoMj40JSzmMyX5qDvriA7QdrIIpA+3cdsMpu0nXI8cV0MtKXCPZev+gCEM1S2NHPvWfP/hL+7FSr3+0p5RBEyhEN5JCKYr8XnASMT0xBNyzQGQeI8fjsGD39RMPk7se2bd5ZtTyoFYXftF6y37gx7NeUtJJOTFlAHDZLDuILU3j3+H5oOrD3yWbIztugaAzgnBKJuBLpGfQrS8wO4FZgV+c1IxaLgWVU0tMLEETCos4xMzEIv9cJXQcyagIwigDGwJgOAtHAwAhisQUjy0ORGERiELgG4iakkzo4MYAxcM5hAMi1WWG1yYCJIcMUaBkVRLdGeSU2995TLWzcUAzONJ7J6FBVBYIggMzmFbvdBV44Corg8vjhzC+EJEl8U1kJtgYrhCzgc/vvTwXKSib1paRFVRVORDAJAsw5FuTaJEhWM2SHB3mOAlhkNxwuLzeJsGwqWzf5TFNdKgtY5qHp6ZFf67Y/sAVadCaVY5YACDDb3Oi4NIjLnWMw2QthCBIsVhsUTU9tvXsjeq9+X1d75/KEs4LNOfcdf/+HthMnvwxOD0wmHaXr7ZItn2wuH2SnBzbZAbPJwpPx+VQuzcm7dgRCB57a1uBzUDRL4bfnI0RE0eaXd9W89mpjqHZnUI5Hh2l2dkZZUhOqpi2qSmpOmZ64Tuu9qlz/SEXo6MEHa3wOip46F1n7633eekV8ds8Wxjn37Wl63VVa+ej5oeEZ/82ZBETJjpJ1Rbij2D3Z/1trXUvLsblCK0XfOx0SX2kMsn9dX+d+7Kf6h8o4AIykuffjT8L20LU+w4AZd5VvEPY+XpWqLV327HR7DzXuDnD8r+ovkBehJ8i+y8YAAAAASUVORK5CYII=);
}
.notifyjs-cancelable-base .buttons {width: 190px; margin: 5px auto;}
.notifyjs-cancelable-base button {width: 90px;text-align: center; margin: 3px;}
\ No newline at end of file
.notifyjs-cancelable-base button {width: 90px;text-align: center; margin: 3px;}
button.accordion::after {
content: '\002B';
color: #777;
font-weight: bold;
float: right;
margin-left: 5px;
}
button.accordion.active::after {
content: "\2212";
}
......@@ -30,15 +30,3 @@ input.link {min-width: 50em;}
overflow: hidden;
}
button.accordion::after {
content: '\002B';
color: #777;
font-weight: bold;
float: right;
margin-left: 5px;
}
button.accordion.active::after {
content: "\2212";
}
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -150,7 +150,6 @@ function get_module_settings() {
}
get_module_settings();
$(document).on('click', '.accordion', function(){
/* Toggle between adding and removing the "active" class,
to highlight the button that controls the panel */
......@@ -163,4 +162,5 @@ $(document).on('click', '.accordion', function(){
} else {
panel.style.display = "block";
}
});
\ No newline at end of file
});
......@@ -189,34 +189,51 @@ class ExportPOS(View):
kept_sessions_id.append(s['id'])
key = y + '-' + m + '-' + d
if not (key in totals):
totals[key] = {'CB': 0, 'CSH': 0, 'CHQ': 0, 'TOTAL': 0}
totals[key] = {'CB': 0,
'CSH': 0,
'CHQ': 0,
'CB_DEJ': 0,
'CHQ_DEJ': 0,
'TOTAL': 0}
sub_total = 0
cb = chq = csh = 0
cb = chq = csh = cbd = chqd = 0
for p in s['payments']:
# p['name'] is a sequence generated string
# Test order is important as CHEQDEJ contains CHEQ for ex.
# p['journal'] could be used but easier to change in Odoo interface
sub_amount = round(p['total_amount'], 2)
if 'CSH' in p['name']:
csh = round(p['total_amount'], 2)
csh = sub_amount
elif 'CHEQDEJ' in p['name']:
chqd = sub_amount
elif 'CHEQ' in p['name']:
chq = round(p['total_amount'], 2)
chq = sub_amount
elif 'CBDEJ' in p['name']:
cbd = sub_amount
elif 'CB' in p['name']:
cb = round(p['total_amount'], 2)
sub_total += round(p['total_amount'], 2)
cb = sub_amount
sub_total += sub_amount
totals[key]['CB'] += cb
totals[key]['CSH'] += csh
totals[key]['CHQ'] += chq
totals[key]['CB_DEJ'] += cbd
totals[key]['CHQ_DEJ'] += chqd
totals[key]['TOTAL'] += round(sub_total, 2)
details_lines.append([mois, s['mm_dates']['min'], s['mm_dates']['min'], s['caisse'], s['name'],
cb, csh, chq, sub_total])
cb, csh, chq, cbd, chqd, sub_total])
wb = Workbook()
ws1 = wb.create_sheet("Totaux " + mois, 0)
ws2 = wb.create_sheet("Détails " + mois, 1)
ws1.append(['date', 'CB', 'CSH', 'CHQ', 'Total'])
ws1.append(['date', 'CB', 'CSH', 'CHQ', 'CB_DEJ', 'CHQ_DEJ', 'Total'])
for day in sorted(totals):
cb = totals[day]['CB']
csh = totals[day]['CSH']
chq = totals[day]['CHQ']
cbd = totals[day]['CB_DEJ']
chqd = totals[day]['CHQ_DEJ']
total = totals[day]['TOTAL']
ws1.append([day, cb, csh, chq, total])
ws2.append(['mois', 'min_date', 'max_date', 'Caisse', 'session', 'CB', 'CSH','CHQ', 'total'])
ws1.append([day, cb, csh, chq, cbd, chqd, total])
ws2.append(['mois', 'min_date', 'max_date', 'Caisse', 'session', 'CB', 'CSH','CHQ', 'CB_DEJ', 'CHQ_DEJ', 'total'])
for row in details_lines:
ws2.append(row)
wb_name = 'export_sessions__' + mois + '.xlsx'
......
......@@ -7,6 +7,7 @@ import csv
import tempfile
import pymysql.cursors
import datetime
import re
vcats = []
......@@ -252,10 +253,52 @@ class CagetteProduct(models.Model):
return res
@staticmethod
def commit_actions_on_product(data):
""" Update:
- NPA (ne pas acheter)
- Product is active
- Minimal stock
"""
res = {}
try:
api = OdooAPI()
# Minimal stock
f = {'minimal_stock': data['minimal_stock']}
# NPA
if 'simple-npa' in data['npa']:
f['purchase_ok'] = 0
if 'npa-in-name' in data['npa']:
# Add [NPA] in product name if needed
f['name'] = data['name'] if ('[NPA]' in data['name']) else data['name'] + " [NPA]"
f['purchase_ok'] = 0
elif '[NPA]' in data['name']:
# Remove [NPA] from name
f['name'] = re.sub(r'( \[NPA\])', '', data['name'])
current_name = data['name'] if ('name' not in f) else f['name']
if 'fds-in-name' in data['npa']:
f['name'] = current_name if '[FDS]' in data['name'] else current_name + " [FDS]"
f['purchase_ok'] = 0
elif '[FDS]' in current_name:
f['name'] = re.sub(r'( \[FDS\])', '', current_name)
if len(data['npa']) == 0:
f['purchase_ok'] = 1
# Active
f["active"] = not data['to_archive']
res["update"] = api.update('product.template', data['id'], f)
except Exception as e:
res["error"] = str(e)
coop_logger.error("update_npa_and_minimal_stock : %s %s", str(e), str(data))
return res
class CagetteProducts(models.Model):
"""Initially used to make massive barcode update."""
@staticmethod
def get_simple_list():
res = []
......@@ -577,9 +620,10 @@ class CagetteProducts(models.Model):
"uom_id",
"purchase_ok",
"supplier_taxes_id",
"product_variant_ids"
"product_variant_ids",
"minimal_stock"
]
c = [['id', 'in', ptids], ['purchase_ok', '=', True]]
c = [['id', 'in', ptids], ['purchase_ok', '=', True], ['active', '=', True]]
products_t = api.search_read('product.template', c, f)
filtered_products_t = [p for p in products_t if p["state"] != "end" and p["state"] != "obsolete"]
......
......@@ -11,6 +11,7 @@ urlpatterns = [
url(r'^update_product_stock$', views.update_product_stock),
url(r'^update_product_purchase_ok$', views.update_product_purchase_ok),
url(r'^update_product_internal_ref$', views.update_product_internal_ref),
url(r'^commit_actions_on_product$', views.commit_actions_on_product),
url(r'^labels_appli_csv(\/?[a-z]*)$', views.labels_appli_csv, name='labels_appli_csv'),
url(r'^label_print/([0-9]+)/?([0-9\.]*)/?([a-z]*)/?([0-9]*)$', views.label_print),
url(r'^shelf_labels$', views.shelf_labels), # massive print
......
......@@ -3,6 +3,7 @@
from outils.common_imports import *
from outils.for_view_imports import *
from members.models import CagetteUser
from products.models import CagetteProduct
from products.models import CagetteProducts
from inventory.models import CagetteInventory
......@@ -99,31 +100,88 @@ def update_product_stock(request):
'products': [p]
}
res['inventory'] = CagetteInventory.update_stock_with_shelf_inventory_data(inventory_data)
res['inventory'] = CagetteInventory.update_products_stock(inventory_data)
return JsonResponse({"res": res})
def update_product_purchase_ok(request):
res = {}
data = json.loads(request.body.decode())
is_connected_user = CagetteUser.are_credentials_ok(request)
if is_connected_user is True:
data = json.loads(request.body.decode())
res = CagetteProduct.update_product_purchase_ok(data["product_tmpl_id"], data["purchase_ok"])
res = CagetteProduct.update_product_purchase_ok(data["product_tmpl_id"], data["purchase_ok"])
if ('error' in res):
return JsonResponse(res, status=500)
if ('error' in res):
return JsonResponse(res, status=500)
else:
return JsonResponse({"res": res})
else:
return JsonResponse({"res": res})
return JsonResponse(res, status=403)
def update_product_internal_ref(request):
res = {}
data = json.loads(request.body.decode())
is_connected_user = CagetteUser.are_credentials_ok(request)
if is_connected_user is True:
data = json.loads(request.body.decode())
res = CagetteProduct.update_product_internal_ref(data["product_tmpl_id"], data["default_code"])
res = CagetteProduct.update_product_internal_ref(data["product_tmpl_id"], data["default_code"])
if ('error' in res):
return JsonResponse(res, status=500)
if ('error' in res):
return JsonResponse(res, status=500)
else:
return JsonResponse({"res": res})
else:
return JsonResponse({"res": res})
return JsonResponse(res, status=403)
def commit_actions_on_product(request):
res = {}
is_connected_user = CagetteUser.are_credentials_ok(request)
if is_connected_user is True:
try:
data = json.loads(request.body.decode())
product_data = CagetteProducts.get_products_for_order_helper(None, [data["id"]])["products"][0]
# Don't allow to archive product if incomin qty > 0
if data["to_archive"] is True and product_data["incoming_qty"] > 0:
res["code"] = "archiving_with_incoming_qty"
return JsonResponse(res, status=500)
res = CagetteProduct.commit_actions_on_product(data)
# If stock > 0: do inventory to set stock to 0
if data["to_archive"] is True and product_data["qty_available"] != 0:
try:
p = {
'id': product_data['product_variant_ids'][0], # Need product id
'uom_id': product_data['uom_id'],
'qty': -product_data["qty_available"]
}
inventory_data = {
'name': 'Archivage - ' + product_data['name'],
'products': [p]
}
res_inventory = CagetteInventory.update_products_stock(inventory_data)
if res_inventory['errors'] or res_inventory['missed']:
res["code"] = "error_stock_update"
res["error"] = res_inventory['errors']
return JsonResponse(res, status=500)
except Exception as e:
res["code"] = "error_stock_update"
return JsonResponse(res, status=500)
except Exception as e:
res['error'] = str(e)
coop_logger.error("Update npa and minimal stock : %s", res['error'])
if ('error' in res):
return JsonResponse(res, status=500)
else:
return JsonResponse({"res": res})
else:
return JsonResponse(res, status=403)
def labels_appli_csv(request, params):
"""Generate files to put in DAV directory to be retrieved by scales app."""
......
......@@ -14,49 +14,38 @@ class CagetteSales(models.Model):
def get_sales(self, date_from, date_to):
res = []
# Get pos sessions
cond = [['stop_at', '>=', date_from], ['stop_at', '<=', date_to], ['state', '=', "closed"]]
fields = []
sessions = self.o_api.search_read('pos.session', cond, fields)
# Get pos orders
cond = [['date_order', '>=', date_from], ['date_order', '<=', date_to]]
fields = ['partner_id', 'statement_ids', 'name']
orders = self.o_api.search_read('pos.order', cond, fields)
# Get bank statements of these sessions
statements = []
for s in sessions:
statements = statements + s["statement_ids"]
statements_partners = {}
statements_orders = {}
for o in orders:
statements = statements + o["statement_ids"]
for s in o["statement_ids"]:
statements_partners[s] = o["partner_id"][1]
statements_orders[s] = o["name"]
# Get payment lines
cond = [['statement_id', 'in', statements]]
fields = ["partner_id", "amount", "journal_id", "create_date", "date"]
cond = [['id', 'in', statements]]
fields = ["amount", "journal_id", "create_date"]
payments = self.o_api.search_read('account.bank.statement.line', cond, fields, order="create_date ASC", limit=50000)
item = None
try:
for payment in payments:
# POS session can contain payments from another day (closing session on next morning, ...)
if payment["date"] >= date_from and payment["date"] <= date_to:
# If the consecutive payment in the results is from the same partner on the same day, we consider it's the same basket
if item is not None and item["partner_id"][0] == payment["partner_id"][0] and item["date"] == payment["date"]:
res[len(res)-1]["total_amount"] += round(float(payment["amount"]), 2)
res[len(res)-1]["payments"].append({
"amount": round(float(payment["amount"]), 2),
"journal_id": payment["journal_id"]
})
else:
item = {
"partner_id": payment["partner_id"],
res.append({
"partner": statements_partners[payment["id"]],
"create_date": payment["create_date"],
"date": payment["date"],
"pos_order_name": statements_orders[payment["id"]],
"total_amount": round(float(payment["amount"]), 2),
"payments": [
{
"amount": round(float(payment["amount"]), 2),
"journal_id": payment["journal_id"]
}
}
]
}
res.append(item)
})
except Exception as e:
pass
coop_logger.error("get_sales %s", str(e))
return res
......@@ -38,20 +38,23 @@ function display_orders(orders) {
columns:[
{
data:"create_date",
title:"Date de vente",
title:"Date enregistrement",
width: "10%"
},
{
data:"partner_id",
data:"pos_order_name",
title:"Ref. Caisse",
width: "10%"
},
{
data:"partner",
title:"Membre",
width: "50%",
render: function (data) {
return data[1];
}
width: "40%"
},
{
data:"total_amount",
title: "Montant du panier",
title: "Montant dû",
className:"dt-body-center",
render: function (data) {
return parseFloat(data).toFixed(2) + ' €';
......
......@@ -173,7 +173,7 @@ def do_shelf_inventory(request):
return JsonResponse(res, status=500)
# Proceed with inventory
res['inventory'] = CagetteInventory.update_stock_with_shelf_inventory_data(full_inventory_data)
res['inventory'] = CagetteInventory.update_products_stock(full_inventory_data)
full_inventory_data['inventory_id'] = res['inventory']['inv_id']
shelf_data['last_inventory_id'] = res['inventory']['inv_id']
......
......@@ -155,6 +155,8 @@ class CagetteShift(models.Model):
"origin": 'memberspace',
"is_makeup": data['is_makeup'],
"state": 'open'}
if shift_type == "standard" and data['is_makeup'] is not True:
fieldsDatas['template_created'] = 1 # It's not true but otherwise, presence add 1 standard point, which is not wanted
st_r_id = self.o_api.create('shift.registration', fieldsDatas)
except Exception as e:
......@@ -211,7 +213,7 @@ class CagetteShift(models.Model):
action = 'create'
# Get partner extension ids
cond = [['id','=',data['idPartner']]]
cond = [['id', '=', data['idPartner']]]
fields = ['extension_ids']
partner_extensions = self.o_api.search_read('res.partner', cond, fields)
response = False
......
......@@ -46,7 +46,7 @@ def do_movement(request):
'products': products
}
res = CagetteInventory.update_stock_with_shelf_inventory_data(inventory_data)
res = CagetteInventory.update_products_stock(inventory_data)
else:
res = CagetteStock.do_stock_movement(data)
......
......@@ -17,7 +17,7 @@
<div style="width: 10%" class="fr txtright"><i class="fas fa-times"></i></div>
</div>
<div id="envelop_cashing_success" class="alert--success clearfix custom_alert" onClick="toggle_success_alert()">
<div style="width: 90%" class="fl txtleft">Enveloppe encaissée !</div>
<div style="width: 90%" class="fl txtleft success_alert_content">Enveloppe encaissée !</div>
<div style="width: 10%" class="fr txtright"><i class="fas fa-times"></i></div>
</div>
<div id="envelop_deletion_success" class="alert--success clearfix custom_alert" onClick="toggle_deleted_alert()">
......@@ -39,8 +39,49 @@
</div>
</section>
<section id="archive_cash">
<hr>
<h2 class="txtcenter">Enveloppes de liquide archivées</h2>
<div id="archive_cash_envelops" class="flex-container flex-column-reverse">
</div>
</section>
<section id="archive_ch">
<hr>
<h2 class="txtcenter">Enveloppes de chèques archivées</h2>
<div id="archive_ch_envelops" class="flex-container flex-column-reverse">
</div>
</section>
</section>
<div id="templates" style="display:none;">
<div id="modal_update_envelop">
<div class="modal_update_envelop_content">
<h3 class="envelop_name"></h3>
<div class="envelop_lines"></div>
<div class="envelop_comments_area">
<p>Commentaires</p>
<textarea class="envelop_comments"></textarea>
</div>
</div>
</div>
<div id="update_envelop_line_template">
<div class="update_envelop_line">
<div class="line_partner_name_container">
<span class="line_number"></span>
<span class="line_partner_name"></span>
</div>
<div class="line_partner_input_container">
<input type="text" class="line_partner_amount" placeholder="Montant">
<i class="fas fa-trash-alt fa-lg delete_envelop_line_icon"></i>
</div>
<div class="deleted_line_through"></div>
</div>
</div>
</div>
<script src="{% static "js/pouchdb.min.js" %}"></script>
<script type="text/javascript">
{%if must_identify %}
......
......@@ -52,7 +52,7 @@
<div class="row-1 grid-2">
<div class="col-1">
<div class="label">
Biper le badge, ou saisissez le n° de coop. ou le nom
Biper le badge, ou saisir le n° de coop. ou le nom
</div>
Recherche :
<input type="text" name="search_string" autocomplete="off" />
......@@ -107,10 +107,12 @@
</div>
<div id="cooperative_state">
</div>
<div id="status_explanation" style="font-weight:bold;">
</div>
<div id="next_shifts">
</div>
</div>
<a class="btn" data-next="first_page">Coopérateur suivant</a>
<a class="btn" data-next="first_page">Coopérateur.rice suivant.e</a>
</div>
<div class="col-1">
<section id="member_advice">
......@@ -206,7 +208,7 @@
{% endif %}
</section>
<div class="col-2"></div>
<a class="btn col-2" data-next="first_page">Coopérateur suivant</a>
<a class="btn col-2" data-next="first_page">Coopérateur.ice suivant.e</a>
<div class="col-2"></div>
</section>
<section class="grid-6 has-gutter" id="rattrapage_1">
......
......@@ -107,7 +107,7 @@
<div class="input-container panel">
<div class="grp_text">
<h3><b>Créneau/service c'est quoi la différence?</b></h3>
<h3><b>Créneau/service c'est quoi la différence ?</b></h3>
<p>
Un créneau, c'est une plage récurrente, par exemple, tous les jeudi de semaine A de 13h30 à 16h30.<br/>
Un service, c'est une plage horaire en particulier, par exemple le jeudi 28 novembre de 13h30 à 16h30.
......@@ -116,7 +116,7 @@
</div>
<div class="grp_text">
<h3><b>Échanger son service:</b></h3>
<h3><b>Échanger son service</b></h3>
<p>
Si tu ne peux pas venir effectuer ton service à la date prévue il te faut l'échanger sur ton espace membre.<br/>
<b>ATTENTION:</b> si tu es en binôme c'est via l'espace membre du titulaire du binôme qu'il faut le faire.
......@@ -132,6 +132,24 @@
</a>
</div>
</div>
<div class="grp_text">
<h3><b>Oubli de validation de service</b></h3>
<p>
Si tu as effectué ton service mais que tu as oublié de le valider à l'entrée du magasin, il te faut remplir le formulaire suivant en indiquant la date de ton service.
</p>
<div class="faq_link_button_area">
<a
href="javascript:void(0);"
target="_blank"
type="button"
class="btn--primary faq_link_button"
id="request_form_link_btn2"
>
Oubli validation service
</a>
</div>
</div>
<div class="grp_text">
<h3><b>Demande de congé maladie ou parental</b></h3>
......@@ -142,9 +160,8 @@
<p></b></p>
</div>
<div class="grp_text">
<b><h3>Les congés maladie:</h3></b>
Les congés maladie peuvent être pris en cas d’impossibilité physique de réaliser son service pendant une longue durée qui prend en compte<b> minimum 2 services</b>. Si ton impossibilité est d'un mois il t'es demandé de déplacer ton service.<br />
<div class="grp_text"><h3><b>Les congés maladie</b></h3>
Les congés maladie peuvent être pris en cas d’impossibilité physique de réaliser son service pendant une longue durée qui prend en compte<b> minimum 2 services</b>. Si ton impossibilité est d'un mois il t'est demandé de déplacer ton service.<br />
En cas de rhume nous encourageons les coops à simplement déplacer leur service depuis l’espace membre. La coop a besoin de la participation de chacun.e !<br />
<b>ATTENTION:</b> Compte tenu de la facilité offerte par le statut de binôme, les personnes formant un binôme ne pourront pas<br />
bénéficier de congés maladie. Il sera alors possible de se désolidariser de son binôme en remplissant le formulaire adéquat sur l’espace membre afin d’en bénéficier.<br />
......@@ -398,7 +415,9 @@
Nous avons créé des formulaires spécifiques pour la plupart des problèmes rencontrés par les membres. Changer de créneau, créer un binôme, ajouter un produit à la gamme, partir en vacances... <br />
Cela dit, nous en découvrons de nouveaux tous les jours.<br />
Si tu n'as pas su quel formulaire remplir, tu es au bon endroit. <br />
Vas-y dit nous tout !<br />
Vas-y dit nous tout !<br /><br />
Attention: si tu souhaites contacter le BDM pour prévenir que tu seras absent-e à ton service cela ne sert à rien! Il te faut déplacer ton service via ton espace membre. Il n'est cependant pas possible d'échanger un service qui commence dans moins de 24h pour des raisons de logistiques. Si tu ne peux pas venir tu seras donc comptabilisé-e absent-e. Tu basculeras en statut "Rattrapage" et ne pourras plus faire tes courses. Il te faudra sélectionner dans ton espace membre un rattrapage à faire dans les 6 prochains mois pour basculer en statut "Délai" et pouvoir faire de nouveau tes courses.<br />
Merci de ne pas contacter le Bureau des membres pour cela, il te donnera exactement la même réponse.<br />
<div class="faq_link_button_area">
<a
href="javascript:void(0);"
......
......@@ -71,7 +71,8 @@
merci de contacter le bureau des membres pour résoudre ce problème en remplissant ce formulaire : </h3>
</div>
<div id="comite_template">
<h3>Vous êtes inscrit.e dans le service des comités, vous n'avez pas accès au calendrier d'échange des services car vous vous organisez directement avec le responsable du comité. Si vous avez des rattrapages à réaliser, merci de contacter le responsable du comité qui vous aidera à planifier les rattrapages ou trouver une solution</h3>
<h3>Vous êtes inscrit.e dans le service des comités, vous n'avez pas accès au calendrier d'échange des services car vous vous organisez directement avec le responsable du comité. Si vous avez des rattrapages à réaliser, merci de contacter le responsable du comité qui vous aidera à planifier les rattrapages ou trouver une solution.</h3>
<h3>Le calendrier ci-dessous est en lecture seule</h3>
</div>
</div>
</div>
......
......@@ -13,6 +13,7 @@
</div>
<div id="comite_content" class="shifts_exchange_page_content">
<div class="comite_content_msg"></div>
<div id="read_only_calendar"></div>
</div>
<div id="suspended_content" class="shifts_exchange_page_content">
<h3>
......
<div>
<button type="button" class="accordion" style="width:100%"><label>Comment sont calculées les conso. moyennes / jour ?</label></button>
<div class="txtleft" style="display: none;">
<p>
La fonction qui calcule les consommations moyennes prend en paramètre une date de départ. <br/>
Si elle n'est pas indiquée, la date prise en compte sera "<em>aujourd'hui - nb de jours paramétré dans Odoo</em>".<br/>
Ce nombre de jours paramétrable se trouve en suivant les menus suivants :<br>
Configuration > Technique > Paramètres > Paramètres systèmes. <br/>
La valeur est définie avec la clef "<em>lacagette_products.nb_past_days_to_compute_sales_average</em>".<br/>
Ce paramètre vaut <strong>{{nb_past_days_to_compute_sales_average}}</strong> au moment du chargement de cette page.<br/>
Les ventes du dimanche sont exclues du calcul.<br/>
</p>
<p>
Une requête est faite sur l'ensemble des passages en caisse, de la date de départ à hier, récupérant pour tous les jours de la période (dimanches exclus) les quantités vendues des articles achetés chez le fournisseur.<br/>
Pour chaque article, le nombre de jours considérés pour faire la moyenne est défini commme suit :<br/>
<em>Nb de jours ouvrés de la période - Nb de jours des périodes de rupture</em><br/>
Les périodes de ruptures sont caractérisées par un nombre de jours consécutifs assez important de jours sans vente de l'article.<br/>
Le nombre de jours consécutifs sans vente pour considérer l'article en rupture est actuellement de <strong>{{nb_of_consecutive_non_sale_days_considered_as_break}}</strong><br/>
(c'est le paramètre système avec la clef "<em>lacagette_products.nb_of_consecutive_non_sale_days_considered_as_break</em>").<br/>
</p>
<p>
Pour chaque article, la consommation moyenne par jour est obtenue en divisant la quantité totale vendue sur la période par le nombre de jours significatifs.
</p>
</div>
</div>
<div>
<button type="button" class="accordion" style="width:100%"><label>Comment sont calculés les besoins ?</label></button>
<div class="txtleft" style="display: none;">
La quantité à commander pour couvrir les besoins (en jours) est le résultat de :
<p>
(<em>nb_jours</em> <strong>x</strong> <em>conso_moyenne</em>) <strong>-</strong> <em>stock_existant</em> <strong>-</strong> <em>quantités_entrantes</em> <strong>+</strong> <em>stock_minimum</em>
</p>
</div>
</div>
......@@ -55,6 +55,9 @@
<button type="button" class='btn--primary action_button' id="do_inventory" style="display:none;">
Faire un inventaire
</button>
<button type="button" class='btn--primary action_button' id="refresh_order">
Rafraîchir la commande
</button>
<button type="button" class='btn--danger action_button' id="delete_order_button">
Supprimer la commande
</button>
......@@ -90,8 +93,14 @@
</select>
</form>
<form action="javascript:;" id="coverage_form" class="order_form_item">
<input type="number" name="coverage_days" id="coverage_days_input" placeholder="Nb jours de couverture" min="1">
<button type="submit" class='btn--primary'>Calculer les besoins</button>
<div class="input-wrapper">
<input type="number" name="coverage_days" id="coverage_days_input" placeholder="Nb jours de couverture" min="1">
<input type="number" name="targeted_amount" id="targeted_amount_input" placeholder="Montant en €" min="1">
<input type="number" name="percent_adjustement" id="percent_adjust_input" placeholder="ajustement en %">
</div>
<div>
<button type="submit" class='btn--primary'>Calculer les besoins</button> <i class='main fa fa-info-circle fa-lg average_consumption_explanation_icon'></i>
</div>
</form>
</div>
......@@ -267,14 +276,30 @@
<hr/>
</div>
<div id="modal_product_npa">
<h3>Attention !</h3>
<p>
Vous vous apprêtez à passer le produit <span class="product_name"></span> en <span class="product_npa"></span>.<br/>
Dès que vous aurez cliqué sur "Valider", le produit sera retiré du tableau et l'information sera enregistrée dans Odoo.
</p>
<p>Êtez-vous sûr ?</p>
<hr/>
<div id="modal_product_actions">
Actions sur <h3><span class="product_name"></span></h3>
<div class="modal_product_actions_section">
<h4 class="modal_product_actions_title">NPA</h4>
<div class="npa-options">
<label><input type="checkbox" name="npa-actions" value="simple-npa" /> Mettre le produit en NPA </label>
<label><input type="checkbox" name="npa-actions" value="npa-in-name" /> Mettre le produit en NPA et afficher NPA</label>
<label><input type="checkbox" name="npa-actions" value="fds-in-name" /> Mettre le produit en NPA et afficher FDS</label>
</div>
</div>
<div class="modal_product_actions_section">
<h4 class="modal_product_actions_title">Archiver le produit</h4>
<label class="checkbox_action_disabled"><input type="checkbox" name="archive-action" value="archive" disabled /> Archiver </label>
<div class="tooltip">
<i class='main fa fa-info-circle'></i>
<span class="tooltiptext tooltip-xl tt_twolines">
Un produit ne peut pas être archivé si une quantité entrante est prévue.
</span>
</div>
</div>
<div class="modal_product_actions_section">
<h4 class="modal_product_actions_title">Stock minimum</h4>
<input type="number" name="minimal_stock" value="" />
</div>
</div>
<div id="modal_create_order">
......@@ -291,7 +316,9 @@
<br/>
<hr/>
</div>
<div id="explanations">
{% include "orders/explanations.html" %}
</div>
<div id="modal_create_order__supplier_date_planned">
<div class="modal_input_area">
<span class="modal_input_label supplier_name"></span>
......
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