Created
June 19, 2017 09:18
-
-
Save Rexagon/c04fa0966776e376f5f80587f022a2ef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sql.query('TRUNCATE TABLE shipments').then(function(rows) { | |
sql.query('SELECT cc.* FROM containers_content cc INNER JOIN containers cn ON cc.container=cn.id ORDER BY date_departure ASC').then(function(rows) { | |
var containers_content = rows; | |
var requests = []; | |
var j = 0; | |
for (var i = 0; i < containers_content.length; i++) { | |
requests.push(function(callback) { | |
var container_content = containers_content[j++]; | |
sql.query('SELECT oc.*, COALESCE(SUM(sh.quantity), 0) AS quantity_shipped FROM orders_content oc LEFT JOIN shipments sh ON sh.order_number=oc.order_number AND sh.nomenclature=oc.nomenclature INNER JOIN orders od ON od.number=oc.order_number WHERE oc.nomenclature=? GROUP BY oc.order_number, oc.nomenclature HAVING oc.quantity > COALESCE(SUM(sh.quantity), 0) ORDER BY od.date ASC', container_content.nomenclature).then(function(rows) { | |
var orders_content = rows; | |
var subrequests = []; | |
var shipments = []; | |
var l = 0; | |
for (var k = 0; k < orders_content.length && container_content.quantity > 0; k++) { | |
var order_content = orders_content[k]; | |
var needed_quantity = order_content.quantity - order_content.quantity_shipped; | |
if ((needed_quantity > container_content.quantity) || (k + 1 == orders_content.length)) { | |
needed_quantity = container_content.quantity; | |
} | |
container_content.quantity -= needed_quantity; | |
shipments.push({ | |
order_number: order_content.order_number, | |
nomenclature: order_content.nomenclature, | |
container: container_content.container, | |
container_content_nomenclature: container_content.nomenclature, | |
quantity: needed_quantity | |
}); | |
subrequests.push(function(subcallback) { | |
var shipment = shipments[l++]; | |
sql.query('INSERT INTO shipments SET ? ON DUPLICATE KEY UPDATE quantity=?', [shipment, shipment.quantity]).then(function(rows) { | |
subcallback(); | |
}).catch(function(err) { | |
console.log(err); | |
subcallback(err); | |
}); | |
}); | |
} | |
async.parallel(subrequests, function(err, results) { | |
if (err) { | |
callback(err); | |
} else { | |
callback(); | |
} | |
}); | |
}).catch(function(err) { | |
console.log(err); | |
callback(err); | |
}); | |
}); | |
} | |
async.series(requests, function(err, results) { | |
if (err) { | |
res.send({ err: 1 }); | |
} else { | |
res.send({}); | |
} | |
}); | |
}).catch(function(err) { | |
console.log(err); | |
res.send({ err: 1 }); | |
}); | |
}).catch(function(err) { | |
console.log(err); | |
res.send({ err: 1 }); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment