All files / src/controllers/components closeIntegration.ts

64.88% Statements 85/131
45.23% Branches 19/42
41.02% Functions 16/39
64.88% Lines 85/131

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 3591x 1x 1x 1x 1x 1x     1x 1x 1x 1x   1x 1x             89x 89x 1x 1x 1x 1x   1x 1x 1x   1x 1x                                                           1x 1x   1x       1x 1x   1x     1x 1x     1x 1x 1x   1x         1x 1x 1x                                             1x 1x                                                                             89x                                             89x 1x   1x     1x 1x             89x 1x   1x 1x 1x 1x   1x                       89x 1x   1x 1x 1x 1x   1x 1x   1x                                                               89x                                     89x 1x   1x   1x 1x                 1x   1x             89x                       89x 1x   1x 1x         89x                     89x   1x   89x     89x     89x     89x 1x 1x           89x                
import axios from "axios";
import isValidDomain from "is-valid-domain";
import * as _ from 'lodash';
import moment from "moment";
import { HandleDomainName, ValidateIPaddress } from ".";
import errorMessages from '../../utils/errorMessages';
import { CloseCustomLead, CloseUserObj, webHookType } from "../types";
import { agentInfo } from "../types/lead.controller.types";
const { permissionDenied } = errorMessages
const CloseIO = require('close.io');
const closeio = new CloseIO(process.env.CLOSE_API_KEY);
const closeBaseURL = `https://${process.env.CLOSE_API_KEY}:@api.close.com/api/v1`
 
export const leadOwnerCustomFieldId = "custom.lcf_NiKdgkQj6F9RSXwL7rcZ5PapAYrqOSsTuvDwL2KLap4"
export class CloseIntegration {
  constructor(
  ) { }
  /**
   * createLead
   */
  // public customFields: any = []
  public closeAgents: agentInfo[] = []
  public createLead = async (lead: any): Promise<any> => {
    let methodName = "createLead"
    try {
      Eif (this.closeAgents.length === 0) {
        this.closeAgents = await this.getusers()
      }
      const description = `${lead.user.email}`
      const jeffCloseID = "user_O3nxdUPKOlzEdjdTLf8L93DqpGdKGyCGwhnCTa3lgGT"
      const agent: CloseUserObj | any = _.find(this.closeAgents, { id: jeffCloseID })
 
      const domainURL = HandleDomainName(lead.domainName)
      const closeLead: any = {
        name: lead.user.name,
        description: description,
 
        contacts: [{
          name: lead.user.name,
          title: `Buyer`,
          emails: [
            {
              type: `office`,
              email: lead.user.email
            }
          ],
          phones: [
            {
              type: `office`,
              phone: lead.user.phone ? lead.user.phone.toString() : ""
            }
          ]
        },
        ],
        addresses: [],
        custom: {
          "Lead Owner": agent.id,
          "Lead Source": lead.leadSource,
          "CC Charged": 0,
          "Creation Date": moment().format("DD/MM/YYYY")
        },
      }
 
      Eif (domainURL) {
        closeLead.custom["Domain Name"] = domainURL
      }
      Iif (lead.formName) {
        closeLead.custom["Form Name"] = lead.formName
      }
 
      Eif (lead.systemIp && ValidateIPaddress(lead.systemIp)) {
        closeLead.custom["IP Address"] = lead.systemIp
      }
      Iif (lead.registrar) {
        closeLead.custom["Registrar Name"] = lead.registrar.name || "sawBuyerBroker"
      }
      Eif (isValidDomain(domainURL)) {
        closeLead.url = domainURL
      }
 
      return await axios.post(closeBaseURL + '/lead', closeLead).then(async res => {
        Eif (res.status === 200) {
          Eif (res.data) {
 
            const opportunity = {
              'value': lead.offerAmount,
              "lead_id": res.data.id,
              "domainName": domainURL,
            }
            const opportunityResponse: any = await this.createOpportunity(opportunity)
            res.data.opportunityId = opportunityResponse.id
            Iif (lead.comments) {
              let notes = {
                note: `
                  Comments: ${lead.comments}
                  `,
                lead_id: res.data.id
              }
              await this.createNotesActivity(notes)
            }
 
 
            // let notes = {
            //   note: `
            //   Contacted Domain Owner: ${lead.contactedOwner || "No"}
            //   Have you made an offer before if so what happened?: ${lead.offerAmount || "No"}
            //   Do you have a deadline?: ${lead.deadLine || "No"}
            //   Other Information?: ${lead.otherInfo || "No"}
            //   `,
            //   lead_id: res.data.id
            // }
            // await this.createNotesActivity(notes)
 
          }
          res.data.agent = agent
          return res.data
        }
        return {}
      }).catch(e => {
        console.error(e.response.data, "Error in create close lead ")
        let message = JSON.stringify(e.response.data)
 
        throw { code: 422, message, methodName, className: CloseIntegration.name }
      })
    } catch (error) {
      console.error(error, "Error in create close lead ")
      throw { code: 422, message: error, methodName }
    }
  }
 
