Commit e3a79bad by Damien Moulard

fix couchdb batch updates

parent 3cf3ba79
Pipeline #1075 failed with stage
in 18 seconds
...@@ -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();
...@@ -515,7 +512,7 @@ $(document).ready(function() { ...@@ -515,7 +512,7 @@ $(document).ready(function() {
$.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } }); $.ajaxSetup({ headers: { "X-CSRFToken": getCookie('csrftoken') } });
fingerprint = new Fingerprint({canvas: true}).get(); fingerprint = new Fingerprint({canvas: true}).get();
// Init couchdb // Init couchdb
dbc = new PouchDB(couchdb_dbname), dbc = new PouchDB(couchdb_dbname),
sync = PouchDB.sync(couchdb_dbname, couchdb_server, { sync = PouchDB.sync(couchdb_dbname, couchdb_server, {
......
...@@ -846,11 +846,14 @@ function clearLineEdition() { ...@@ -846,11 +846,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();
...@@ -917,7 +920,7 @@ function editProductInfo (productToEdit, value = null) { ...@@ -917,7 +920,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);
...@@ -933,8 +936,10 @@ function editProductInfo (productToEdit, value = null) { ...@@ -933,8 +936,10 @@ function editProductInfo (productToEdit, value = null) {
} }
} }
// Update product order if (batch === false) {
update_distant_order(productToEdit.id_po); // Update product order
update_distant_order(productToEdit.id_po);
}
add_to_processed(productToEdit); add_to_processed(productToEdit);
} catch (e) { } catch (e) {
...@@ -961,13 +966,16 @@ function setAllQties() { ...@@ -961,13 +966,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 */
...@@ -1180,9 +1188,9 @@ function send() { ...@@ -1180,9 +1188,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,
...@@ -1190,18 +1198,25 @@ function send() { ...@@ -1190,18 +1198,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({
...@@ -1285,7 +1300,7 @@ function send() { ...@@ -1285,7 +1300,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;
...@@ -1318,7 +1333,6 @@ function send() { ...@@ -1318,7 +1333,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;
...@@ -1332,7 +1346,7 @@ function send() { ...@@ -1332,7 +1346,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);
...@@ -1353,8 +1367,6 @@ function send() { ...@@ -1353,8 +1367,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);
...@@ -1366,21 +1378,6 @@ function send() { ...@@ -1366,21 +1378,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);
...@@ -1408,13 +1405,16 @@ function confirm_all_left_is_good() { ...@@ -1408,13 +1405,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();
} }
...@@ -1792,7 +1792,7 @@ $(document).ready(function() { ...@@ -1792,7 +1792,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