Skip to content

Instantly share code, notes, and snippets.

@sbiaudet
Last active August 29, 2015 14:08
Show Gist options
  • Save sbiaudet/253e9f53b3ac76235d35 to your computer and use it in GitHub Desktop.
Save sbiaudet/253e9f53b3ac76235d35 to your computer and use it in GitHub Desktop.
var async = require('async')
, _ = require('lodash');
module.exports = [
require('cqrs-domain').defineCommand({
name: 'addInvoiceLine',
payload: 'payload'
}, function (data, aggregate) {
aggregate.apply('invoiceLineAdded', data); //1 - 1
calculateTotal(aggregate) //2 - 3
}),
require('cqrs-domain').defineCommand({
name: 'changeInvoiceLine',
payload: 'payload'
}, function (data, aggregate) {
aggregate.apply('invoiceLineChanged', data);
calculateTotal(aggregate)
}),
require('cqrs-domain').defineCommand({
name: 'removeInvoiceLine',
payload: 'payload'
}, function (data, aggregate) {
aggregate.apply('invoiceLineRemoved', data);
calculateTotal(aggregate)
})
];
function calculateTotal(aggregate) {//3 - 4
// Here for exemple with command AddInvoiceLine lines are empty.
var lines = aggregate.get('lines');
async.parallel({
totalHT: function (callback) {
var total = _.reduce(lines, function (sum, line) {
return sum + line['quantity'] * line['article_unitPrice'];
}, 0)
callback(null, total);
},
totalTTC: function (callback) {
var total = _.reduce(lines, function (sum, line) {
return sum + (line['quantity'] * line['article_unitPrice']) * (1 + line['article_TVA']);
}, 0);
callback(null, total);
},
recapTVA: function (callback) {
var total = _.reduce(lines, function (recap, line) {
if (line['article_TVA'] !== 0) {
recap[line['article_TVA']] = recap[line['article_TVA']] || 0;
recap[line['article_TVA']] += line['quantity'] * line['article_unitPrice'] * line['article_TVA'];
}
return recap;
}, {});
callback(null, total);
}
}, function(err, result){
aggregate.apply('invoiceTotalUpdated', result);
);
}
module.exports = require('cqrs-domain').defineEvent({
name: 'invoiceLineAdded',
payload: 'payload' // if not defined it will pass the whole event...
}, function (data, aggregate) {
var lines = aggregate.get('lines');//4 - 2
lines.push(data);
aggregate.set('lines', lines);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment