Skip to content

Instantly share code, notes, and snippets.

@NickDeckerDevs
Created February 28, 2025 18:36
Show Gist options
  • Save NickDeckerDevs/9dc0385c48250c7d679eae2bde28a86f to your computer and use it in GitHub Desktop.
Save NickDeckerDevs/9dc0385c48250c7d679eae2bde28a86f to your computer and use it in GitHub Desktop.
gpt / claude model comparison for a specific query
//Here’s a function that takes the GraphQL response and calculates the required totals for the company and affiliates:
function processPipelineData(data) {
if (!data || !data.CRM || !data.CRM.contact || !data.CRM.contact.associations) {
return { companyPipeline: {}, affiliatePipeline: {} };
}
const companyData = data.CRM.contact.associations.company?.items[0];
if (!companyData || !companyData.associations) {
return { companyPipeline: {}, affiliatePipeline: {} };
}
// Extract company pipeline deals
const companyDeals = companyData.associations.pipeline?.items || [];
const affiliates = companyData.associations.affiliates?.items || [];
// Extract affiliate pipeline deals
const affiliateDeals = affiliates.flatMap(
(affiliate) => affiliate.associations?.pipeline?.items || []
);
// Helper function to calculate totals
const calculateTotals = (deals) => {
if (deals.length === 0) {
return {
totalNetLoanProceeds: 0,
totalFinancedAmount: 0,
totalDeals: 0,
totalDealsWon: 0,
avgCreditScore: 0,
};
}
let totalNetLoanProceeds = 0;
let totalFinancedAmount = 0;
let totalDeals = deals.length;
let totalDealsWon = 0;
let totalCreditScore = 0;
let creditScoreCount = 0;
deals.forEach((deal) => {
totalNetLoanProceeds += deal.net_loan_proceeds_calculated || 0;
totalFinancedAmount += deal.total_financed_amount_calculated || 0;
if (deal.fundedDate) {
totalDealsWon++;
}
if (deal.credit_score !== null && deal.credit_score !== undefined) {
totalCreditScore += deal.credit_score;
creditScoreCount++;
}
});
return {
totalNetLoanProceeds,
totalFinancedAmount,
totalDeals,
totalDealsWon,
avgCreditScore: creditScoreCount > 0 ? totalCreditScore / creditScoreCount : 0,
};
};
return {
companyPipeline: calculateTotals(companyDeals),
affiliatePipeline: calculateTotals(affiliateDeals),
};
}
/*
Breakdown:
1. Extracts company pipeline deals from companyData.associations.pipeline.items.
2. Extracts all affiliate deals using flatMap to combine multiple affiliate pipelines.
3. Uses a helper function calculateTotals() to:
• Sum net loan proceeds and total financed amount.
• Count total deals and deals won (using fundedDate).
• Calculate average credit score (only counting deals where a credit score exists).
4. Returns an object with separate calculations for the company pipeline and affiliate pipeline.
Let me know if you need any refinements! 🚀
*/
/* 16 seconds
I’m mapping out a GraphQL query with nested associations. It pulls contact info, company details, pipeline data, and affiliate specifics, showing the flow from data retrieval to processing.
I’m piecing together an object that consolidates data for companies and affiliates, focusing on total deals, net loan proceeds, financed amounts, and computing average credit scores, including a fundedDate check.
I’m gathering net loan proceeds, financed amounts, and deals. Then, I’m mapping or reducing affiliate data, summing pipe data, and averaging credit scores while checking if fundedDate is truthy.
I’m thinking through only summing net loan proceeds, considering calculating total financed amount and deals, and averaging credit scores using only those with valid credit scores.
I’m detailing the parsePipelineData function to In my thinking, the function breaks down into parsing data, handling null values, summing deals, net loan proceeds, financed amounts, and averaging credit scores.
^^^ reasoning
Below is an example of how you could implement a helper function in JavaScript to:
1. Take the GraphQL response data as input.
2. Extract the pipeline deals for the primary company.
3. Aggregate (combine) the pipeline deals for all affiliates.
4. Return an object with the totals you specified (net loan proceeds, total financed amount, number of deals, number of deals “won,” average credit score) for both company and affiliates.
*/
/**
* Aggregates pipeline data from an array of deal objects
* @param {Array} pipelineItems - Array of deal objects from the query
* @returns {Object} An object with total deals, total deals won,
* total net loan proceeds, total financed amount, and average credit score
*/
function aggregatePipeline(pipelineItems = []) {
let totalNumberOfDeals = 0;
let totalNumberOfDealsWon = 0;
let totalNetLoanProceeds = 0;
let totalFinancedAmount = 0;
let creditScoreSum = 0;
let creditScoreCount = 0;
pipelineItems.forEach((deal) => {
totalNumberOfDeals++;
// net_loan_proceeds or net_loan_proceeds_calculated
const netLoanProceeds = parseFloat(deal.net_loan_proceeds ?? deal.net_loan_proceeds_calculated ?? 0);
totalNetLoanProceeds += netLoanProceeds;
// total_financed_amount or total_financed_amount_calculated
const financedAmount = parseFloat(deal.total_financed_amount ?? deal.total_financed_amount_calculated ?? 0);
totalFinancedAmount += financedAmount;
// If the fundedDate field is truthy, consider it a won deal
if (deal.fundedDate) {
totalNumberOfDealsWon++;
}
// Credit score
if (deal.credit_score) {
const cs = parseFloat(deal.credit_score);
if (!isNaN(cs)) {
creditScoreSum += cs;
creditScoreCount++;
}
}
});
const averageCreditScore = creditScoreCount > 0 ? (creditScoreSum / creditScoreCount) : 0;
return {
totalNumberOfDeals,
totalNumberOfDealsWon,
totalNetLoanProceeds,
totalFinancedAmount,
averageCreditScore,
};
}
/**
* Main function to process the GraphQL data and return summarized totals
* @param {Object} data - The full GraphQL response
* @returns {Object} An object containing `company` and `affiliates` pipeline totals
*/
function getPipelineTotals(data) {
// Safety checks to avoid runtime errors if data is missing or unexpected
if (
!data?.CRM?.contact?.associations?.company?.items?.length ||
!data.CRM.contact.associations.company.items[0]?.associations
) {
return {
company: null,
affiliates: null,
};
}
const companyItem = data.CRM.contact.associations.company.items[0];
const pipelineItems = companyItem.associations.pipeline?.items || [];
// Aggregate pipeline data at the company level
const companyTotals = aggregatePipeline(pipelineItems);
// Aggregate pipeline data across ALL affiliates
const affiliatesArray = companyItem.associations.affiliates?.items || [];
let allAffiliateDeals = [];
for (const affiliate of affiliatesArray) {
const affiliateDeals = affiliate.associations?.pipeline?.items || [];
allAffiliateDeals = allAffiliateDeals.concat(affiliateDeals);
}
const affiliatesTotals = aggregatePipeline(allAffiliateDeals);
return {
company: companyTotals,
affiliates: affiliatesTotals,
};
}
// Example usage:
// (Assuming `graphqlResponse` is the object you get back from your API call)
const totals = getPipelineTotals(graphqlResponse);
console.log(totals);
/*
Example output structure:
{
company: {
totalNumberOfDeals: 5,
totalNumberOfDealsWon: 3,
totalNetLoanProceeds: 50000,
totalFinancedAmount: 100000,
averageCreditScore: 725
},
affiliates: {
totalNumberOfDeals: 12,
totalNumberOfDealsWon: 8,
totalNetLoanProceeds: 350000,
totalFinancedAmount: 600000,
averageCreditScore: 710
}
}
*/
/*
Explanation
1. aggregatePipeline(pipelineItems)
• Loops through each deal (pipelineItems array).
• Sums up net_loan_proceeds (or fallback to net_loan_proceeds_calculated), total_financed_amount (or fallback to total_financed_amount_calculated), and counts how many deals have a fundedDate.
• Averages the credit scores for deals that have credit_score.
2. getPipelineTotals(data)
• Extracts the first company from the returned GraphQL data (since your query limit is 1, there will be at most one “primary” company in items).
• Aggregates the pipeline items for that single company.
• Iterates over all affiliates, concatenates their pipeline deals, then aggregates the result in one shot.
• Returns a final object with two sets of totals: one for the company and one combined for all affiliates.
This structure allows you to keep your API calls separate from the business-logic function that computes totals, and should be adaptable to whatever shape your final data takes.
*/
/*
This implementation includes:
A main calculatePipelineMetrics function that takes the GraphQL response data and processes it
A helper processDeals function that calculates metrics for an array of deals
3. Proper handling of null/undefined values
Use of calculated fields when available
Separate totals for company and affiliate pipelines
You can use it like this:
*/
function calculatePipelineMetrics(data) {
// Initialize result object with default values
const result = {
company: {
netLoanProceeds: 0,
totalFinancedAmount: 0,
totalDeals: 0,
totalWonDeals: 0,
averageCreditScore: 0
},
affiliates: {
netLoanProceeds: 0,
totalFinancedAmount: 0,
totalDeals: 0,
totalWonDeals: 0,
averageCreditScore: 0
}
}
// Early return if no data
if (!data?.CRM?.contact?.associations?.company?.items?.[0]) {
return result
}
const company = data.CRM.contact.associations.company.items[0]
// Process company pipeline
const companyPipeline = company.associations.pipeline.items || []
const companyMetrics = processDeals(companyPipeline)
result.company = companyMetrics
// Process all affiliates pipeline
const affiliatesPipeline = company.associations.affiliates.items || []
const allAffiliateDeals = affiliatesPipeline.reduce((deals, affiliate) => {
return [...deals, ...(affiliate.associations.pipeline.items || [])]
}, [])
const affiliatesMetrics = processDeals(allAffiliateDeals)
result.affiliates = affiliatesMetrics
return result
}
function processDeals(deals) {
const validDeals = deals.filter(deal => deal) // Remove any null/undefined deals
if (validDeals.length === 0) {
return {
netLoanProceeds: 0,
totalFinancedAmount: 0,
totalDeals: 0,
totalWonDeals: 0,
averageCreditScore: 0
}
}
const metrics = validDeals.reduce((acc, deal) => {
// Use calculated fields if available, otherwise use regular fields
const netProceeds = deal.net_loan_proceeds_calculated || deal.net_loan_proceeds || 0
const financedAmount = deal.total_financed_amount_calculated || deal.total_financed_amount || 0
const creditScore = parseInt(deal.credit_score) || 0
return {
netLoanProceeds: acc.netLoanProceeds + parseFloat(netProceeds),
totalFinancedAmount: acc.totalFinancedAmount + parseFloat(financedAmount),
totalDeals: acc.totalDeals + 1,
totalWonDeals: acc.totalWonDeals + (deal.fundedDate ? 1 : 0),
totalCreditScore: acc.totalCreditScore + creditScore,
validCreditScores: acc.validCreditScores + (creditScore ? 1 : 0)
}
}, {
netLoanProceeds: 0,
totalFinancedAmount: 0,
totalDeals: 0,
totalWonDeals: 0,
totalCreditScore: 0,
validCreditScores: 0
})
return {
netLoanProceeds: metrics.netLoanProceeds,
totalFinancedAmount: metrics.totalFinancedAmount,
totalDeals: metrics.totalDeals,
totalWonDeals: metrics.totalWonDeals,
averageCreditScore: metrics.validCreditScores ?
Math.round(metrics.totalCreditScore / metrics.validCreditScores) : 0
}
}
export default calculatePipelineMetrics
/* additional added */
const response = await graphqlApiCall() // Your API call
const metrics = calculatePipelineMetrics(response)
console.log(metrics)
/* Output will look like:
{
company: {
netLoanProceeds: 1000000,
totalFinancedAmount: 1200000,
totalDeals: 10,
totalWonDeals: 5,
averageCreditScore: 680
},
affiliates: {
netLoanProceeds: 2000000,
totalFinancedAmount: 2400000,
totalDeals: 20,
totalWonDeals: 12,
averageCreditScore: 700
}
}
*/
/*
The function handles edge cases by:
Providing default values if data is missing
Filtering out null/undefined deals
Only counting valid credit scores in the average
Using calculated fields when available, falling back to regular fields
Properly parsing numeric values to avoid NaN issues
*/
// reasoned 14 seconds
/*
Below is one way you might implement the function in JavaScript. In this example, we assume the response data follows the structure from your GraphQL query. The function extracts the deals for the company and for all affiliates, then aggregates totals for net loan proceeds, total financed amount, deal counts, deals won (i.e. those where fundedDate is truthy), and computes an average credit score.
*/
function computePipelineTotals(data) {
// Initialize arrays for deals
let companyPipelineDeals = [];
let affiliatesPipelineDeals = [];
// Safely navigate the returned data structure
if (
data &&
data.CRM &&
data.CRM.contact &&
data.CRM.contact.associations &&
data.CRM.contact.associations.company &&
data.CRM.contact.associations.company.items &&
data.CRM.contact.associations.company.items.length > 0
) {
const company = data.CRM.contact.associations.company.items[0];
// Company pipeline deals
if (
company.associations &&
company.associations.pipeline &&
company.associations.pipeline.items
) {
companyPipelineDeals = company.associations.pipeline.items;
}
// Affiliate pipeline deals across all affiliates
if (
company.associations &&
company.associations.affiliates &&
company.associations.affiliates.items
) {
company.associations.affiliates.items.forEach((affiliate) => {
if (
affiliate.associations &&
affiliate.associations.pipeline &&
affiliate.associations.pipeline.items
) {
affiliatesPipelineDeals = affiliatesPipelineDeals.concat(
affiliate.associations.pipeline.items
);
}
});
}
}
// Helper function to aggregate metrics from an array of deals
function aggregateDeals(deals) {
let totalNetLoanProceeds = 0;
let totalFinancedAmount = 0;
let totalDeals = 0;
let totalDealsWon = 0;
let totalCreditScore = 0;
let creditScoreCount = 0;
deals.forEach((deal) => {
totalDeals++;
// Sum up Net Loan Proceeds (assuming numeric values)
const netLoan = parseFloat(deal.net_loan_proceeds) || 0;
totalNetLoanProceeds += netLoan;
// Sum up Total Financed Amount
const financed = parseFloat(deal.total_financed_amount) || 0;
totalFinancedAmount += financed;
// Count deals won if fundedDate exists (truthy)
if (deal.fundedDate) {
totalDealsWon++;
}
// Average credit score (using credit_score field)
const credit = parseFloat(deal.credit_score);
if (!isNaN(credit)) {
totalCreditScore += credit;
creditScoreCount++;
}
});
return {
totalNetLoanProceeds,
totalFinancedAmount,
totalDeals,
totalDealsWon,
averageCreditScore: creditScoreCount ? totalCreditScore / creditScoreCount : 0,
};
}
// Compute metrics separately for company and affiliates
const companyTotals = aggregateDeals(companyPipelineDeals);
const affiliateTotals = aggregateDeals(affiliatesPipelineDeals);
// Return the combined result
return {
company: companyTotals,
affiliates: affiliateTotals,
};
}
/*
How It Works
1. Extracting Deals:
The function first safely extracts the company pipeline deals from
data.CRM.contact.associations.company.items[0].associations.pipeline.items
and then iterates over each affiliate in
data.CRM.contact.associations.company.items[0].associations.affiliates.items
to combine all affiliate pipeline deals.
2. Aggregating Metrics:
The helper function aggregateDeals loops through each deal and:
• Adds up the numeric values for Net Loan Proceeds and Total Financed Amount.
• Counts the total number of deals.
• Increments a counter for deals where fundedDate is present.
• Sums the credit scores and counts them to later compute an average.
3. Returning the Totals:
Finally, the function returns an object with separate totals for the company and affiliate pipelines.
This approach should let you easily plug in your API call results and get the totals you need.
*/
#intial query
# label: "Pipeline"
# description: "Pipeline Query with Affiliate Data"
# $record_id: "{{ request.contact.contactVid || "1151" }}"
query all_pipeline($record_id:String!){
CRM {
contact(uniqueIdentifier: "hs_object_id", uniqueIdentifierValue: $record_id) {
associations {
company:company_collection__contact_to_company_unlabeled(
limit: 1,
filter: {
has_partner_portal_access__eq: true
}
) {
items {
...company_info
associations {
pipeline: deal_collection__referral_partner(
limit: 10000,
filter: {
pipeline__eq: "65459577"
},
orderBy: createdate__desc,
) {
items {
...pipeline_data
}
}
affiliates: company_collection__master_affiliate_sub_affiliate (limit: 1000) {
items {
...company_info
associations {
pipeline: deal_collection__referral_partner (
limit: 100000,
filter: {
pipeline__eq: "65459577",
}
) {
items {
...pipeline_data
}
}
}
}
}
}
}
}
}
}
}
}
fragment company_info on crm_company {
name
hs_object_id
}
fragment pipeline_data on crm_deal {
affordability
dealname
credit_score: experian_credit_score
contact_first_name
contact_last_name
createdate
closedate
hs_object_id
net_loan_proceeds
net_loan_proceeds_calculated
total_financed_amount
total_financed_amount_calculated
invoice_amount
invoice_amount_retained
invoice_amount_calculated
invoice_date
dealstage
lastStageChange: hs_lastmodifieddate
fundedDate: hs_v2_date_entered_127676948
}
I have this graphql query that I'm going to convert to JS. I already have the api call to take care of this.
I'm going to send the results of the data return to a function I need to create, it will take the data from the call and it will need to total up two different sets of pipeline data. One for the company,a dn one for the companies affiliates (not limited to 1 affiliate, can be combined, we aren't drilling into totals of each affiliate
I need the function to return an object that contains totals on Net Loan Proceeds, Total Financed Amount, total number of deals, total number of deals won (using fundedDate true as the way to understand that) and average credit score -- these should be broken up as company pipeline and affiliate pipeline
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment