Sure, here it is!
//Import required libraries & Hubspot functions
const hubspot = require('@hubspot/api-client');
exports.main = async (event, callback) => {
//Create a new HubSpot Client session to make the API call
const hubspotClient = new hubspot.Client({
accessToken: process.env.HUBSPOTAPIKEY
});
// Get primary company of the deal
const AssociatedPrimaryCompany = await hubspotClient.crm.associations.v4.basicApi.getPage('deal', event.object.objectId, 'company')
.then(AssociatedPrimaryCompany => {
const el = AssociatedPrimaryCompany.results.find(({ associationTypes }) => associationTypes.find(({ label }) => label === 'Primary'))
if (el) {
return el.toObjectId;
} else {
console.log('Primary company not found', AssociatedPrimaryCompany.results)
}
});
// Retrieve data for deal to renew
const distribution_channel = event.inputFields['centrale_d_achat'];
const pb_client_id = event.inputFields['pb_client_id'];
const deal_owner = event.inputFields['hubspot_owner_id'];
const facility_type = event.inputFields['facility_type'];
const sales_specialist_owner = event.inputFields['sales_specialist_owner'];
const cs_owner = event.inputFields['cs_owner'];
const account_manager = event.inputFields['account_manager'];
const ids_hublo = event.inputFields['insitution_id_medgo'];
const ids_mstaff = event.inputFields['id_mstaff'];
const last_billed_date = Number(event.inputFields['last_billed_date']);
const hublo_product = event.inputFields['hublo_product'];
const renewal_ownership = event.inputFields['renewal_ownership'];
const country = event.inputFields['country'];
const beds = event.inputFields['beds'];
const logiciel_de_gestion_des_temps = event.inputFields['logiciel_de_gestion_des_temps'];
const first_day_billed = Number(event.inputFields['billing_start_date']);
const cb_external_id = event.inputFields['cb_external_id'];
// Calculate other data needed
const new_renewal_date = new Date(last_billed_date)
new_renewal_date.setFullYear(new_renewal_date.getFullYear() + 1)
const new_first_day_billed = new Date(first_day_billed)
new_first_day_billed.setFullYear(new_first_day_billed.getFullYear() + 1)
const company_name = await hubspotClient.crm.companies.basicApi.getById(AssociatedPrimaryCompany, ['name']);
const deal_name = "Renewal " + new_renewal_date.getFullYear() + " - "+ company_name.properties.name + " - " + hublo_product
// Create renewal deal properties
const properties = {
"dealname": deal_name,
"closedate": last_billed_date.valueOf(),
"billing_start_date": new_first_day_billed.valueOf(),
"last_billed_date": new_renewal_date.valueOf(),
"hubspot_owner_id": deal_owner,
"pipeline": 32159864,
"dealstage": 204036709,
"insitution_id_medgo": ids_hublo,
"centrale_d_achat": distribution_channel,
"renewal_deal_id" : event.object.objectId,
"pb_client_id" : pb_client_id,
"facility_type" : facility_type,
"sales_specialist_owner" : sales_specialist_owner,
"cs_owner" : cs_owner,
"account_manager" : account_manager,
"ids_mstaff" : ids_mstaff,
"hublo_product" : hublo_product,
"renewal_ownership" : renewal_ownership,
"country" : country,
"beds" : beds,
"logiciel_de_gestion_des_temps" : logiciel_de_gestion_des_temps,
"dealtype" : 'Renewal',
"cb_external_id" : cb_external_id,
};
// Create the deal
const NewDealID = await hubspotClient.crm.deals.basicApi.create({ properties })
.then(DealCreateResponse => {
return (DealCreateResponse.id);
});
// Get line items associated to the deal
const associatedLineItems = await hubspotClient.crm.associations.v4.basicApi.getPage('deal', event.object.objectId, 'line_items')
.then(associatedLineItems => {
return associatedLineItems.results.map(({ toObjectId }) => String(toObjectId))
});
var inputs = await Promise.all(associatedLineItems.map(async (lineItemId) => {
const lineItemResponse = await hubspotClient.crm.lineItems.basicApi.getById(lineItemId, [
'quantity',
'discount',
'price',
'hs_product_id',
'recurringbillingfrequency',
'hublo_item',
'is_pool_included',
'is_contract_add_on_included',
'contract_add_on_price',
'hs_recurring_billing_period',
'hs_sku',
'cb_item_id',
'cb_item_family_id',
'cb_discount_frequency',
'cb_item_type',
'cb_site_name',
'cb_subscription_type',
'cb_billing_cycles',
'hs_recurring_billing_start_date',
'type_of_revenue'
]);
if (lineItemResponse.properties.hs_recurring_billing_start_date != null) {
var bsd = new Date(lineItemResponse.properties.hs_recurring_billing_start_date)
bsd.setFullYear(bsd.getFullYear() + 1)
lineItemResponse.properties.hs_recurring_billing_start_date = bsd
}
lineItemResponse.properties.type_of_revenue = 'renew'
const properties = lineItemResponse.properties;
// Exclude properties not needed for the clone or that should not be copied
['createdate', 'hs_lastmodifieddate', 'hs_object_id'].forEach(prop => delete properties[prop]);
console.log(properties)
const associations = [{
to: { id: NewDealID },
types: [
{
associationCategory: "HUBSPOT_DEFINED",
associationTypeId: 20,
},
],
}];
return {
properties,
associations
};
}));
await hubspotClient.crm.lineItems.batchApi.create({ inputs });
// Get all associated companies
const AssociatedCompanies = await hubspotClient.crm.associations.v4.basicApi.getPage('deal', event.object.objectId, 'companies')
.then(AssociatedCompaniesResponse => {
return AssociatedCompaniesResponse.results.map(({ toObjectId }) => String(toObjectId))
});
// Write companies associations to renewal deal including primary one
var inputs = AssociatedCompanies.map(id => {
let relationship;
if (id == AssociatedPrimaryCompany) {
relationship = 'deal_to_company';
} else {
relationship = 'deal_to_company_unlabeled';
}
return {
_from: { id: NewDealID },
to: { id },
type: relationship
}
})
const BatchInputPublicAssociationCompanies = { inputs };
await hubspotClient.crm.associations.batchApi.create("Deals", "Companies", BatchInputPublicAssociationCompanies);
// Get contacts associations
const AssociatedContacts = await hubspotClient.crm.associations.v4.basicApi.getPage('deal', event.object.objectId, 'contact')
.then(AssociatedContactsResponse => {
return AssociatedContactsResponse.results.map(({ toObjectId }) => String(toObjectId))
});
// Write contact associations to renewal deal
var inputs = AssociatedContacts.map(id => ({
_from: { id: NewDealID }, // please note the _ before 'from'!!!
to: { id },
type: 'deal_to_contact'
}))
const BatchInputPublicAssociationContacts = { inputs };
await hubspotClient.crm.associations.batchApi.create("Deals", "Contacts", BatchInputPublicAssociationContacts);
// Pass information back as a data output to use as a data input with Copy to Property workflow action.
callback({
outputFields: {
NewDealID: NewDealID,
}
});
}