-
Notifications
You must be signed in to change notification settings - Fork 1
/
kivasearchdb.js
409 lines (364 loc) · 11.3 KB
/
kivasearchdb.js
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
var partnerscraper = require('./scrape_partnerdata_job.js');
var http = require('http');
if(process.env.VCAP_SERVICES){
var env = JSON.parse(process.env.VCAP_SERVICES);
var mongo = env['mongodb-1.8'][0]['credentials'];
}
else{
var mongo = {
"hostname":"localhost",
"port":27017,
"username":"",
"password":"",
"name":"",
"db":"kivasearchdb"
}
}
var generate_mongo_url = function(obj){
obj.hostname = (obj.hostname || 'localhost');
obj.port = (obj.port || 27017);
obj.db = (obj.db || 'test');
if(obj.username && obj.password){
return "mongodb://" + obj.username + ":" + obj.password + "@" + obj.hostname + ":" + obj.port + "/" + obj.db;
}
else{
return "mongodb://" + obj.hostname + ":" + obj.port + "/" + obj.db;
}
}
var databaseUrl = generate_mongo_url(mongo);
var collections = ["loans", "search_criteria", "partners","chkoutloans"];
var db = require("mongojs").connect(databaseUrl, collections);
var app_id = "cm.af.aws.kivasearch";
var countries = require("./slim-2.js");
exports.database = db;
var allPartners = {};
var A_MINUTE = 60 * 1000;
var AN_HOUR = A_MINUTE * 60;
var A_DAY = 24 * AN_HOUR;
var A_WEEK = A_DAY * 7;
var A_MONTH = A_DAY * 30;
exports.prefetchallPartners =
function(){
db.partners.find(function(err,partners){
console.log("Prefetching all partners");
for (id in partners){
var partner = partners[id];
partner.rating = parseFloat(partner.rating);
allPartners[partner.id] = partner;
}
});
};
//For loans not updated for more than five minutes
//check the status at Kiva and delete if funded.
exports.cleanupStaleLoans = function(){
console.log("Running DB Cleanup job now");
query = {last_updated:{$lt:(Date.now() - (2 * A_MINUTE))}};
console.log(JSON.stringify(query));
db.loans.remove(query);
db.loans.count({},function(result){
console.log("Loan Count:" + JSON.stringify(result));
})
};
function saveLoanToDb(loan){
if (allPartners[loan.partner_id] == null){
console.log("Skipping loan update for id:" + loan.id + ", Missing partner data");
return;
}
loan['borrower_count'] = loan.borrowers.length;
loan['amount_needed'] = (loan.loan_amount - (loan.funded_amount + loan.basket_amount));
loan['partner'] = allPartners[loan.partner_id];
loan['last_updated'] = Date.now();
loan['amount_needed_per_borrower'] = parseInt(
parseInt(loan.loan_amount) /
parseInt(loan['borrower_count']));
loan['percentage_funded'] = parseInt(((loan.funded_amount + loan.basket_amount) / loan.loan_amount)*100);
loan['country_name'] = countries.countries_map[loan.location.country_code.toUpperCase()];
loan.location.country_code = loan.location.country_code.toLowerCase();
loan['loan_description_excerpt'] = "...";
var payments = loan.terms.scheduled_payments;
var last_payment_date = payments[payments.length-1].due_date;
var months = Math.round((new Date(last_payment_date) - Date.now()) / A_MONTH);
loan['repayment_term'] = months;
loan['expiration_days'] = Math.round((new Date(loan.planned_expiration_date) - Date.now()) / A_DAY);
if (isNaN(loan.partner.rating)){
console.log("Partner :" + loan.partner.name + " is with status :" + loan.partner.status + ",Marking Rating as 0");
loan.partner.rating = 0;
}
else{
loan.partner.rating = parseFloat(loan.partner.rating);
}
db.loans.findOne({id:loan.id},{id:1},function(err,doc){
if(doc != null){
db.loans.remove({id:doc.id});
}
db.loans.save(loan);
});
}
exports.scrapeCallback =
function (additionalPartnerInfo){
if (!additionalPartnerInfo){
console.log("Error while fetching additional partner info");
}
else{
db.partners.update({id:additionalPartnerInfo.partner_id},{
$set:{"additional_info" : additionalPartnerInfo}
});
}
console.log("Additional data added for partner :" + additionalPartnerInfo.partner_id);
}
function savePartnerToDb(partner){
db.partners.findOne({id:partner.id},{id:1,additional_info:1},function(err,doc){
if(doc == null){
console.log("Saving new Partner, ID:" + partner.id);
db.partners.save(partner);
partnerscraper.scrapePartnerInfo(partner.id, function(data){
scrapeCallback(data);
});
}
else if (doc.additional_info == null){
partnerscraper.scrapePartnerInfo(doc.id,function(data){
scrapeCallback(data);
});
}
});
};
exports.refreshPartnerData =
function (){
console.log("Starting partner data refresh");
var options = {
hostname: 'api.kivaws.org',
port: 80,
path: '/v1/partners.json&app_id=' + app_id,
method: 'GET'
};
var data = '';
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
data+=chunk;
});
res.on('end',function(){
var partners = JSON.parse(data).partners;
for (id in partners){
var partner = partners[id];
savePartnerToDb(partner);
}
console.log("Partner data saved to database");
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();
};
function refreshLoanListByPage(page){
var options = {
hostname: 'api.kivaws.org',
port: 80,
path: '/v1/loans/newest.json&page='+page + '&app_id=' + app_id,
method: 'GET'
};
var data = '';
var i = 0;
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
data+=chunk;
});
res.on('end',function(){
var loans = JSON.parse(data).loans;
var ids=[];
var i = 0;
//console.log("There are " + loans.length + " Loans in this page");
for (aLoan in loans){
ids[i] = loans[aLoan].id;
if (allPartners[loans[aLoan].partner_id] == null){
console.log("Skipping loan update for id:" + loans[aLoan].id + ", Missing partner data");
break;
}
i = i + 1;
if (i >= 10){
//console.log("Getting Loan Details Now");
getLoanDetails(ids.toString());
i = 0;
ids=[];
}
}
getLoanDetails(ids);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();
}
function getLoanDetails(ids){
//console.log("IDs:" + ids);
var options = {
hostname: 'api.kivaws.org',
port: 80,
path: '/v1/loans/'+ ids +'.json'+ '&app_id=' + app_id,
method: 'GET'
};
var data = '';
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
data+=chunk;
});
res.on('end',function(){
var loans = JSON.parse(data).loans;
for (aLoan in loans){
var loan = loans[aLoan];
saveLoanToDb(loan);
}
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();
}
exports.refreshLoanList =
function (){
var options = {
hostname: 'api.kivaws.org',
port: 80,
path: '/v1/loans/newest.json&app_id=' + app_id,
method: 'GET'
};
var data = '';
var i = 0;
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
data+=chunk;
});
res.on('end',function(){
var paging = JSON.parse(data).paging;
var noOfPages = paging.pages;
for (i = 1 ; i < noOfPages+1; i++){
refreshLoanListByPage(i);
}
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();
};
//({borrower_count:{$lt:2}})
/*
{ borrower:
{ borrowerCount: { min: 0, max: 2 },
amount_needed: { min: 0, max: 700 },
repayment_term: { min: 0, max: 5 },
expiration_days: { min: 0, max: 30 },
currency_loss_protection: false },
partner:
{ partner_rating: { min: '3', max: 5 },
partner_delinquency_rate: { min: 0, max: 5 },
partner_default_rate: { min: 0, max: 4 },
partner_portfolio_yield: { min: 0, max: 25 },
partner_profit_percentage: { min: 0, max: 25 },
exclude_pilot: false } }
*/
exports.findMatchingLoans = function(criterion,callback){
var borrower = criterion.borrower;
var partner = criterion.partner;
var query = {
"status":"fundraising",
"borrower_count":{$gte:parseInt(borrower.borrowerCount.min),$lte:parseInt(borrower.borrowerCount.max)},
"amount_needed":{$gte:parseInt(borrower.amount_needed.max),$gte:parseInt(borrower.amount_needed.min)},
"repayment_term":{$gte:parseInt(borrower.repayment_term.min),$lte:parseInt(borrower.repayment_term.max)},
"expiration_days":{$gte:parseInt(borrower.expiration_days.min),$lte:parseInt(borrower.expiration_days.max)},
"partner.rating":{$gte:partner.partner_rating.min,$lte:partner.partner_rating.max},
"partner.delinquency_rate":{$gte:parseFloat(partner.partner_delinquency_rate.min),$lte:parseFloat(partner.partner_delinquency_rate.max)},
"partner.default_rate":{$gte:parseFloat(partner.partner_default_rate.min),$lte:parseFloat(partner.partner_default_rate.max)},
"partner.additional_info.portfolio_yield":{$gte:parseFloat(partner.partner_portfolio_yield.min),$lte:parseFloat(partner.partner_portfolio_yield.max)},
"partner.additional_info.profitability":{$gte:parseFloat(partner.partner_profit_percentage.min),$lte:parseFloat(partner.partner_profit_percentage.max)}
};
if (partner.exclude_pilot){
query["partner.status"] = {$ne:"pilot"};
}
if (borrower.currency_loss_protection){
query["borrower.terms.loss_liability.currency_exchange"] = "partner";
}
var resultTemplate =
{
"id":1,
"name":1,
"borrower_count":1,
"location.country_code":1,
"country_name":1,
"sector":1,
"use":1,
"description":1,
"loan_amount":1,
"funded_amount":1,
"amount_needed_per_borrower":1,
"percentage_funded":1,
"activity":1,
"image":1,
"partner.image":1,
"partner.name":1
};
console.log(JSON.stringify(query));
db.loans.find(query, resultTemplate).sort({"percentage_funded":-1},callback);
};
exports.saveCheckOutActivity = function(loans){
for(key in loans){
db.chkoutloans.save(loans[key]);
}
}
var indexFields =
{
"id":1,"partner_id":1,
"status":1,"borrower_count":1,"amount_needed":1,"repayment_term":1,"expiration_days":1,
"partner.rating":1,"partner.delinquency_rate":1,"partner.default_rate":1,
"partner.additional_info.portfolio_yield":1,"partner.additional_info.profitability":1};
exports.createIndexes = function(){
db.loans.indexInformation(function(err,current_indexes){
for(aKey in current_indexes){
//skipping already created indexes.
var field = current_indexes[aKey][0][0];
delete(indexFields[field]);
}
});
for(key in indexFields){
//Creating index for each field specified
createIndex(key);
}
db.loans.indexInformation(function(err,data){
console.log("DB has the following indexes");
console.log(data);
});
}
function createIndex(field){
db.loans.ensureIndex([[field,1]],function(err,data){
if(err){console.log(err);}
else{
//console.log(data);
}
});
}
exports.countLoans = function(callback){
db.loans.find({},{id:1},function(err,data){
if(err){
callback(err,{count:0});
}
else{
callback(err,{count:data.length});
}
});
}
exports.countChkoutLoans = function(callback){
db.chkoutloans.find({},{id:1},function(err,data){
if(err){
callback(err,{count:0});
}
else{
callback(err,{count:data.length});
}
});
}