  // public getContact = async () => {
  //   let methodName = "getContact"
  //   // const leadUID = "lead_BdxoKnysB7DMQASGuNwkNDvuoB2P6s3kvctnBPnVafo"
  //   const contactID = "cont_hA29CqTGd61oHGBKXn2AlQSS2cT4mxTPPKapYwsyztu"
  //   const payload = {
  //     phones: [{
  //       type: `office`,
  //       phone: "+919092429504"
  //     },
  //     {
  //       type: `office`,
  //       "phone": "+918667587229"
  //     }]
  //   }
  //   return axios.put(closeBaseURL + "/contact/" + contactID, payload).then(res => {
  //     return res.data
  //   }).catch(e => {
  //     throw {code: 422, message: e.response.data, methodName, className: CloseIntegration.name}
  //   })
  // }
  /**
 * createWebHooks to receive any new update in the lead
 * close will hit this url when lead status gets changed
 */
  public createWebHooks = async (webHook: webHookType): Promise<CloseEvent> => {
    let methodName = "createWebHooks"
    const url: string = process.env.API_URL ?? ""
    const payload = {
      url: url + '/closeStatusUpdate',
      events: [
        {
          object_type: `lead`,
          action: `updated`
        },
        {
          object_type: `opportunity`,
          action: `updated`
        },
      ]
    }
    return axios.post(closeBaseURL + '/webhook/', payload).then(res => {
      return res.data
    }).catch(e => {
      throw { code: 422, message: e.response.data, methodName, className: CloseIntegration.name }
    })
  }
 
  public updateLeadContact = async (contactID: string, payload: any): Promise<CloseEvent> => {
    let methodName = "updateLeadContact"
 
    Iif (contactID === "") {
      throw { code: 422, message: permissionDenied, methodName, className: CloseIntegration.name }
    }
    return axios.put(closeBaseURL + "/contact/" + contactID, payload).then(res => {
      return res.data
    }).catch(e => {
      throw { code: 422, message: e.response.data, methodName, className: CloseIntegration.name }
    })
  }
 
 
  public getWebHooks = async (): Promise<CloseEvent> => {
    let methodName = "getWebHooks"
 
    return axios.get(closeBaseURL + '/webhook').then(res => {
      let data = []
      Eif (res.status === 200) {
        data = res.data.data
      }
      return data
    }).catch(e => {
      throw { code: 422, message: e.response.data, methodName, className: CloseIntegration.name }
    })
  }
  // public deleteAllWebHook = async (listId: {id: string}[]): Promise<any> => {
  //   return listId.forEach(async (obj: any) => {
  //     return axios.delete(closeBaseURL + '/webhook/' + obj.id)
  //   });
 
  // }
 
  public getusers = async (): Promise<agentInfo[]> => {
    let methodName = "getusers"
 
    return axios.get(closeBaseURL + '/user').then(res => {
      let data = []
      Eif (res.status === 200) {
        data = res.data.data
      }
      Eif (this.closeAgents.length === 0) {
        this.closeAgents = data
      }
      return data
    }).catch(e => {
      throw { code: 422, message: e.response.data, methodName, className: CloseIntegration.name }
    })
  }
 
  // public getCustomFields = async (): Promise<CloseEvent> => {
  //   let methodName = "getCustomFields"
 
  //   return axios.get(closeBaseURL + '/custom_field/lead').then(res => {
  //     let data = []
  //     if (res.status === 200) {
  //       data = res.data.data
  //     }
  //     return data
  //   }).catch(e => {
  //     console.error(e, "CustomFields Error")
  //     throw {code: 422, message: e.response.data, methodName, className: CloseIntegration.name}
  //   })
  // }
  // public deleteOpportunity = async (id: string): Promise<CloseEvent> => {
  //   let methodName = "deleteOpportunity"
 
