const request = require('request-promise'); const moment = require('moment'); module.exports = function (API_KEY, deals, activities, app, type, pbl, address, test){ //moment().format(); var soonPart = {}; var laterPart = {}; let soon = deals.filter(deal => ( deal.stage_id === app && deal[type.key] === type.refi || deal.stage_id === app && deal[type.key] === type.purchase && deal[pbl.key] === pbl.no )).reduce((obj, deal) => { ...obj, [deal.id]:deal }); let later = deals.filter(deal => ( !soon[deal.id] && ( deal.stage_id === app && deal[type.key] === type.purchase && deal[pbl.key] === pbl.yes && deal[address.key] === '' || deal.stage_id === app && deal[type.key] === type.purchase && deal[pbl.key] === pbl.yes && deal[address.key] === null ) )).reduce((obj, deal) => { ...obj, [deal.id]:deal }); let have = activities.filter(a => a.subject === 'W-2') .reduce((obj, a) => { ...obj, [`${a.deal_id}${deal.person_id}`]: a }); console.log('Here are the people who already have a W-2 activity:'); console.log(Object.keys(have)); let soonArr = Object.keys(soon).map(d => +d); console.log('Here are the deals that could potentially need a W-2 soon:'); console.log(soonArr); const getId = url => request(url).then(b => JSON.parse(b).data) Promise.all(soonArr.map(d => getId(`https://api.pipedrive.com/v1/deals/${d}/participants?start=0&api_token=${API_KEY}`))) .then(results => results.reduce((obj, part) => { ...obj, [`${part.related_item_id}${part.person.id}`]:part }, {})) .then(soonPart => { console.log('Here are the people associated with those deals that are EMPLOYED:'); console.log(Object.keys(soonPart)); let soonQueue = Object.keys(soonPart).filter(part => Object.keys(have).indexOf(part) === -1); console.log('Here is the soon queue:'); console.log(soonQueue); return Promise.all(soonQueue.map(cat => request.post( `https://api.pipedrive.com/v1/activities?api_token=${API_KEY}`, { form: { subject : 'W-2', deal_id : soonPart[cat].related_item_id, person_id: soonPart[cat].person.id, type : 'task', note : `Sign and scan 1003 for ${soonPart[cat].person_id.name}.`, due_date : moment().add(3, 'days').format('YYYY-MM-DD')} } ))); }) .then(function() { console.log("Do moar shit heeeeaaaaare!!!"); }); }