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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x | import {authenticate, AuthenticationBindings} from '@loopback/authentication'; import {UserRelations} from '@loopback/authentication-jwt'; import {inject} from '@loopback/core'; import { repository, Where } from '@loopback/repository'; import { get, param, post, requestBody, response, Response, RestBindings } from '@loopback/rest'; import _ from "lodash"; import moment from 'moment'; import {AuthController} from '.'; import {roles} from '../config'; import {ControllerKey, PasswordHasherBindings, UserServiceBindings} from '../keys'; import {Payments, PromoCodes, PromoCodesRelations, User} from '../models'; import {LeadsRepository, PaymentsRepository, PromoCodesRepository, PromoDetailsRepository, RolesRepository, UserDetailsRepository, UserRepository} from '../repositories'; import {sendPaidSuccessEmail} from '../services/email'; import {BcryptHasher} from '../services/hash.password'; import {MyUserService} from '../services/user-service'; import errorMessages from '../utils/errorMessages'; import {log} from "../utils/logMethod"; // import {AccountsController} from './accounts.controller'; import {failureHandler, getUID, successHandler, validatePayload} from './components'; import {CloseIntegration} from './components/closeIntegration'; import StripeIntegrations from "./components/stripeIntegrations"; import {countReq, getMyPaymentsRes, getPaymentsByIDRes, paymentReq, promoReq, stripeVerificationReq} from './requestSpecs'; import {currentUserType, promoReqType} from './types'; let {paymentNotCompleted, permissionDenied, requestBodyIsInvalid, requiredFieldIsMissing} = errorMessages const stripeIntegrations = new StripeIntegrations() @authenticate("jwt") export class PaymentsController { constructor( @repository(PaymentsRepository) public paymentsRepository: PaymentsRepository, @inject(AuthenticationBindings.CURRENT_USER) public currentUser: currentUserType, @inject(RestBindings.Http.RESPONSE) protected res: Response, @repository(UserRepository) public userRepository: UserRepository, @repository(LeadsRepository) public leadsRepository: LeadsRepository, @repository(UserDetailsRepository) public userDetailsRepository: UserDetailsRepository, @repository(RolesRepository) public rolesRepository: RolesRepository, @inject(PasswordHasherBindings.PASSWORD_HASHER) public hasher: BcryptHasher, @inject(ControllerKey.AUTH_CONTROLLER) public authController: AuthController, @inject(ControllerKey.CLOSE_COMPONENT) public closeIntegration: CloseIntegration, // @inject(ControllerKey.ACCOUNTS_CONTROLLER) public accountController: AccountsController, @inject(UserServiceBindings.USER_SERVICE) public userService: MyUserService, @repository(PromoCodesRepository) public promoCodesRepository: PromoCodesRepository, @repository(PromoDetailsRepository) public promoDetailsRepository: PromoDetailsRepository, ) { } @post('/paymentUsingPromoCode') @response(200, promoReq) @log() async paymentUsingPromoCode(@requestBody(promoReq) payload: promoReqType): Promise<Response> { let methodName = "paymentUsingPromoCode" try { let promoCode: (PromoCodes & PromoCodesRelations) | null = await this.promoCodesRepository.findOne({where: {code: payload.code}, include: ["promoDetails"]}) if (promoCode) { let expired = moment(promoCode.validThru).utc().isBefore(moment().utc().format()) if (expired) throw {message: errorMessages.promoCodeExpired, methodName} if (!promoCode.reUsabelCount && promoCode.promoDetails) throw {message: errorMessages.promoCodeIsUsed, methodName} if (promoCode.reUsabelCount && promoCode.reUsabelCount <= promoCode.promoDetails.length) { let findCurrentUser = _.find(promoCode.promoDetails, {usedByUID: this.currentUser.UID}) if (findCurrentUser) throw {message: errorMessages.promoUsedBySameUser, methodName} } let paymentPayload = { UID: getUID(), promoUID: promoCode.UID, status: "succeeded", leadUID: payload.leadUID, } await this.paymentsRepository.create(paymentPayload); const leadDetails = await this.assignedAgent({leadUID: payload.leadUID, amountPaid: 0, promoUsed: true}) if (_.isEmpty(leadDetails)) throw {message: errorMessages.leadNotFound, methodName} let promoDetails = { UID: getUID(), promoUID: promoCode.UID, leadUID: payload.leadUID, usedByUID: this.currentUser.UID } await this.promoDetailsRepository.create(promoDetails); return successHandler(this.res, 200, leadDetails) } else { throw {message: errorMessages.promoCodeIsNotValid, methodName} } } catch (error) { return this.failureHandler(this.res, 422, error) } } @post('/stripe/webHook') @response(200, countReq) @log() async createStripWebHook(): Promise<Response> { try { const webHookResponse = stripeIntegrations.createWebHook() return successHandler(this.res, 200, webHookResponse) } catch (error) { return this.failureHandler(this.res, 422, error) } } @post('/stripeVerification') @response(200, countReq) @log() async stripeVerification(@requestBody(stripeVerificationReq) body: {leadUID: string, id: string}): Promise<Response> { try { validatePayload(body, stripeVerificationReq) const result = await this.paymentsRepository.updateAll({status: "succeeded"}, {paymentID: body.id}); const paymentDetails = await this.paymentsRepository.findOne({where: {paymentID: body.id}}); Iif (result.count && paymentDetails) { const lead = await this.assignedAgent({leadUID: body.leadUID, amountPaid: paymentDetails.offerAmount}) return successHandler(this.res, 200, lead) } else { return successHandler(this.res, 422, paymentNotCompleted) } } catch (error) { return this.failureHandler(this.res, 422, error) } } @post('/payments') @response(200, paymentReq) @log() async create(@requestBody(paymentReq) payments: Payments): Promise<Response> { let methodName = "create" try { validatePayload(payments, paymentReq) Eif (payments.leadUID) { payments.UID = getUID() payments.userUID = payments.userUID || this.currentUser.UID const payment = await stripeIntegrations.paymentIntents(payments, this.currentUser) Eif (payment.error) { throw {code: 422, message: payment.error?.message || payment.error, methodName} } else { const status = payment.data.status if (status === 'succeeded' || status === "requires_action") { payments.paymentID = payment.data.id payments.status = payment.data.status await this.paymentsRepository.create(payments); if (status === "succeeded") { const lead = await this.assignedAgent(payments) return successHandler(this.res, 200, lead) } else if (payment.data.status === "requires_action") { return await successHandler(this.res, 203, {clientSecret: payment.data.client_secret}) } else { throw {code: 422, message: paymentNotCompleted, methodName} } } else { throw {code: 422, message: payment.data.status, methodName} } } } else { throw {code: 422, message: requiredFieldIsMissing, methodName} } } catch (error: any) { return this.failureHandler(this.res, 422, error) } } @get('/payments/count') @response(200, countReq) @log() async count(@param.where(Payments) where?: Where<Payments>): Promise<Response> { try { const result = await this.paymentsRepository.count(where); return successHandler(this.res, 200, result) } catch (error) { return this.failureHandler(this.res, 422, error) } } @get('/payments') @log() async find(): Promise<Response> { let methodName = "find" try { Iif (this.currentUser.role.roleType === roles.admin) { const result = await this.paymentsRepository.find({include: ['user']});; return successHandler(this.res, 200, result) } else { throw {code: 403, message: permissionDenied, methodName} } } catch (error) { return this.failureHandler(this.res, 422, error) } } @get('/getMyPayments') @response(200, getMyPaymentsRes) @log() async getMyPayments(): Promise<Response> { try { const result = await this.paymentsRepository.find({where: {userUID: this.currentUser.UID}, include: ['user']}); return successHandler(this.res, 200, result) } catch (error) { return this.failureHandler(this.res, 422, error) } } @get('/payments/{UID}') @response(200, getPaymentsByIDRes) @log() async findUser(@param.path.string('UID') UID: string,): Promise<Response> { try { const result = await this.paymentsRepository.findOne({where: {UID}, include: ['user']}); return successHandler(this.res, 200, result) } catch (error) { return this.failureHandler(this.res, 422, error) } } private async assignedAgent(payments: {leadUID: string, amountPaid: any, promoUsed?: boolean}) { const methodName = "assignedAgent" const leadObj = await this.leadsRepository.findOne({where: {UID: payments.leadUID}, include: ['opportunities']}); const closeUser: (User & UserRelations) | null = await this.agentRoundRobin() let note = `This is a lead created using Buyer Broker App. He/She has paid $${payments.amountPaid} to speak to you.` if (payments.promoUsed) { note = `This is a lead created using Buyer Broker App. A promo code has been applied instead of a fee to speak to you. ` } const payload = { note: note + ` Please keep in mind we need to pay the registrar 20% of the sale. The buyer will see the status you update in the Opportunity. The four statuses for each name are: In Progress Sold Refunded Canceled`, lead_id: leadObj?.closeUID } if (leadObj) { // if (leadObj.payments) { // throw {code: 422, message: errorMessages.alreadyPaid, methodName} // } // Initial amount update in account table const leadUID = leadObj?.UID this.authController.createRegistrarAccounts({initialFee: payments.amountPaid, leadUID}) const opportunity: any = _.find(leadObj.opportunities, {domainName: leadObj.domainName}) this.closeIntegration.createNotesActivity(payload) let leadDetails: any if (closeUser?.closeAgentUID) { let leadPayload: any = {} if (payments.promoUsed) { leadPayload["custom.Payment Method"] = "Promo Code" } else { leadPayload["custom.Payment Method"] = "Credit Card" } leadPayload["custom.Lead Owner"] = closeUser.closeAgentUID leadPayload["custom.CC Charged"] = payments.amountPaid leadDetails = await this.closeIntegration.updateLead(leadObj?.closeUID, leadPayload) await this.leadsRepository.updateAll({consultantUID: closeUser.UID}, {UID: payments.leadUID}); leadDetails.consultant = closeUser if (opportunity) { this.closeIntegration.updateOpportunity({"user_id": closeUser.closeAgentUID, id: opportunity.closeOpportunityID}) } } const user = await this.userRepository.findOne({where: {UID: this.currentUser.UID}},) if (user) { sendPaidSuccessEmail(user) } leadDetails = {...leadDetails, ...leadObj} return leadDetails } else { return {} } } public async agentRoundRobin() { let agentDetail: (User & UserRelations) | null if (process.env.NODE_ENV === "production") { // round robin agentDetail = await this.getAgent() } else { // static agent assign const paulID = "user_A08s242iNA9m1EgLM9EEtNbcwKCbDf2mjSyxJ97L01J" agentDetail = await this.userRepository.findOne({where: {closeAgentUID: paulID}}) if (!agentDetail) { await this.authController.loadCloseUser() agentDetail = await this.userRepository.findOne({where: {closeAgentUID: paulID}}) } } if (!agentDetail) { await this.userRepository.updateAll({leadAssigned: false}, {leadAssigned: true}); agentDetail = await this.getAgent() } await this.userRepository.updateAll({leadAssigned: true}, {UID: agentDetail?.UID}); return agentDetail } private async getAgent() { // let amendaCloseID = 'user_vmKQROMKpgVwHbfz29gbpsP2KU0umdNOsljLrzYyMYe' // let jeffCloseID = 'user_O3nxdUPKOlzEdjdTLf8L93DqpGdKGyCGwhnCTa3lgGT' // let yogiCloseID = "user_PXm2K7Whj5vnCsOicUoFvUVjO0uGKySoyxQRhL4YPLv" let removeFromRoundRobin = ['user_vmKQROMKpgVwHbfz29gbpsP2KU0umdNOsljLrzYyMYe', 'user_O3nxdUPKOlzEdjdTLf8L93DqpGdKGyCGwhnCTa3lgGT', "user_PXm2K7Whj5vnCsOicUoFvUVjO0uGKySoyxQRhL4YPLv"] const agentDetail = await this.userRepository.findOne({ order: ["createdAt ASC"], where: { and: [ {closeAgentUID: {nin: removeFromRoundRobin}}, {leadAssigned: false}] }, }) return agentDetail } public async registerAgent(closeUser: any) { const userData = { closeAgentUID: closeUser.UID, email: closeUser.email, name: closeUser.first_name + " " + closeUser.last_name, image: closeUser.image || "" } const {userDetails}: any = await this.authController.registerUser(userData, roles.consultant) return userDetails } async getUserDetails(UID: string): Promise<User | null> { const foundUser: (User & UserRelations) | null = await this.userRepository.findOne({where: {UID}, include: ["role"]}); return foundUser } private failureHandler(res: Response, code: number, error: any): Promise<Response> { let className = error.className || PaymentsController.name return failureHandler(res, code, error, className) } } |