  //   return axios.delete(closeBaseURL + '/opportunity/' + id).then(res => {
  //     return res.data
  //   }).catch(e => {
  //     console.error(e.response.data, "Error in update close lead opportunity ")
  //     throw { code: 422, message: e.response.data, methodName, className: CloseIntegration.name }
  //   })
  // }
 
 
  public createTask = async (payload: any): Promise<CloseEvent> => {
    let methodName = "createTask"
 
    const jeffCloseID = "user_O3nxdUPKOlzEdjdTLf8L93DqpGdKGyCGwhnCTa3lgGT"
    const tasks = {
      "_type": "lead",
      "assigned_to": payload.agentID || jeffCloseID,
      "text": "follow up",
      "date": payload.preferredTime,
      "is_complete": false,
      "lead_id": payload.closeLeadID
    }
    return axios.post(closeBaseURL + '/task', tasks).then(res => {
      return res.data
    }).catch(e => {
      console.error(e.response.data, "Error in create tasks ")
      throw { code: 422, message: e.response.data, methodName, className: CloseIntegration.name }
    })
  }
  public createOpportunity = async (payload: any): Promise<CloseEvent> => {
    let methodName = "createOpportunity"
 
    const jeffCloseID = "user_O3nxdUPKOlzEdjdTLf8L93DqpGdKGyCGwhnCTa3lgGT"
    // value set to 0 initially, once domain is sold then agent will update the value
    const budget = parseFloat(payload.value) * 100
    const opportunity = {
      'value': budget,
      "lead_id": payload.lead_id,
      "status_id": "In progress",
      "note": budget && `The Budget for ${HandleDomainName(payload.domainName)} name is ` + payload.value,
      "custom.cf_CaM1E7txihl7QwT4RKuRowPMU3rRf9bsbAxDC1T8UNM": HandleDomainName(payload.domainName),
 
      user_id: payload.user_id || jeffCloseID
    }
    return axios.post(closeBaseURL + '/opportunity', opportunity).then(res => {
 
      return res.data
    }).catch(e => {
      console.error(e.response.data, "Error in create opportunity ")
      let message = errorMessages.opportunityError //JSON.stringify(e.response.data)
      throw { code: 422, message, methodName, className: CloseIntegration.name }
    })
  }
  public updateOpportunity = async (opportunity: any): Promise<CloseEvent> => {
    let methodName = "updateOpportunity"
 
    return axios.put(closeBaseURL + '/opportunity/' + opportunity.id, opportunity).then(res => {
      return res.data
    }).catch(e => {
      console.error(e.response.data, "Error in update close lead opportunity ")
      throw { code: 422, message: e.response.data, methodName, className: CloseIntegration.name }
    })
  }
 
 
  public createNotesActivity = async (notes: any): Promise<CloseEvent> => {
    let methodName = "createNotesActivity"
 
    return axios.post(closeBaseURL + '/activity/note/', notes).then(res => {
      return res.data
    }).catch(e => {
      throw { code: 422, message: e, methodName, className: CloseIntegration.name }
    })
  }
  public createLeadCustomFields = async (closeCustomLead: CloseCustomLead): Promise<CloseEvent> => {
    let methodName = "createLeadCustomFields"
 
    return axios.post(closeBaseURL + '/custom_field/lead', closeCustomLead).then(res => {
      return res.data
    }).catch(e => {
      console.error(e.response.data, "Error in create Notes ")
      throw { code: 422, message: e.response.data, methodName, className: CloseIntegration.name }
    })
  }
 
  public updateLead = async (leadId: string, payload: any): Promise<CloseEvent> => {
    // leadId = leadId || 'lead_Mx6QEpFqVZWY7CO6cVR1Kpi8JSjhQ96zfIscpejxqzD'
    return await closeio.lead.update(leadId, payload)
  }
  public deleteLead = (leadId: string): Promise<CloseEvent> => {
    return closeio.lead.delete({ id: leadId })
  }
  public getAllLead = (): Promise<CloseEvent> => {
    return closeio.lead
  }
  public getLead = (): Promise<CloseEvent> => {
    return closeio.lead.read()
  }
  public getLeadById = (leadID: string): Promise<CloseEvent> => {
    return axios.get(closeBaseURL + "/lead/" + leadID).then(res => {
      return res.data
    }).catch(e => {
      return e.response.data
    })
  }
 
  public searchLead = (payload?: object): Promise<CloseEvent> => {
    return closeio.lead.search(payload)
  }
 
 
 
 
}