Hi All,
Apologies Im not really a developer but Ive managed to do this custom coding to roll up closed won start and end dates from deals to company level so I can see their start date and their end dates through their time. I will attach the code below however despite having successful outputs that match exactly to my date pickers formats it keeps saying invalid dates in tests? Apologies for the long message in advance
const axios = require(‘axios’);
exports.main = async (event, callback) => {
const companyId = event.inputFields[‘hs_object_id’];
const apiKey = process.env.HAPIKEY;
const headers = {
Authorization: `Bearer ${apiKey}`,
‘Content-Type’: ‘application/json’
};
try {
const requestBody = { inputs: [{ id: companyId.toString() }] };
console.log(‘Requesting batch associations with body:’, JSON.stringify(requestBody));
const batchRes = await axios.post(
‘https://api.hubapi.com/crm/v3/associations/company/deal/batch/read’,
requestBody,
{ headers }
);
const dealIds = batchRes.data.results[0]?.to?.map(d => d.id) || [];
console.log(‘Associated deal IDs:’, dealIds.join(', '));
if (dealIds.length === 0) {
return callback({
outputFields: {
start_date: null,
end_date: null
}
});
}
let earliestStart = null;
let latestEnd = null;
for (const dealId of dealIds) {
const dealRes = await axios.get(
`https://api.hubapi.com/crm/v3/objects/deals/${dealId}?properties=dealstage,contract_start_date,contract_end_date__ced_`,
{ headers }
);
const props = dealRes.data.properties;
console.log(`Deal ${dealId} properties:`, props);
if (props.dealstage !== ‘757916358’) {
console.log(`Deal ${dealId} is not in target dealstage.`);
continue;
}
const start = props.contract_start_date ? new Date(props.contract_start_date) : null;
const end = props.contract_end_date__ced_ ? new Date(props.contract_end_date__ced_) : null;
if (!start || !end) {
console.log(`Deal ${dealId} missing start or end date.`);
continue;
}
if (!earliestStart || start < earliestStart) earliestStart = start;
if (!latestEnd || end > latestEnd) latestEnd = end;
}
// Format date as DD/MM/YYYY (with slashes)
const format = date => {
const dd = String(date.getDate()).padStart(2, ‘0’);
const mm = String(date.getMonth() + 1).padStart(2, ‘0’);
const yyyy = date.getFullYear();
return `${dd}/${mm}/${yyyy}`; // <-- day first with slashes
};
const output = {
start_date: earliestStart ? format(earliestStart) : null,
end_date: latestEnd ? format(latestEnd) : null
};
console.log(‘Final Output Fields:’, output);
return callback({ outputFields: output });
} catch (error) {
console.error(‘Custom code error:’, error.response?.data || error.message);
return callback({
outputFields: {
start_date: null,
end_date: null
}
});
}
};








