-
Notifications
You must be signed in to change notification settings - Fork 56
[DEV] New API endpoint to get Billing Accounts from SFDC #621
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
// import _ from 'lodash'; | ||
import validate from 'express-validation'; | ||
import Joi from 'joi'; | ||
import { middleware as tcMiddleware } from 'tc-core-library-js'; | ||
import SalesforceService from '../../services/salesforceService'; | ||
|
||
/** | ||
* API to get project attachments. | ||
* | ||
*/ | ||
|
||
const permissions = tcMiddleware.permissions; | ||
|
||
const schema = { | ||
params: { | ||
projectId: Joi.number().integer().positive().required(), | ||
}, | ||
}; | ||
|
||
module.exports = [ | ||
validate(schema), | ||
permissions('projectBillingAccounts.view'), | ||
async (req, res, next) => { | ||
// const projectId = _.parseInt(req.params.projectId); | ||
const userId = req.authUser.userId; | ||
try { | ||
const { accessToken, instanceUrl } = await SalesforceService.authenticate(); | ||
// eslint-disable-next-line | ||
const sql = `SELECT Topcoder_Billing_Account__r.id, Topcoder_Billing_Account__r.TopCoder_Billing_Account_Id__c, Topcoder_Billing_Account__r.Billing_Account_Name__c, Topcoder_Billing_Account__r.Start_Date__c, Topcoder_Billing_Account__r.End_Date__c from Topcoder_Billing_Account_Resource__c tbar where UserID__c='${userId}'`; | ||
// and Topcoder_Billing_Account__r.TC_Connect_Project_ID__c='${projectId}' | ||
req.log.debug(sql); | ||
const billingAccounts = await SalesforceService.query(sql, accessToken, instanceUrl, req.log); | ||
res.json(billingAccounts); | ||
} catch (error) { | ||
req.log.error(error); | ||
next(error); | ||
} | ||
}, | ||
]; |
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
/* eslint-disable no-unused-expressions */ | ||
// import chai from 'chai'; | ||
import request from 'supertest'; | ||
import sinon from 'sinon'; | ||
|
||
import models from '../../models'; | ||
import server from '../../app'; | ||
import testUtil from '../../tests/util'; | ||
import SalesforceService from '../../services/salesforceService'; | ||
|
||
// const should = chai.should(); | ||
|
||
describe('Project Billing Accounts list', () => { | ||
let project1; | ||
let salesforceAuthenticate; | ||
let salesforceQuery; | ||
|
||
beforeEach((done) => { | ||
testUtil.clearDb() | ||
.then(() => testUtil.clearES()) | ||
.then(() => { | ||
models.Project.create({ | ||
type: 'generic', | ||
directProjectId: 1, | ||
billingAccountId: 1, | ||
name: 'test1', | ||
description: 'test project1', | ||
status: 'draft', | ||
details: {}, | ||
createdBy: 1, | ||
updatedBy: 1, | ||
lastActivityAt: 1, | ||
lastActivityUserId: '1', | ||
}).then((p) => { | ||
project1 = p; | ||
// create members | ||
return models.ProjectMember.create({ | ||
userId: testUtil.userIds.copilot, | ||
projectId: project1.id, | ||
role: 'copilot', | ||
isPrimary: true, | ||
createdBy: 1, | ||
updatedBy: 1, | ||
}).then(() => models.ProjectMember.create({ | ||
userId: testUtil.userIds.member, | ||
projectId: project1.id, | ||
role: 'customer', | ||
isPrimary: false, | ||
createdBy: 1, | ||
updatedBy: 1, | ||
})); | ||
}).then(() => { | ||
salesforceAuthenticate = sinon.stub(SalesforceService, 'authenticate', () => Promise.resolve({ | ||
accessToken: 'mock', | ||
instanceUrl: 'mock_url', | ||
})); | ||
salesforceQuery = sinon.stub(SalesforceService, 'query', () => Promise.resolve([{ | ||
accessToken: 'mock', | ||
instanceUrl: 'mock_url', | ||
}])); | ||
done(); | ||
}); | ||
}); | ||
}); | ||
|
||
afterEach((done) => { | ||
salesforceAuthenticate.restore(); | ||
salesforceQuery.restore(); | ||
done(); | ||
}); | ||
|
||
after((done) => { | ||
testUtil.clearDb(done); | ||
}); | ||
|
||
describe('List /projects/{id}/billingAccounts', () => { | ||
it('should return 403 for anonymous user', (done) => { | ||
request(server) | ||
.get(`/v5/projects/${project1.id}/billingAccounts`) | ||
.expect(403, done); | ||
}); | ||
|
||
it('should return 403 for a regular user who is not a member of the project', (done) => { | ||
request(server) | ||
.get(`/v5/projects/${project1.id}/billingAccounts`) | ||
.set({ | ||
Authorization: `Bearer ${testUtil.jwts.member2}`, | ||
}) | ||
.send() | ||
.expect(403, done); | ||
}); | ||
|
||
it('should return all attachments to admin', (done) => { | ||
request(server) | ||
.get(`/v5/projects/${project1.id}/billingAccounts`) | ||
.set({ | ||
Authorization: `Bearer ${testUtil.jwts.admin}`, | ||
}) | ||
.send() | ||
.expect(200) | ||
.end((err, res) => { | ||
if (err) { | ||
done(err); | ||
} else { | ||
const resJson = res.body; | ||
resJson.should.have.length(2); | ||
// TODO verify BA fields | ||
done(); | ||
} | ||
}); | ||
}); | ||
|
||
xit('should return all attachments using M2M token with "read:user-billing-accounts" scope', (done) => { | ||
request(server) | ||
.get(`/v5/projects/${project1.id}/billingAccounts`) | ||
.set({ | ||
Authorization: `Bearer ${testUtil.m2m['read:user-billing-accounts']}`, | ||
}) | ||
.send() | ||
.expect(200) | ||
.end((err, res) => { | ||
if (err) { | ||
done(err); | ||
} else { | ||
const resJson = res.body; | ||
resJson.should.have.length(2); | ||
// TODO verify BA fields | ||
done(); | ||
} | ||
}); | ||
}); | ||
}); | ||
}); |
This file contains hidden or 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
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
/** | ||
* Represents the Salesforce service | ||
*/ | ||
import _ from 'lodash'; | ||
import config from 'config'; | ||
import jwt from 'jsonwebtoken'; | ||
|
||
const axios = require('axios'); | ||
|
||
const loginBaseUrl = config.salesforce.CLIENT_AUDIENCE || 'https://login.salesforce.com'; | ||
// we are using dummy private key to fail safe when key is not provided in env | ||
let privateKey = config.salesforce.CLIENT_KEY || 'privateKey'; | ||
privateKey = privateKey.replace(/\\n/g, '\n'); | ||
|
||
const urlEncodeForm = k => | ||
Object.keys(k).reduce((a, b) => `${a}&${b}=${encodeURIComponent(k[b])}`, ''); | ||
|
||
/** | ||
* Helper class to abstract salesforce API calls | ||
*/ | ||
class SalesforceService { | ||
/** | ||
* Authenticate to Salesforce with pre-configured credentials | ||
* @returns {{accessToken: String, instanceUrl: String}} the result | ||
*/ | ||
static authenticate() { | ||
const jwtToken = jwt.sign({}, privateKey, { | ||
expiresIn: '1h', // any expiration | ||
issuer: config.salesforce.CLIENT_ID, | ||
audience: config.salesforce.CLIENT_AUDIENCE, | ||
subject: config.salesforce.SUBJECT, | ||
algorithm: 'RS256', | ||
}); | ||
return axios({ | ||
method: 'post', | ||
url: `${loginBaseUrl}/services/oauth2/token`, | ||
data: urlEncodeForm({ | ||
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', | ||
assertion: jwtToken, | ||
}), | ||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, | ||
}).then(res => ({ | ||
accessToken: res.data.access_token, | ||
instanceUrl: res.data.instance_url, | ||
})); | ||
} | ||
|
||
/** | ||
* Run the query statement | ||
* @param {String} sql the Saleforce sql statement | ||
* @param {String} accessToken the access token | ||
* @param {String} instanceUrl the salesforce instance url | ||
* @param {Object} logger logger to be used for logging | ||
* @returns {{totalSize: Number, done: Boolean, records: Array}} the result | ||
*/ | ||
static query(sql, accessToken, instanceUrl, logger) { | ||
return axios({ | ||
url: `${instanceUrl}/services/data/v37.0/query?q=${sql}`, | ||
method: 'get', | ||
headers: { authorization: `Bearer ${accessToken}` }, | ||
}).then((res) => { | ||
if (logger) { | ||
logger.debug(_.get(res, 'data.records', [])); | ||
} | ||
const billingAccounts = _.get(res, 'data.records', []).map(o => ({ | ||
sfBillingAccountId: _.get(o, 'Topcoder_Billing_Account__r.Id'), | ||
tcBillingAccountId: _.get(o, 'Topcoder_Billing_Account__r.TopCoder_Billing_Account_Id__c'), | ||
name: _.get(o, 'Topcoder_Billing_Account__r.Billing_Account_Name__c'), | ||
startDate: _.get(o, 'Topcoder_Billing_Account__r.Start_Date__c'), | ||
endDate: _.get(o, 'Topcoder_Billing_Account__r.End_Date__c'), | ||
})); | ||
return billingAccounts; | ||
}); | ||
} | ||
} | ||
|
||
export default new SalesforceService(); |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.