UNPKG

2.63 kBJavaScriptView Raw
1var fs = require('fs'),
2 ejs = require('ejs'),
3 formatters = require('./formatters'),
4 barcode = require('./barcode');
5
6var banks = null;
7
8var hashString = function(string) {
9 var hash = 0, i, chr, len;
10 if (string.length == 0) return hash;
11 for (i = 0, len = string.length; i < len; i++) {
12 chr = string.charCodeAt(i);
13 hash = ((hash << 5) - hash) + chr;
14 hash |= 0; // Convert to 32bit integer
15 }
16 return hash;
17};
18
19var Boleto = function(options) {
20 if(!options) {
21 throw "No options provided initializing Boleto.";
22 }
23
24 this.bank = banks[options['banco']];
25 if(!this.bank) {
26 throw "Invalid bank."
27 }
28
29 if(!options['data_emissao']) {
30 options['data_emissao'] = new Date();
31 }
32
33 if(!options['data_expiracao']) {
34 options['data_expiracao'] = new Date(new Date().getTime() + (5 * 24 * 3600 * 1000));
35 }
36
37 for(var key in options) {
38 this[key] = options[key]
39 }
40
41 this['pagador'] = formatters.htmlString(this['pagador']);
42 this['instrucoes'] = formatters.htmlString(this['instrucoes']);
43
44 if(!this['local_de_pagamento']) {
45 this['local_de_pagamento'] = 'Até o vencimento, preferencialmente no Banco ' + formatters.capitalize(this['banco'])
46 }
47
48 this._calculate();
49};
50
51Boleto.barcodeRenderEngine = 'img';
52
53Boleto.prototype._calculate = function() {
54 this['codigo_banco'] = this.bank.options.codigo + "-" + formatters.mod11(this.bank.options.codigo);
55 this['nosso_numero_dv'] = formatters.mod11(this['nosso_numero'].toString());
56 this['barcode_data'] = this.bank.barcodeData(this);
57 this['linha_digitavel'] = this.bank.linhaDigitavel(this['barcode_data']);
58}
59
60Boleto.prototype.renderHTML = function(callback) {
61 var self = this;
62
63 fs.readFile(__dirname + '/../assets/layout.ejs', function(err, content){
64 if(err) {
65 throw err;
66 }
67
68 var renderOptions = self.bank.options;
69 renderOptions.boleto = self;
70
71 // Copy renderHelper's methods to renderOptions
72 for(var key in formatters) {
73 renderOptions[key] = formatters[key];
74 }
75
76 renderOptions['barcode_render_engine'] = Boleto.barcodeRenderEngine;
77 renderOptions['barcode_height'] = '50';
78
79 if(Boleto.barcodeRenderEngine == 'bmp') {
80 renderOptions['barcode_data'] = barcode.bmpLineForBarcodeData(self['barcode_data']);
81 } else if(Boleto.barcodeRenderEngine == 'img') {
82 renderOptions['barcode_data'] = barcode.binaryRepresentationForBarcodeData(self['barcode_data']);
83 }
84
85 renderOptions['boleto']['linha_digitavel_hash'] = hashString(renderOptions['boleto']['linha_digitavel']).toString();
86
87 var html = ejs.render(content.toString(), renderOptions);
88
89 callback(html);
90 });
91}
92
93module.exports = function(_banks){
94 banks = _banks;
95 return Boleto;
96}