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 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 1x 2x 2x 2x 2x 1x 5x 5x 5x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 1x 1x 1x 1x 1x 1x 16x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 1x 1x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 1x 1x 1x 1x 4x 7x 7x 1x 1x 7x 2x 2x 2x 7x 7x 2x 2x 2x 7x 5x 2x 8x 8x | import {authenticate, AuthenticationBindings} from '@loopback/authentication'; import {UserRelations} from '@loopback/authentication-jwt'; import {inject} from '@loopback/core'; import { repository } from '@loopback/repository'; import { get, param, patch, post, Request, requestBody, response, Response, RestBindings } from '@loopback/rest'; import _, {isEmpty} from 'lodash'; import moment from 'moment'; import {roles} from '../config'; import {MysqlDataSource} from "../datasources"; import {ControllerKey} from '../keys'; import {Leads, LeadsRelations, User} from '../models'; import {LeadsRepository, OpportunitiesRepository, UserRepository} from '../repositories'; import errorMessages from '../utils/errorMessages'; import {log} from "../utils/logMethod"; import successMessages from '../utils/successMessages'; import {PaymentsController} from "./"; import {failureHandler, getUID, HandleDomainName, isValidDate, successHandler, validatePayload} from './components'; import {CloseIntegration} from "./components/closeIntegration"; import {baseResponse, CloseCustomLeadReq, getRegistrarLeadsReq, leadsReq, leadsRes, opportunitiesReq, updateLeadReq, webHookReq} from "./requestSpecs"; import {CloseCustomLead, currentUserType, opportunityObject, webHookType} from "./types"; import {agentInfo, closeAgent, registrarLead} from './types/lead.controller.types'; import {opportunityType} from './types/opportunities.types'; let {EbookMaxDownloadMsg, invalidEntry, leadNotFound, permissionDenied, requiredFieldIsMissing} = errorMessages interface oppTypes { domainName: string offerAmount: any closeOpportunityID?: string, } const include = ['user', 'consultant', 'registrar', 'updateByUser', 'payments', {relation: 'opportunities', scope: {'order': ['createdAt ASC']}}] const closeIntegrations = new CloseIntegration() @authenticate("jwt") export class LeadsController { constructor( @repository(UserRepository) public userRepository: UserRepository, @repository(LeadsRepository) public leadsRepository: LeadsRepository, @repository(OpportunitiesRepository) public opportunitiesRepository: OpportunitiesRepository, @inject(AuthenticationBindings.CURRENT_USER) public currentUser: currentUserType, @inject(RestBindings.Http.RESPONSE) protected res: Response, @inject('datasources.mysql') public dataSource: MysqlDataSource, @inject(RestBindings.Http.REQUEST) protected req: Request, @inject(ControllerKey.CLOSE_COMPONENT) public closeIntegration: CloseIntegration, @inject(ControllerKey.PAYMENT_CONTROLLER) public paymentsController: PaymentsController, ) { } @get('/downloadEbook/{UID}') @response(200, baseResponse) @log() async downloadEbook(@param.path.string('UID') UID: string): Promise<any> { let methodName = "downloadEbook" try { Eif (UID) { const result: any = await this.leadsRepository.findOne({where: {UID}}, include); if (result) { Iif (result.ebookDownload >= 2) { throw {message: EbookMaxDownloadMsg, methodName} } else { await this.leadsRepository.updateAll({ebookDownload: result.ebookDownload + 1}, {UID}); return successHandler(this.res, 200, successMessages.proceed) } } else { throw {message: errorMessages.leadNotFound, leadNotFound} } } else { throw {code: 400, message: requiredFieldIsMissing, methodName} } } catch (error) { return this.failureHandler(this.res, 422, error) } } @post('/createOrUpdateOpportunities/', baseResponse) @log() async createOrUpdateOpportunities(@requestBody(opportunitiesReq) requestObj: opportunityType): Promise<any> { try { validatePayload(requestObj, opportunitiesReq) const closeAgents = await this.closeIntegration.getusers() const agent: any = _.find(closeAgents, {id: "user_A08s242iNA9m1EgLM9EEtNbcwKCbDf2mjSyxJ97L01J"}) const opportunities = await this.opportunitiesRepository.find({where: {leadUID: requestObj.leadUID}}); const result = requestObj.opportunity.map(async (obj: any, index: number) => { if (obj.domainName !== "") { obj.domainName = HandleDomainName(obj.domainName) const updatePayload: oppTypes = { domainName: obj.domainName, offerAmount: <any>parseFloat(obj.offerAmount) } const payload: any = { 'value': updatePayload.offerAmount, "lead_id": requestObj.closeUID, "user_id": agent.id, "domainName": obj.domainName, "note": 'The Budget for this domain name is ' + (updatePayload.offerAmount / 100) + " USD" } if (obj.UID) { // if (obj.domainName === "" && obj.closeOpportunityID) { // updatePayload.offerAmount = 0 // await this.closeIntegration.deleteOpportunity(obj.closeOpportunityID) // updatePayload.closeOpportunityID = "" // } else if (obj.domainName !== "" && obj.closeOpportunityID) { // if (needsUpdate(existLead, obj)) { // payload.id = obj.closeOpportunityID // await this.closeIntegration.updateOpportunity(payload) // } else { // return this.failureHandler(this.res, 403, obj.domainName + " is already Exist") // } // } else if (obj.domainName !== "") { // if (domainNameExist(opportunities, obj)) { // let opportunity: any = await this.closeIntegration.createOpportunity(payload) // if (opportunity) { // updatePayload.closeOpportunityID = opportunity.id // } // } else { // error = true // return this.failureHandler(this.res, 403, obj.domainName + " is already Exist") // } // } // return await this.opportunitiesRepository.updateAll(updatePayload, { UID: obj.UID }); } else { if (opportunities.length < 5) { const opportunityObj: {closeOpportunityID: string, leadUID: string, UID: string, domainName: string, offerAmount: any} = obj opportunityObj.UID = getUID() opportunityObj.leadUID = requestObj.leadUID if (obj.domainName) { const opportunity: any = await this.closeIntegration.createOpportunity(payload) if (opportunity) { opportunityObj.closeOpportunityID = opportunity.id } } return this.opportunitiesRepository.create(opportunityObj) } } } }) await Promise.all(result) const latestOpportunity = await this.opportunitiesRepository.find({order: ["createdAt ASC"], where: {leadUID: requestObj.leadUID}}); return successHandler(this.res, 200, latestOpportunity) } catch (error) { return this.failureHandler(this.res, 422, error) } } @get('/getRegistrarLeads') @response(200, getRegistrarLeadsReq) @log() async getRegistrarLeads(): Promise<any> { try { const UID = this.currentUser.UID const limit: any = this.req.query.limit ?? 10 const pageNumber: any = this.req.query.pageNumber ?? 1 const fromDate = this.req.query.fromDate const toDate = this.req.query.toDate const sortBy = this.req.query.sortBy const sortType = this.req.query.sortType let filterByDate = "" if (fromDate) { filterByDate = `AND createdAt >= '${fromDate}'` } if (toDate) { filterByDate = filterByDate + `AND createdAt <= '${toDate}'` } const query = `SELECT createdAt AS date ,SUM(click)AS clicks, COUNT(soldAmount)AS sales, SUM(initialFee) AS commission,SUM(soldAmount) AS sales_commission, SUM(refunds) AS refunds, (SUM(COALESCE(initialFee, 0))+SUM(COALESCE(soldAmount, 0)))- SUM(COALESCE(refunds, 0)) AS total , COUNT(*) OVER() AS totalRows FROM Accounts where registrarUID='${UID}' ${filterByDate} GROUP BY DATE(createdAt) ORDER BY ${sortBy ?? 'createdAt'} ${sortType ?? 'DESC'} limit ${limit} offset ${(pageNumber - 1) * limit}` const result = await this.dataSource.execute(query) const totalRows = result[0]?.totalRows ?? 0 result.map((data: registrarLead, index: number) => { data.date = isValidDate(data.date) ? moment(data.date).utc().format("YYYY-MM-DD") : data.date delete data.totalRows }) return successHandler(this.res, 200, {leads: result, totalRows, limit, pageNumber}) } catch (error) { return this.failureHandler(this.res, 422, error) } } @post('/leads') @log() async create(@requestBody(leadsReq) leads: Leads,): Promise<Response> { try { validatePayload(leads, leadsReq) await this.leadRequestFormValidation(leads) leads.domainName = HandleDomainName(leads.domainName) // send error message if domain name is not valid for example .saw-..com // if (!isValidDomain(leads.domainName)) { // return this.failureHandler(this.res, 422, errorMessages.invalidDomainName) // } // this.req.clientIp = leads.systemIp = this.req.clientIp leads.UID = getUID() leads.updateBy = this.currentUser.UID leads.userUID = leads.userUID ?? this.currentUser.UID let result: any = await this.leadsRepository.findOne({where: {userUID: leads.userUID, domainName: leads.domainName}}, include); Eif (!result) { const leadObj = await this.closeIntegration.createLead({...leads, leadSource: "buy.saw.com", user: this.currentUser}) leads.closeUID = leadObj.id leadObj.agent = await this.paymentsController.registerAgent(leadObj.agent) leads.consultantUID = leadObj.agent.UID result = await this.leadsRepository.create(leads); result = await this.leadsRepository.findOne({where: {UID: result.UID}}) // creating Lead opportunity const payload: opportunityObject = {leadUID: result.UID, closeOpportunityID: leadObj.opportunityId, domainName: leads.domainName, offerAmount: leads.offerAmount} this.createOpportunity(payload) } return successHandler(this.res, 200, result) } catch (error) { return this.failureHandler(this.res, 422, error) } } @post('/createCloseWebHooks/', baseResponse) @log() async createCloseWebHooks(@requestBody(webHookReq) webHook: webHookType,): Promise<any> { try { validatePayload(webHook, webHookReq) const result = await this.closeIntegration.createWebHooks(webHook) return successHandler(this.res, 200, result) } catch (error) { return this.failureHandler(this.res, 403, error,) } } @get('/getWebHooks/', baseResponse) @log() async getWebHooks(): Promise<any> { try { const result = await this.closeIntegration.getWebHooks() return successHandler(this.res, 200, result) } catch (error) { return this.failureHandler(this.res, 403, error) } } @get('/getCloseUsers') @response(200, leadsRes) @log() async getCloseUsers(): Promise<Response> { try { const result = await this.closeIntegration.getusers() return successHandler(this.res, 200, result) } catch (error) { return this.failureHandler(this.res, 403, error) } } @post('/createLeadCustomFields') @response(200, CloseCustomLeadReq) @log() async createLeadCustomFields(@requestBody(CloseCustomLeadReq) closeCustomLead: CloseCustomLead): Promise<Response> { try { validatePayload(closeCustomLead, CloseCustomLeadReq) const result = await this.closeIntegration.createLeadCustomFields(closeCustomLead) return successHandler(this.res, 200, result) } catch (error) { return this.failureHandler(this.res, 403, error) } } @get('/leadInfo/{UID}') @response(200, leadsRes) @log() async leadInfo(@param.path.string('UID') UID: string): Promise<Response> { try { const result = await this.leadsRepository.findOne({where: {UID}, include}); return successHandler(this.res, 200, result) } catch (error) { return this.failureHandler(this.res, 403, error) } } @get('/getMyLeads') @response(200, leadsRes) @log() async getMyLeads(): Promise<Response> { try { const myUID = this.currentUser.UID const result = await this.leadsRepository.find({ where: { or: [ {userUID: myUID}] }, include }); return successHandler(this.res, 200, result) } catch (error: any) { return this.failureHandler(this.res, 403, error) } } @patch('/leads/{UID}', baseResponse) @log() async updateAll(@param.path.string('UID') UID: string, @requestBody(updateLeadReq) leads: any): Promise<Response> { let methodName = "updateAll" try { validatePayload(leads, updateLeadReq) await this.leadRequestFormValidation(leads) leads.updateBy = this.currentUser.UID leads.updatedAt = new Date().toString() const existingLead: (Leads & LeadsRelations) | null = await this.leadsRepository.findOne({where: {UID}, include: ['opportunities']}); Eif (existingLead) { Eif (existingLead.userUID === this.currentUser.UID) { Eif (leads.offerAmount) { const opportunity: any = _.find(existingLead.opportunities, {domainName: existingLead.domainName}) opportunity && await this.opportunitiesRepository.updateAll({offerAmount: leads.offerAmount}, {UID: opportunity.UID}) } // if (leads.isSurveyCompleted) { this.updateSurvey({...leads, phone: this.currentUser.phone, email: this.currentUser.email}, existingLead) this.createNotes(leads, existingLead) // } delete leads.phone delete leads.email await this.leadsRepository.updateAll(leads, {UID}); return successHandler(this.res, 200, successMessages.leadUpdatedSuccessfully) } else { throw {code: 403, message: permissionDenied, methodName} } } else { throw {code: 400, message: leadNotFound, methodName} } } catch (error) { return this.failureHandler(this.res, 403, error) } } @get('/leads') @response(200, leadsRes) @log() async find(): Promise<Response> { let methodName = "find" try { Iif (this.currentUser.role.roleType === roles.admin) { const result = await this.leadsRepository.find({include}); return successHandler(this.res, 200, result) } else { throw {code: 403, message: permissionDenied, methodName} } } catch (error) { return this.failureHandler(this.res, 403, error) } } public updateSurvey = async (leads: any, existLead: any) => { let payload: {description: string, custom: any, contacts?: []} | any = { description: `${leads.email} `, } const checkDescriptionLen = () => { return payload.description.length > 0 ? payload.description + "\n " : payload.description + "" } Eif (leads.preferredContact) { payload = {description: checkDescriptionLen() + "Preferred Contact: " + leads.preferredContact} } Iif (leads.preferText) { payload = {description: checkDescriptionLen() + "I Preferred Text "} } Iif (leads.deadLine) { payload = {...payload, "custom.Deadline": moment(leads.deadLine).utc().format("YYYY-MM-DD")} } Eif (leads.phone ?? leads.email) { const leadUID = existLead.closeUID const name = this.currentUser.name const phone = leads.phone const email = leads.email const leadDetails: any = await this.closeIntegration.getLeadById(leadUID) const contactDetails: any = _.find(leadDetails.contacts, {name}) const contactObject: any = { phones: [{ type: `office`, phone }], emails: [{ type: `office`, email }] } Iif (!contactDetails) { // update new contact details for lead contactObject.name = name payload.contacts = [contactObject] } else { // update existing contact details this.closeIntegration.updateLeadContact(contactDetails.id, contactObject) } } const opportunity: any = _.find(existLead.opportunities, {domainName: leads.domainName}) Iif (opportunity && leads.offerAmount && leads.offerAmount !== existLead.offerAmount) { this.closeIntegration.updateOpportunity({ id: opportunity.closeOpportunityID, note: leads.offerAmount && "The Budget for this domain name is " + leads.offerAmount }) } Eif (existLead.closeUID) { Iif (leads.preferredTime && leads.preferredTime !== existLead.preferredTime && isValidDate(leads.preferredTime)) { // create task this.closeIntegration.createTask({ agentID: "user_A08s242iNA9m1EgLM9EEtNbcwKCbDf2mjSyxJ97L01J", closeLeadID: existLead.closeUID, preferredTime: leads.preferredTime ?? moment().utc().format("YYYY-MM-DD") }) } Eif (!isEmpty(payload)) { this.closeIntegration.updateLead(existLead.closeUID, payload) } } } public createNotes = async (newLead: any, oldLead?: any) => { let note = "" const checkNotesLen = () => { return note.length > 0 ? note + "\n" : note + "" } Eif (!oldLead.isSurveyCompleted) { note = "BUYER SURVEY: " this.leadsRepository.updateAll({isSurveyCompleted: true}, {UID: oldLead.UID}); } Eif (newLead.offerAmount && newLead.offerAmount !== oldLead.offerAmount) { note = checkNotesLen() + `Do you have a budget in mind? ${newLead.offerAmount ?? "-"}` } Eif (newLead.beSeen && newLead.beSeen !== oldLead.beSeen) { note = checkNotesLen() + `Have you contacted the domain owner or seller before and what was the result? ${newLead.beSeen ?? "-"}` } Eif (newLead.questionsAny && newLead.questionsAny !== oldLead.questionsAny) { note = checkNotesLen() + `Any other questions or comments? ${newLead.questionsAny ?? "-"}` } Eif (newLead.marketAnalysis && newLead.marketAnalysis !== oldLead.marketAnalysis) { note = checkNotesLen() + `Other Information? ${newLead.marketAnalysis ?? "-"}` } const notesObj = { note, lead_id: oldLead.closeUID } Eif (note !== "") { this.closeIntegration.createNotesActivity(notesObj) } return true } public createOpportunity = async (opportunityObj: opportunityObject) => { opportunityObj.UID = getUID() try { Eif (opportunityObj.domainName) { this.opportunitiesRepository.create(opportunityObj) } } catch (error) { console.error(error, "error in createOpportunity") } } public async findUser(UID: string): Promise<(User & UserRelations) | any> { return this.userRepository.findOne({where: {UID}, include: ['role']}); } public async leadRequestFormValidation(lead: Leads) { let errorString; let methodName = 'leadRequestFormValidation' if (lead.deadLine) { Eif (!isValidDate(lead.deadLine)) { errorString = errorMessages.invalidDateFormat } } if (!errorString && lead.registrarUID) { const userExist = await this.findUser(lead.registrarUID) Eif (!userExist ?? (userExist && userExist.role.roleType !== roles.registrar)) { errorString = invalidEntry + " registrarUID" } } Iif (!errorString && lead.userUID) { const userExist = await this.findUser(lead.userUID) if (!userExist ?? (userExist && userExist.role.roleType !== roles.customer)) { errorString = invalidEntry + " userUID" } } if (!errorString && lead.consultantUID) { const userExist = await this.findUser(lead.consultantUID) Eif (!userExist ?? (userExist && userExist.role.roleType !== roles.consultant)) { errorString = invalidEntry + " consultantUID" } } if (errorString) { throw {code: 422, message: errorString, methodName} } return true } private failureHandler(res: Response, code: number, error: any): Promise<Response> { let className = error.className || LeadsController.name return failureHandler(res, code, error, className) } } |