scrive
Version:
ERROR: No README.md file found!
1,045 lines (917 loc) • 39.1 kB
JavaScript
var User = require('../../models/user');
var Courthouse = require('../../models/courthouse');
var Promotion = require('../../models/Promotion');
var config = require('../../config');
var geolib = require('geolib');
var ObjectID = require('mongodb').ObjectID;
var agent = require('../_header');
var request = require('request');
var stripeSecretKey = 'sk_live_hMX0DUVwVUFIPOA0EF4gNOMS';
var stripeTestKey = 'sk_test_BQokikJOvBiI2HlWgH4olfQ2'
var webStripeTestKey = 'sk_test_OTdESa0KxfWTOKATULG5jvsN';
var stripe = require('stripe')(stripeSecretKey);
var CoordinateTZ = require('coordinate-tz'),
zoneinfo = require('zoneinfo'),
TZDate = zoneinfo.TZDate;
// Your accountSid and authToken from twilio.com/user/account
var accountSid = 'ACe98fc8f39fc0326b17e6ad22d6063a8b';
var authToken = 'd8e3aebc8bc357a5ab3aa6aef7ae4c29';
var client = require('twilio')(accountSid, authToken);
StandinService = function() {};
Array.prototype.containsObjectId = function(v) {
for(var i = 0; i < this.length; i++) {
if(this[i].toString() ==v) return true;
}
return false;
};
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
StandinService.prototype.getCourthousesForCity = function(params, callback)
{
Courthouse.find({ city : params['city'] }, function (err, courthouses)
{
if (!err)
{
console.log('Found courthouses');
callback(null, courthouses);
}
else
{
console.log('Error finding courthouses : ' + err);
callback(err);
}
});
}
StandinService.prototype.getStandinsForCity = function(params, callback)
{
User.find({ createdProfile : true, $or : [{ userType : 'standin'}, { userType : 'both' }], currentCity : params['city'], emailAddress : { $ne : params['emailAddress'] }, stripeUserId : { $ne : '' } }, function (err, standins)
//User.find({ createdProfile : true, $or : [{ userType : 'standin'}, { userType : 'both' }], currentCity : params['city'], emailAddress : { $ne : params['emailAddress'] } }, function (err, standins)
{
if (!err)
{
console.log('Found standins');
callback(null, standins);
}
else
{
console.log('Error finding standins : ' + err);
callback(err);
}
});
}
StandinService.prototype.getReviewsForStandIn = function(params, callback)
{
}
StandinService.prototype.updateLocation = function(params, callback)
{
console.log('userId: ' + params['userId']);
var timezoneAtLocation = CoordinateTZ.calculate(params['lat'],params['lon']);
var dateAtLocation = new TZDate();
dateAtLocation.setTimezone(timezoneAtLocation.timezone);
var hour = dateAtLocation.format('H');
//if local time is between 8AM and 5PM, update location
if (hour >= 8 && hour < 17)
{
console.log('Within business hours');
User.find({ _id : new ObjectID(params['userId']) }, {}, { limit : 1 }, function(err, users)
{
if (!err)
{
if (users && users.length > 0 && (users[0].workAddress.lat === 0 && users[0].workAddress.lon === 0))
{
console.log('Coordinates updated');
console.log('Email: ' + params['emailAddress']);
console.log('Lat: ' + params['lat']);
console.log('Lon: ' + params['lon']);
users[0].location.lat = parseFloat(params['lat']);
users[0].location.lon = parseFloat(params['lon']);
users[0].currentCity = params['city'];
users[0].save(function(err, user)
{
if (!err)
callback();
else
callback(err);
});
}
else
{
console.log('Error finding user : ' + err);
callback('No users found');
}
}
else
{
console.log('Error finding user : ' + err);
callback(err);
}
});
}
else
{
console.log('outside business hours');
callback();
}
}
StandinService.prototype.updateDeviceToken = function(params, callback)
{
console.log('userId: ' + params['userId']);
User.find({ _id : new ObjectID(params['userId']) }, {}, { limit : 1 }, function(err, users)
{
if (!err)
{
if (users && users.length > 0)
{
console.log('Device Token updated');
if (params['deviceToken'] && params['deviceToken'] !== undefined && params['deviceToken'] !== null && params['deviceToken'] !== '')
users[0].deviceToken = params['deviceToken'];
users[0].save(function(err, user)
{
if (!err)
callback();
else
callback(err);
});
}
else
{
console.log('Error finding user : ' + err);
callback('No users found');
}
}
else
{
console.log('Error finding user : ' + err);
callback(err);
}
});
}
StandinService.prototype.updateStripeToken = function(params, callback)
{
console.log('userId: ' + params['userId']);
console.log('token: ' + params['stripeToken']);
User.findOne({ _id : params['userId'] }, function(err, user)
{
if (!err)
{
if (user)
{
console.log('Stripe Token updated');
request.post('https://connect.stripe.com/oauth/token',
{ json : { client_secret : stripeSecretKey, grant_type : 'authorization_code', code : params['stripeToken'], scope : 'read_write' } },
function (error, response, body)
{
if (!error && response.statusCode == 200)
{
console.log(body);
user.stripeToken = body.access_token;
user.stripeUserId = body.stripe_user_id;
user.stripePublishableKey = body.stripe_publishable_key;
user.save(function(err, user)
{
if (!err)
callback(null, user.stripeToken);
else
callback(err, null);
});
}
else
{
console.log('error getting access token: ' + error, body);
callback('error');
}
}
);
}
else
{
console.log('Error finding user : ' + err);
callback('No users found');
}
}
else
{
console.log('Error finding user : ' + err);
callback(err);
}
});
}
StandinService.prototype.updateStripeCreditCardToken = function(params, callback)
{
User.findOne({ _id : params['userId'] }, function(err, user)
{
if (!err)
{
if (user)
{
console.log('Stripe Credit Card Token updated');
//new customer
if (!user.stripeCustomerId || user.stripeCustomerId === null || user.stripeCustomerId === undefined || user.stripeCustomerId === '')
{
console.log('create new customer');
stripe.customers.create(
{
source: params['stripeCreditCardToken'],
description: params['userId']
}, function(err, customer)
{
if (err)
{
console.log('failed to update credit card ' + err);
callback('failed to update credit card', null);
}
else
{
console.log('Customer: ' + customer.id);
user.stripeCustomerId = customer.id;
user.stripeCardToken = params['stripeCreditCardToken'];
user.save(function(err, updatedUser)
{
if (!err)
callback(null, updatedUser);
else
callback('err', null);
});
}
});
}
//existing customer, update credit card token
else
{
console.log('update existing customer');
stripe.customers.update(user.stripeCustomerId,
{
source: params['stripeCreditCardToken']
}, function(err, customer)
{
if (err)
{
console.log('failed to update credit card');
callback('failed to update credit card', null);
}
else
{
user.stripeCustomerId = customer.id;
user.stripeCardToken = params['stripeCreditCardToken'];
user.save(function(err, updatedUser)
{
if (!err)
callback(null, updatedUser);
else
callback('err', null);
});
}
});
}
}
else
{
console.log('Error finding user : ' + err);
callback('No users found');
}
}
else
{
console.log('Error finding user : ' + err);
callback('err');
}
});
}
StandinService.prototype.updateStripeBankAccountToken = function(params, callback)
{
User.findOne({ _id : params['userId'] }, function(err, user)
{
if (!err)
{
if (!user || !user.stripeUserId || user.stripeUserId === null || user.stripeUserId === undefined || user.stripeUserId === '')
{
console.log('Error finding user : ' + err);
callback('No user found');
}
else
{
console.log('updating bank account token');
//accept TOS if user hasn't added a bank account before
if (!user.verifiedBankAccount)
{
stripe.accounts.update(user.stripeUserId,
{
tos_acceptance:
{
date: Math.floor(Date.now() / 1000),
ip: params['ipAddress']
}
}, function(err, account)
{
if (err)
{
console.log('faliled to accept TOS '+ err)
callback('failed to update Account', null)
}
else {
console.log('TOS accepted successfully');
stripe.accounts.createExternalAccount(user.stripeUserId,
{
external_account : params['stripeBankAccountToken'],
default_for_currency : true
}, function(err, bankAccount)
{
if (err)
{
console.log('failed to update bank account ' + err);
callback('failed to update bank account: ' + err, null);
}
else
{
console.log('Stripe Bank Account Token updated');
user.verifiedBankAccount = true;
user.createdStripeAccount = true;
user.save(function(err, updatedUser)
{
if (err)
callback(err, null);
else
callback(null, updatedUser);
});
}
});
}
})
}
//otherwise just add the new bank account
else
{
stripe.accounts.createExternalAccount(user.stripeUserId,
{
external_account : params['stripeBankAccountToken'],
default_for_currency : true
}, function(err, bankAccount)
{
if (err)
{
console.log('failed to update bank account: ' + err);
callback('failed to update bank account: '+ err, null);
}
else
{
console.log('Stripe Bank Account Token updated');
user.verifiedBankAccount = true;
user.createdStripeAccount = true;
user.save(function(err, updatedUser)
{
if (err)
callback(err, null);
else
callback(null, updatedUser);
});
}
});
}
}
}
else
{
console.log('Error finding user : ' + err);
callback('error');
}
});
};
//verify user identity for stripe account
StandinService.prototype.verifyUserIdentity = function(params, callback)
{
var details = { legal_entity: { dob: {} } };
var supportedCountry, stripeCountry, stripeCurrency;
if (params['country'] === 'CA')
{
supportedCountry = true;
stripeCountry = params['country'];
stripeCurrency = 'cad';
details.legal_entity.type = params['accountType'];
details.legal_entity.first_name = params['firstName'];
details.legal_entity.last_name = params['lastName'];
details.legal_entity.personal_id_number = params['idNumber'];
details.legal_entity.dob.month = params['birthMonth'];
details.legal_entity.dob.day = params['birthDay'];
details.legal_entity.dob.year = params['birthYear'];
if (params['accountType'] === 'corporation')
{
details.legal_entity.business_name = params['businessName'];
details.legal_entity.business_tax_id = params['businessNumber'];
}
}
else if (params['country'] === 'US')
{
supportedCountry = true;
stripeCountry = params['country'];
stripeCurrency = 'usd';
console.log('country', stripeCountry);
details.legal_entity.type = params['accountType'];
details.legal_entity.first_name = params['firstName'];
details.legal_entity.last_name = params['lastName'];
details.legal_entity.ssn_last_4 = params['idNumber'];
details.legal_entity.dob.month = params['birthMonth'];
details.legal_entity.dob.day = params['birthDay'];
details.legal_entity.dob.year = params['birthYear'];
if (params['accountType'] === 'corporation')
{
details.legal_entity.business_name = params['businessName'];
details.legal_entity.business_tax_id = params['businessNumber'];
}
}
else
{
callback('country not supported', null);
}
User.findOne({ _id : params['userId'] }, function(err, user)
{
if (!err)
{
if (user)
{
console.log('user found: ' + user);
//ceate new user stripe account if not existing
if (!user.stripeUserId || user.stripeUserId === null || user.stripeUserId === undefined || user.stripeUserId === '')
{
console.log('create new account');
if (supportedCountry)
{
stripe.accounts.create(
{
email: user.emailAddress,
country: stripeCountry,
debit_negative_balances: true,
managed: true
}, function(reason, account)
{
if (reason)
{
console.log('failed to create Stripe account. Reason: ' + reason);
callback('Failed to create Stripe account', null);
}
else
{
console.log('created Stripe account');
//save user stripe account details
user.stripeUserId = account.id;
stripeToken = account.keys.secret;
stripePublishableKey = account.keys.publishable;
user.save(function(err, savedUser){
if (err)
{
console.log('error saving user: ' + err);
callback('Failed to save Stripe account', null);
}
else
{
console.log('saved user');
//update user stripe account details with verified data
stripe.accounts.update(user.stripeUserId, details,
function(reason, account){
if (reason)
{
console.log('failed to update account. Reason: ' + reason);
callback('Failed to update account', null);
}
else
{
console.log('updated account');
//update user identity verification status
user.verifiedIdentity = true;
user.save(function(err, savedUser){
if (err)
{
console.log('failed to save user. INVESTIGATE');
callback('failed to save user', null);
}
else
{
console.log('saved user');
callback(null, savedUser);
}
});
}
});
}
});
}
});
}
}
//existing account, update identity info
else
{
if (supportedCountry)
{
//update user stripe account data
stripe.accounts.update(user.stripeUserId, details, function(reason, account)
{
if (reason)
{
console.log('failed to update account. Reason: ' + reason);
callback('Failed to update account', null);
}
else
{
console.log('updated account');
//update user identity verification status
user.verifiedIdentity = true;
user.save(function(err, savedUser){
if (err)
{
console.log('failed to save user. INVESTIGATE');
callback(null, user);
}
else
{
console.log('saved user');
callback(null, savedUser);
}
});
}
});
}
}
}
else
{
console.log('Error finding user : ' + err);
callback('No user found', null);
}
}
else
{
console.log('Error finding user : ' + err);
callback('err', null);
}
});
};
StandinService.prototype.verifyUserAddress = function(params, callback)
{
User.findOne({ _id : params['userId'] }, function(err, user)
{
if (err)
{
console.log('failed to find user');
callback(err, null);
}
else
{
if (!user || !user.stripeUserId || user.stripeUserId === null || user.stripeUserId === undefined || user.stripeUserId === '')
callback('No user found', null);
else
{
console.log('update existing account');
var details = { legal_entity: { address: { } } };
details.legal_entity.address.line1 = params['addressLine1'];
details.legal_entity.address.line2 = params['addressLine2'];
details.legal_entity.address.city = params['city'];
details.legal_entity.address.state = params['state'];
details.legal_entity.address.postal_code = params['postalCode'];
details.legal_entity.address.country = params['country'];
stripe.accounts.update(user.stripeUserId, details, function(err, account)
{
if (err)
{
console.log('Failed to update account: ' + err)
callback('Failed to update account: ' + err, null)
}
else
{
console.log('updated account');
user.verifiedAddress = true;
user.save(function(err, savedUser)
{
if (err)
{
console.log('failed to save user: ' + err);
callback(null, user);
}
else
{
console.log('saved user');
callback(null, savedUser);
}
});
}
})
}
}
});
};
StandinService.prototype.verifyLinkedIn = function(params, callback)
{
console.log('userId: ' + params['userId']);
User.find({ _id : new ObjectID(params['userId']) }, {}, { limit : 1 }, function(err, users)
{
if (!err)
{
if (users && users.length > 0)
{
if (params['linkedInId'] && params['linkedInId'] !== undefined && params['linkedInId'] !== null && params['linkedInId'] !== '')
{
users[0].verifiedWithLinkedIn = true;
users[0].linkedinId = params['linkedInId'];
}
users[0].save(function(err, user)
{
if (err)
callback(err, null);
else
{
console.log('LinkedIn Verified');
callback(null, user);
}
});
}
else
{
console.log('Error finding user : ' + err);
callback('No users found');
}
}
else
{
console.log('Error finding user : ' + err);
callback(err);
}
});
}
StandinService.prototype.verifyClio = function(params, callback)
{
console.log('userId: ' + params['userId']);
User.find({ _id : new ObjectID(params['userId']) }, {}, { limit : 1 }, function(err, users)
{
if (!err)
{
if (users && users.length > 0)
{
var user = users[0];
if (params['clioUserId'] && params['clioUserId'] !== undefined && params['clioUserId'] !== null && params['clioUserId'] !== '')
{
user.clioUserId = params['clioUserId'];
user.clioAccessToken = params['clioAccessToken'];
user.verifiedWithClio = true;
}
user.save(function(err, user)
{
if (err)
callback(err, null);
else
{
console.log('Clio Verified');
callback(null, user);
}
});
}
else
{
console.log('Error finding user : ' + err);
callback('No users found');
}
}
else
{
console.log('Error finding user : ' + err);
callback(err);
}
});
}
StandinService.prototype.sendInvites = function(params, callback)
{
console.log('userId: ' + params['userId']);
console.log('contacts: ' + params['contacts']);
var userId = params['userId'];
var contacts = params['contacts'];
User.findById(userId, function(err, user){
if (err)
{
console.log('error getting user: ' + err);
callback(err);
}
else
{
for (var c in contacts)
{
if (typeof contacts[c] === 'string')
{
var body = "Invitation from " + user.firstName + " " + user.lastName + "\nCourts aren't always working at the optimal level of efficiency, but with StandIn, you certainly can. Use the StandIn app to find trusted legal professionals, right where and when you need them, and they will fill in for you at court appearances. Each of us will get $10 in credits when you sign up with my unique code " + user.promoCode + " \n\nDownload here: https://itunes.apple.com/app/standin/id972138344?mt=8";
client.messages.create({
body: body,
to: contacts[c],
from: "+12898063579"
}, function(err, message) {
console.log('Err: ' + JSON.stringify(err));
console.log('Message: ' + message);
});
}
}
callback(null);
}
});
}
StandinService.prototype.favoriteUser = function(params, callback) {
console.log('userId: ' + params['userId']);
console.log('userIdToFavorite: ' + params['userIdToFavorite']);
var userId = params['userId'];
var userIdToFavorite = params['userIdToFavorite'];
User.findById(userId, function(err, user) {
if (err) {
console.log('error getting user: ' + err);
callback(err, null);
} else {
if (!user.favoriteUsers) {
user.favoriteUsers = [];
}
if (user.favoriteUsers.indexOf(userIdToFavorite) === -1) {
user.favoriteUsers.push(userIdToFavorite);
} else {
user.favoriteUsers.splice(user.favoriteUsers.indexOf(userIdToFavorite), 1);
}
user.save(function(err, savedUser) {
if (err) {
console.log('error saving user: ' + err);
callback(err, null);
} else {
console.log('saved user');
callback(null, user);
}
});
}
});
}
StandinService.prototype.redeemPromoCode = function(userId, promoCode, callback)
{
console.log('redeemPromoCode - code: ' + promoCode);
promoCode = promoCode.toLowerCase();
Promotion.findOne({ code : promoCode, active: true }, function(err, promotion){
if (err)
{
console.log('error finding promotion');
callback(err, null);
}
else
{
//regular promo code
if (promotion && promotion.code !== 'Referral')
{
User.findOne({ _id : userId }, function(err, user){
if (err)
{
console.log('error finding user: ' + err);
callback(err, null);
}
else
{
if (!user || user === '')
{
console.log('Could not find user ID');
callback("UserDoesNotExist", null);
}
else
{
console.log('Updating User...');
if (user.promotionsRedeemed.containsObjectId(promotion._id) ||
user.availablePromotions.containsObjectId(promotion._id))
{
console.log('promotion already redeemed');
callback('PromoAlreadyRedeemed', null);
}
else
{
user.availablePromotions.push(promotion._id);
//Save user
user.save(function(err, updatedUser)
{
if (err)
{
console.log('failed to save user: ' + err);
callback('Failed to redeem promo code', null);
} else
{
console.log('user saved');
callback(null, promotion.value / 100.0);
}
});
}
}
}
});
}
//referral promo code
else
{
User.findOne({ promoCode : promoCode }, function(err, referringUser){
if (err)
{
console.log('error finding user: ' + err);
callback(err, null);
}
else
{
if (referringUser)
{
User.findOne({ _id : userId }, function(err, user){
if (err)
{
console.log('error finding user: ' + err);
callback(err, null);
}
else
{
if (user)
{
//if the user has redeemed a unique promo code or made a payment before, dont redeem another
if (user.usedReferralCode)
{
console.log('promotion already redeemed');
callback('PromoAlreadyRedeemed', null);
}
else
{
Promotion.findOne({ code : 'Referral', active: true }, function(err, promotion){
if (err)
{
console.log('error finding promotion');
callback(err, null);
}
else
{
if (promotion)
{
user.availablePromotions.push(promotion._id);
user.usedReferralCode = true;
user.referringUserId = referringUser._id;
//Save user
user.save(function(err, updatedUser)
{
if (err)
{
console.log('failed to save user: ' + err);
callback('Failed to redeem promo code', null);
} else
{
console.log('user saved');
callback(null, promotion.value / 100.0);
}
});
}
else
{
console.log('no promotion found');
callback('InvalidPromoCode', null);
}
}
});
}
}
else
{
console.log('No user found');
callback('No User Found', null);
}
}
});
}
else
{
console.log('no promotion found');
callback('InvalidPromoCode', null);
}
}
});
}
}
})
}
function sendPushNotificationToUser(userId, message)
{
User.find({ _id : userId }, {}, { limit : 1 }, function(err, users)
{
if (!err)
{
if (users && users.length > 0)
{
console.log('Device Token updated');
agent.createMessage()
.device(users[0].deviceToken)
.alert('Hello World!')
.send();
}
else
{
console.log('Error finding user : ' + err);
callback('No users found');
}
}
else
{
console.log('Error finding user : ' + err);
callback(err);
}
});
}
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
exports.StandinService = StandinService;