Commit 26ca1150 by Damien Moulard Committed by Alexis Aoun

fix couchdb batch updates

parent a5b8f0f3
...@@ -58,7 +58,6 @@ function reload() { ...@@ -58,7 +58,6 @@ function reload() {
function check_before_goto(id) { function check_before_goto(id) {
const order_doc_id = 'order_' + id; const order_doc_id = 'order_' + id;
dbc.get(order_doc_id).then((doc) => { dbc.get(order_doc_id).then((doc) => {
console.log(doc);
if (doc.last_update.fingerprint !== null && doc.last_update.fingerprint !== fingerprint) { if (doc.last_update.fingerprint !== null && doc.last_update.fingerprint !== fingerprint) {
time_diff = dates_diff(new Date(doc.last_update.timestamp), new Date()) time_diff = dates_diff(new Date(doc.last_update.timestamp), new Date())
diff_str = `` diff_str = ``
...@@ -151,7 +150,7 @@ function create_order_doc(order_data, go_to_order = false) { ...@@ -151,7 +150,7 @@ function create_order_doc(order_data, go_to_order = false) {
}).catch((err) => { }).catch((err) => {
error = { error = {
msg: 'Erreur dans la creation de la commande dans couchdb', msg: 'Erreur dans la creation de la commande dans couchdb',
ctx: 'validatePrices', ctx: 'create_order_doc',
details: err details: err
}; };
report_JS_error(error, 'reception'); report_JS_error(error, 'reception');
...@@ -254,8 +253,6 @@ function group_action() { ...@@ -254,8 +253,6 @@ function group_action() {
// Create doc for each group order if doesn't exist // Create doc for each group order if doesn't exist
create_order_doc(selected_data[i]); create_order_doc(selected_data[i]);
// TODO (en dernier): ask before grouping if at least one of the orders is being updated somewhere else
} }
group_ids.sort(); group_ids.sort();
......
...@@ -844,11 +844,14 @@ function clearLineEdition() { ...@@ -844,11 +844,14 @@ function clearLineEdition() {
document.getElementById('product_uom').innerHTML = ''; document.getElementById('product_uom').innerHTML = '';
} }
/** /**
* Update a product info : qty or unit price * Update a product info : qty or unit price
* If 'value' is set, use it as new value * @param {Object} productToEdit
* @param {Float} value if set, use it as new value
* @param {Boolean} batch if true, don't update couchdb data here
* @returns
*/ */
function editProductInfo (productToEdit, value = null) { function editProductInfo (productToEdit, value = null, batch = false) {
try { try {
// Check if the product is already in the 'updated' list // Check if the product is already in the 'updated' list
var index = searchUpdatedProduct(); var index = searchUpdatedProduct();
...@@ -923,7 +926,7 @@ function editProductInfo (productToEdit, value = null) { ...@@ -923,7 +926,7 @@ function editProductInfo (productToEdit, value = null) {
orders[productToEdit.id_po]['updated_products'].push(productToEdit); orders[productToEdit.id_po]['updated_products'].push(productToEdit);
// May have been directly validated then updated from processed list // May have been directly validated then updated from processed list
// -> then: remove from 'valid_products' list // -> remove from 'valid_products' list
for (i in orders[productToEdit.id_po]['valid_products']) { for (i in orders[productToEdit.id_po]['valid_products']) {
if (orders[productToEdit.id_po]['valid_products'][i] == productToEdit['id']) { if (orders[productToEdit.id_po]['valid_products'][i] == productToEdit['id']) {
orders[productToEdit.id_po]['valid_products'].splice(i, 1); orders[productToEdit.id_po]['valid_products'].splice(i, 1);
...@@ -939,8 +942,10 @@ function editProductInfo (productToEdit, value = null) { ...@@ -939,8 +942,10 @@ function editProductInfo (productToEdit, value = null) {
} }
} }
if (batch === false) {
// Update product order // Update product order
update_distant_order(productToEdit.id_po); update_distant_order(productToEdit.id_po);
}
if(addition){ if(addition){
let row = table_processed.row($('#'+productToEdit.product_id[0])); let row = table_processed.row($('#'+productToEdit.product_id[0]));
...@@ -972,13 +977,16 @@ function setAllQties() { ...@@ -972,13 +977,16 @@ function setAllQties() {
table_to_process.rows().every(function () { table_to_process.rows().every(function () {
var data = this.data(); var data = this.data();
editProductInfo(data, 0); editProductInfo(data, 0, true);
return true; return true;
}); });
list_to_process = []; list_to_process = [];
table_to_process.rows().remove() table_to_process.rows().remove()
.draw(); .draw();
// Batch update orders
update_distant_orders()
} }
/* ACTIONS */ /* ACTIONS */
...@@ -1191,9 +1199,9 @@ function send() { ...@@ -1191,9 +1199,9 @@ function send() {
update_data.orders[prod_order_id]['po'].push(updatedProducts[i]); update_data.orders[prod_order_id]['po'].push(updatedProducts[i]);
} }
/* Prepare data for error report */ /* Create the error report */
// Send changes between items to process and processed items // Send changes between items to process and processed items
var updates = { var error_report_data = {
'group_amount_total' : 0, 'group_amount_total' : 0,
'update_type' : updateType, 'update_type' : updateType,
'updated_products' : updatedProducts, 'updated_products' : updatedProducts,
...@@ -1201,18 +1209,25 @@ function send() { ...@@ -1201,18 +1209,25 @@ function send() {
'orders' : [] 'orders' : []
}; };
for (i in orders) { for (let i in orders) {
updates.group_amount_total += orders[i].amount_total; error_report_data.group_amount_total += orders[i].amount_total;
updates.orders.push(orders[i]); error_report_data.orders.push(orders[i]);
} }
// TODO: (le vrai) step 1 : don't save report, just previous data // Send request for error report
// step 2 : prepare data by concatening both steps updated data. Envoyer ça au serveur. Coté back, just read ça. $.ajax({
// on peut supprimer les données dans couchdb au retour de update_orders sans problème parce qu'on a déjà anvoyé les données à save_error_report (préparées ici) type: "POST",
// -> Code beaucoup plus simple côté back dans save error report! et probablement ok ici url: "../save_error_report",
// + àa permettra de personaliser le back dans update_orders : dataType: "json",
// - si paramètre "reception_3_steps" activée, on fait rien tant que pas step 3 traditional: true,
// - on envoie toutes les updated_data concaténées après step 3 contentType: "application/json; charset=utf-8",
data: JSON.stringify(error_report_data),
success: function() {},
error: function() {
closeModal();
alert('Erreur dans l\'envoi du rapport.');
}
});
/* Update orders */ /* Update orders */
$.ajax({ $.ajax({
...@@ -1296,7 +1311,7 @@ function send() { ...@@ -1296,7 +1311,7 @@ function send() {
// Save current step updated data // Save current step updated data
orders[order_id].previous_steps_data = {} orders[order_id].previous_steps_data = {}
orders[order_id].previous_steps_data[reception_status] = { orders[order_id].previous_steps_data[reception_status] = {
updated_products: orders[order_id].updated_products updated_products: orders[order_id].updated_products || []
} }
orders[order_id].reception_status = updateType; orders[order_id].reception_status = updateType;
...@@ -1329,7 +1344,6 @@ function send() { ...@@ -1329,7 +1344,6 @@ function send() {
); );
/* Last step: Clear distant data */ /* Last step: Clear distant data */
// TODO test
// Delete orders doc // Delete orders doc
for (let order_id in orders) { for (let order_id in orders) {
orders[order_id]._deleted = true; orders[order_id]._deleted = true;
...@@ -1343,7 +1357,7 @@ function send() { ...@@ -1343,7 +1357,7 @@ function send() {
if (Object.keys(orders).length > 1) { if (Object.keys(orders).length > 1) {
let groups_doc = doc; let groups_doc = doc;
const first_order_id = Object.keys(orders)[0]; let first_order_id = parseInt(Object.keys(orders)[0]);
for (let i in groups_doc.groups) { for (let i in groups_doc.groups) {
if (groups_doc.groups[i].includes(first_order_id)) { if (groups_doc.groups[i].includes(first_order_id)) {
groups_doc.groups.splice(i, 1); groups_doc.groups.splice(i, 1);
...@@ -1364,8 +1378,6 @@ function send() { ...@@ -1364,8 +1378,6 @@ function send() {
// Back if modal closed // Back if modal closed
$('#modal_closebtn_top').on('click', back); $('#modal_closebtn_top').on('click', back);
$('#modal_closebtn_bottom').on('click', back); $('#modal_closebtn_bottom').on('click', back);
// TODO ? Dans modal : "merci de patienter avant de quitter la page..." -> "vous pouvez quitter la page !"
} catch (ee) { } catch (ee) {
err = {msg: ee.name + ' : ' + ee.message, ctx: 'callback update_orders'}; err = {msg: ee.name + ' : ' + ee.message, ctx: 'callback update_orders'};
console.error(err); console.error(err);
...@@ -1377,21 +1389,6 @@ function send() { ...@@ -1377,21 +1389,6 @@ function send() {
alert('Erreur lors de la sauvegarde des données.'); alert('Erreur lors de la sauvegarde des données.');
} }
}); });
/* Create error report */
$.ajax({
type: "POST",
url: "../save_error_report",
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(updates),
success: function() {},
error: function() {
closeModal();
alert('Erreur dans l\'envoi du rapport.');
}
});
} catch (e) { } catch (e) {
err = {msg: e.name + ' : ' + e.message, ctx: 'send'}; err = {msg: e.name + ' : ' + e.message, ctx: 'send'};
console.error(err); console.error(err);
...@@ -1419,13 +1416,16 @@ function confirm_all_left_is_good() { ...@@ -1419,13 +1416,16 @@ function confirm_all_left_is_good() {
} else { } else {
value = data.price_unit; value = data.price_unit;
} }
editProductInfo(data, value); editProductInfo(data, value, true);
return true; return true;
}); });
list_to_process = []; list_to_process = [];
table_to_process.rows().remove() table_to_process.rows().remove()
.draw(); .draw();
// Batch update orders
update_distant_orders()
closeModal(); closeModal();
} }
...@@ -1803,7 +1803,7 @@ $(document).ready(function() { ...@@ -1803,7 +1803,7 @@ $(document).ready(function() {
orders[order_id] = order; orders[order_id] = order;
//Add each order's already updated and validated products to common list // Add each order's already updated and validated products to common list
if (order["updated_products"]) { if (order["updated_products"]) {
updatedProducts = updatedProducts.concat(order["updated_products"]); updatedProducts = updatedProducts.concat(order["updated_products"]);
} }
......
...@@ -247,7 +247,7 @@ def update_orders(request): ...@@ -247,7 +247,7 @@ def update_orders(request):
# """ Method used for tests purposes: Reset an order status """ # """ Method used for tests purposes: Reset an order status """
# m = CagetteReception(id_po) # m = CagetteReception(id_po)
# m.update_order_status(id_po, False) # m.update_order_status(id_po, False)
#
# return JsonResponse({'id_po': id_po}) # return JsonResponse({'id_po': id_po})
def save_error_report(request): def save_error_report(request):
...@@ -472,8 +472,6 @@ def save_error_report(request): ...@@ -472,8 +472,6 @@ def save_error_report(request):
data_full.append(item) data_full.append(item)
# For an eventual step 3, save data_full
# Sort by error amount # Sort by error amount
def sortByError(e): def sortByError(e):
return abs(e['error_line']) return abs(e['error_line'])
......
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