Last active
August 29, 2015 14:08
-
-
Save sbiaudet/253e9f53b3ac76235d35 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
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); | |
); | |
} | |
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
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