-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathinvoice.js
More file actions
221 lines (200 loc) · 6.87 KB
/
invoice.js
File metadata and controls
221 lines (200 loc) · 6.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/* jshint node: true */
'use strict';
var db = require('./db');
var config = require('./config');
var request = require('request');
var async = require('async');
function createAuctionInvoice(auctionId, user, expiration, discounts, webhook) {
var invoice = {};
invoice.currency = 'BTC';
invoice.expiration = expiration;
invoice.min_confirmations = Number(config.bitcoin.numberOfConfs);
invoice.line_items = [];
for (var i = 0; i < user.lineItems.length; i++) {
var lineItem = {};
lineItem.description = 'Auction ' + auctionId + ' Ad Slot for ' + user.lineItems[i].region;
lineItem.quantity = 1;
lineItem.amount = Number(user.lineItems[i].price);
invoice.line_items.push(lineItem);
}
invoice.discounts = discounts;
invoice.api_key = config.baron.key;
invoice.webhooks = {};
// leave webhook token out at this point, it'll be generated later
invoice.webhooks.paid = {};
invoice.webhooks.paid.url = webhook;
return invoice;
}
function createRegistrationInvoice(user, webhook) {
var invoice = {};
invoice.currency = 'BTC';
invoice.min_confirmations = Number(config.bitcoin.numberOfConfs);
invoice.line_items = [{
description: user.username + ' Auction Registration Fee',
quantity: 1,
amount: config.registrationFee,
}];
invoice.api_key = config.baron.key;
invoice.webhooks = {};
// leave webhook token out at this point, it'll be generated later
invoice.webhooks.paid = {};
invoice.webhooks.paid.url = webhook;
return invoice;
}
// metadata: any extra data that may be needed in the callback's function
// invoiceType: a string to indicate which type of invoice this is.
// This is needed to figure out which callback to use if the first
// call fails and needs to be queued. (Could be optimized.)
function createInvoice(metadata, invoiceType, invoice, cb) {
if (!invoiceType)
console.log('Invoice Created without a type. Callback is not guaranteed.');
var receipt = { metadata: metadata, invoiceType: invoiceType };
// create baron receipt with username and auctionId
generateReceipt(receipt, function(err, savedReceipt) {
if (err) { return cb(err, undefined); }
// add the receipt's id as the webhook token
if (invoice.webhooks) { invoice.webhooks.token = savedReceipt._id; }
postInvoice(invoice, savedReceipt, true, cb);
});
}
function generateReceipt(receipt, cb) {
// insert baron receipt into db
db.newReceipt(receipt, function(err, body) {
if (err) { return cb(err, undefined); }
// use baron receipt id as webhook token
receipt._id = body.id;
console.log('Created a BP Receipt with ID: ' + body.id);
cb(null, receipt);
});
}
function postInvoice(invoice, receipt, queue, cb) {
// send invoice to baron and get invoice id
request.post(
{
uri: config.baron.internalUrl + '/invoices',
method: 'POST',
form: invoice
},
function(err, response, body) {
parseBaronResponse(err, body, function(err, response) {
if (err) {
if (queue) {
console.log('Encountered an Error, Queuing Invoice...');
delete invoice.api_key;
var newInvoice = { invoice: invoice, receipt: receipt };
db.newQueuedInvoice(newInvoice, function(err) {
if (err) { console.log(err); }
});
}
return cb(err, undefined);
}
else {
saveInvoice(receipt, invoice, response, queue, cb);
}
});
}
);
}
function parseBaronResponse(postErr, body, cb) {
// Pass through request.post error
if (postErr) { return cb(postErr, null); }
// Check for invalid JSON or unexpected Baron response
var baronResponse;
var invalidBody = false;
var jsonParseError;
try { baronResponse = JSON.parse(body); }
catch (error) {
jsonParseError = error;
}
var errorMsg = 'Invalid response from Baron: ';
if (jsonParseError) {
errorMsg += body + jsonParseError.message;
}
else {
// Validate response from Baron
if (!baronResponse.ok || baronResponse.ok === false || !baronResponse.id || !baronResponse.rev) {
errorMsg += "missing ok: true, _id or _rev: " + body;
invalidBody = true;
}
}
// Pass back error or valid response
if (jsonParseError || invalidBody) {
var invoiceError = new Error(errorMsg);
cb(invoiceError, undefined);
}
else { cb(null, baronResponse); }
}
function saveInvoice(receipt, originalInvoice, invoice, queue, cb) {
console.log('Invoice ' + invoice.id + ' created for Receipt: ' + receipt._id);
// update receipt with new invoice
originalInvoice.id = invoice.id;
receipt.invoice = originalInvoice;
receipt.invoiceStatus = 'sent';
db.updateReceipt(receipt, function(err) {
if (err) { return cb(err, undefined); }
console.log('Updated Receipt ' + receipt._id + ' with Invoice ID ' + receipt.invoice.id);
var results = { receipt: receipt, invoice: invoice };
return cb(null, results);
});
}
function queuedInvoices(callback) {
async.waterfall([
// get all the queuedInvoices
function (cb) {
db.getAllQueuedInvoices(cb);
},
// iterate through and call each queuedInvoice
function (invoices, cb) {
async.eachSeries(invoices, function(queuedInvoice, innerCb) {
retryInvoice(queuedInvoice, innerCb);
},
function(err) { return cb(err); });
}
],
// final call to close this iteration of queuedInvoices
function (err) {
if (err) { console.log(err); }
return callback(null);
});
}
function retryInvoice(queuedInvoice, cb) {
// call each one
var invoice = queuedInvoice.invoice;
var receipt = queuedInvoice.receipt;
receipt.queuedInvoiceId = queuedInvoice._id;
invoice.api_key = config.baron.key;
postInvoice(invoice, receipt, false, function(err, results) {
if (err) { console.log('retryInvoice: ' + err); }
else {
var invoiceType = results.receipt.invoiceType;
var queuedInvoiceId = results.receipt.queuedInvoiceId;
delete results.receipt.queuedInvoiceId;
// create a modified callback
if (invoiceType === 'registration') {
registration.completeInvoice(null, results);
}
else if (invoiceType === 'auction') {
auctionClose.completeInvoice(null, results);
}
else if (invoiceType === 'auctionModified'){
auctionClose.completeModifiedInvoice(null, results);
}
else {
console.log('QueuedInvoice with unknown type found.');
}
// delete queuedInvoice
db.deleteQueuedInvoice(queuedInvoiceId, function(err) {
if (err) { console.log('deleteQueuedInvoice: ' + JSON.stringify(err)); }
});
}
return cb(null);
});
}
module.exports = {
createAuctionInvoice: createAuctionInvoice,
createRegistrationInvoice: createRegistrationInvoice,
createInvoice: createInvoice,
queuedInvoices: queuedInvoices
};
var registration = require('./registration');
var auctionClose = require('./events/auction-close');