Skip to content

Instantly share code, notes, and snippets.

@martintajur
Last active August 29, 2015 14:23
Show Gist options
  • Save martintajur/113e8afd89586f4243b3 to your computer and use it in GitHub Desktop.
Save martintajur/113e8afd89586f4243b3 to your computer and use it in GitHub Desktop.
Convert Pipedrive deals' custom person-type fields into deal participants
/*
Pipedrive person type field as participants linker
MIT Licence.
*/
var Pipedrive = require('pipedrive');
var pipedrive = new Pipedrive.Client('PUT_YOUR_API_TOKEN_HERE');
var personTypeFields = ['0196e433d44471e3cad7306209bc70ed623abd95','dd0e6438e2082ed2a6cdced28aeb7aff3557d3c6'],
batchSize = 200,
dealsConverted = 0,
newFilterId;
var newFilterObject = {
"name": "Deals with custom contacts",
"type": "deals",
"conditions": {
"glue": "and",
"conditions": [
{
"glue": "and",
"conditions": []
},
{
"glue": "or",
"conditions": []
}
]
}
}
pipedrive.DealFields.getAll({ start:0, limit:500 }, function(err, fields) {
if (err) throw err;
fields.forEach(function(field) {
if (personTypeFields.indexOf(field.key) > -1) {
newFilterObject.conditions.conditions[1].conditions.push({
"object": "deal",
"field_id": field.id,
"operator": "IS NOT NULL",
"value": null,
"extra_value": null
});
}
});
console.log('Creating temporary filter');
pipedrive.Filters.add(newFilterObject, function(err, newFilter) {
if (err) throw err;
newFilterId = newFilter.id;
fetchAndConvertDeals(0, function(err) {
console.log('Removing temporary filter');
pipedrive.Filters.remove(newFilterId, function(errRemovingFilter) {
if (errRemovingFilter) throw errRemovingFilter;
console.log('Temporary filter removed!');
if (err) throw err;
process.exit(0);
});
});
});
});
function fetchAndConvertDeals(start, finalCallback) {
var x = 0;
pipedrive.Deals.getAll({ start: start, limit: batchSize }, function(err, deals, additionalData) {
if (err) return finalCallback(err);
deals.forEach(function(deal) {
var participantsToAdd = [];
personTypeFields.forEach(function(fieldKey) {
if (deal[fieldKey] && participantsToAdd.length === 0) {
participantsToAdd.push({ person_id: deal[fieldKey].value });
}
});
var y = 0;
participantsToAdd.forEach(function(participant) {
deal.addParticipant(participant, function(err, participants) {
if (err) return finalCallback(err);
y++;
if (y === participantsToAdd.length) {
console.log('Deal ' + deal.id + ' updated (added person ' + participant.person_id + ' as participant)');
x++;
dealsConverted++;
if (Math.round(x / 10) === (x / 10)) {
console.log(x + ' deals converted');
}
if (x === deals.length) {
if (additionalData.pagination && additionalData.pagination.more_items_in_collection) {
// there is more, fetch and convert those too
fetchAndConvertDeals(additionalData.pagination.next_start);
} else {
// all done
console.log('All deals converted! (' + dealsConverted + ' total)');
finalCallback();
}
}
}
});
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment