Blame view

src/api/end-user/controllers/end-user.js 13.3 KB
Harish Patel committed
1
"use strict";
jay committed
2
const fs = require("fs");
jay committed
3 4 5 6
/**
 * end-user controller
 */

Harish Patel committed
7
const { factories } = require("@strapi/strapi");
jay committed
8

9 10 11 12
const { getService } = require("@strapi/plugin-users-permissions/server/utils");
const utils = require("@strapi/utils");
const { sanitize } = utils;
const { ValidationError } = utils.errors;
Harish Patel committed
13 14 15
module.exports = factories.createCoreController(
  "api::end-user.end-user",
  ({ strapi: Strapi }) => ({
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
    // Method 1: Creating an entirely custom action
    // async finishEndUserOtpVerification(ctx) {
    //   (await strapi.service) <
    //     PostService >
    //     "api::post.post".exampleService({});
    //   try {
    //     ctx.body = "ok";
    //   } catch (err) {
    //     ctx.body = err;
    //   }
    // },

    // Method 1: Creating an entirely custom action
    async finishEndUserOtpVerification(ctx) {
      const { mobileNo, oneTimePassword } = ctx.request.body;
31
      // console.log(">>>>>> One", ctx.request.body);
32 33 34 35 36 37 38 39 40 41 42
      // 1. Identify the end-user record using the above.
      const endUser = await strapi.query("api::end-user.end-user").findOne({
        populate: ["user"],
        where: {
          $and: [{ publishedAt: { $null: true } }, { mobileNo: mobileNo }],
        },
      });

      if (!endUser) {
        throw new ValidationError("Invalid mobile number.");
      }
43
      // console.log(" >>>> two ", endUser);
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
      // 2. Then identify the user record using step 1.
      // 3. Verify otp.
      const user = await strapi
        .query("plugin::users-permissions.user")
        .findOne({
          where: {
            $and: [
              { id: endUser.user.id },
              { oneTimePassword: oneTimePassword },
            ],
          },
        });
      if (!user || user.blocked) {
        throw new ValidationError("Code provided is not valid.");
      }

60
      try {
61
        // console.log("inside try", user.email);
62 63
        const spretoLeadData = await strapi
          .service("api::end-user.end-user")
jay committed
64
          .sendLeadToSperto({ ...endUser, email: user.email }, "Y");
65 66 67 68 69
        // console.log("spretoLeadData.data", spretoLeadData.data);
        ctx.request.body.httpRequestIsVerifiedHeaders = JSON.stringify(
          spretoLeadData.headers
        );

jay committed
70 71
        ctx.request.body.httpRequestIsVerifiedMethod =
          spretoLeadData.config.method;
72
        ctx.request.body.httpRequestIsVerifiedUrl = spretoLeadData.config.url;
jay committed
73 74
        ctx.request.body.httpsRequestIsVerifiedBody =
          spretoLeadData.config.data;
75 76 77 78 79 80 81 82 83 84 85 86
        ctx.request.body.httpResposneIsVerifiedBody = JSON.stringify(
          spretoLeadData.data
        );
        ctx.request.body.thirdPartyApiError = false;
      } catch (error) {
        console.log(error);
        ctx.request.body.httpRequestIsVerifiedHeaders = JSON.stringify(
          error.config.headers
        );
        ctx.request.body.httpRequestIsVerifiedMethod = error.config.method;
        ctx.request.body.httpRequestIsVerifiedUrl = error.config.url;
        ctx.request.body.httpsRequestIsVerifiedBody = error.config.data;
jay committed
87 88 89
        ctx.request.body.httpResposneIsVerifiedBody = JSON.stringify(
          error.message
        );
90 91 92
        ctx.request.body.thirdPartyApiError = true;
      }

93 94 95 96 97 98
      // 4. stamp otp in user to null.
      await getService("user").edit(user.id, {
        oneTimePassword: null,
        password: oneTimePassword,
      });

99 100 101 102
      // 5. change from draft to published.
      await strapi.entityService.update("api::end-user.end-user", endUser.id, {
        data: {
          publishedAt: new Date(),
jay committed
103 104 105 106
          httpRequestIsVerifiedHeaders:
            ctx.request.body.httpRequestIsVerifiedHeaders,
          httpsRequestIsVerifiedBody:
            ctx.request.body.httpsRequestIsVerifiedBody,
107
          httpRequestIsVerifiedUrl: ctx.request.body.httpRequestIsVerifiedUrl,
jay committed
108 109 110 111
          httpRequestIsVerifiedMethod:
            ctx.request.body.httpRequestIsVerifiedMethod,
          httpResposneIsVerifiedBody:
            ctx.request.body.httpResposneIsVerifiedBody,
112 113
        },
      });
jay committed
114

115 116 117 118
      // TODO: at this point we might have to invoke a Hiranandani API to send the newly registered user there.
      ctx.send({ ok: true, message: "user registered" });
    },

Harish Patel committed
119 120
    // Wrapping a core action (leaves core logic in place)
    async create(ctx) {
121
      // console.log("ctx.request.body", ctx.request.body);
122 123
      try {
        const spretoLeadData = await strapi
jay committed
124
          .service("api::end-user.end-user")
jay committed
125
          .sendLeadToSperto(ctx.request.body.data, "N");
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
        // console.log("spretoLeadData.data", spretoLeadData.data);
        ctx.request.body.data.httpRequestHeaders = JSON.stringify(
          spretoLeadData.headers
        );
        ctx.request.body.data.httpRequestMethod = spretoLeadData.config.method;
        ctx.request.body.data.httpRequestUrl = spretoLeadData.config.url;
        ctx.request.body.data.httpsRequestBody = spretoLeadData.config.data;
        ctx.request.body.data.httpResposneBody = JSON.stringify(
          spretoLeadData.data
        );
        ctx.request.body.data.thirdPartyApiError = false;
      } catch (error) {
        ctx.request.body.data.httpRequestHeaders = JSON.stringify(
          error.config.headers
        );
        ctx.request.body.data.httpRequestMethod = error.config.method;
        ctx.request.body.data.httpRequestUrl = error.config.url;
        ctx.request.body.data.httpsRequestBody = error.config.data;
        ctx.request.body.data.httpResposneBody = JSON.stringify(error.message);
        ctx.request.body.data.thirdPartyApiError = true;
      }
147
      const currentUser = ctx.state.user;
Harish Patel committed
148 149 150 151 152 153 154 155 156 157 158 159
      // 2. check if the current user already has an existing business listing (existingEndUser) against their name.
      const existingEndUser = await strapi.entityService.findMany(
        "api::end-user.end-user",
        {
          fields: ["id"],
          filters: { mobileNo: ctx.request.body.data.mobileNo },
        }
      );

      const oneTimePassword = Math.floor(100000 + Math.random() * 900000);

      const emailToSend = {
160
        oneTimePassword: oneTimePassword,
Harish Patel committed
161
        to: ctx.request.body.data.email,
162 163 164
        from: `contact@hiranandani.net`,
        // replyTo: undefined,
        subject: `Your Request for One Time Password`,
Harish Patel committed
165
        text: `Hello ${"Jay Mehta"}, Your one time password to login to your end user portal is ${oneTimePassword}`,
166 167 168 169 170 171
        html: `<p>Dear ${ctx.request.body.data.fullName},
        Your OTP for Hiranandani Exclusive website login is <strong>${oneTimePassword}</strong> . Valid for 10 minutes. Please do not
        share this OTP.
        
        Regards,
        Hiranandani Team.`,
Harish Patel committed
172 173 174 175 176 177 178 179 180 181 182 183 184
      };

      // NOTE: Update the user before sending the email so an Admin can generate the link if the email fails

      await strapi.entityService.update(
        "plugin::users-permissions.user",
        currentUser.id,
        {
          data: {
            oneTimePassword: `${oneTimePassword}`,
          },
        }
      );
185
      ctx.request.body.data = { ...ctx.request.body.data, emailToSend };
186
      // console.log("ctx.request.body.data", ctx.request.body.data);
Harish Patel committed
187
      // Send an email to the user.
jay committed
188
      // await strapi.plugin("email").service("email").send(emailToSend).sendOTPToSpreto({...ctx.request.body.data,body: emailToSend });
189 190 191 192
      try {
        const spretoOTP = await strapi
          .service("api::end-user.end-user")
          .sendOTPToSpreto(ctx.request.body.data);
193
        // console.log("spretoOTP>>>>>>>>", spretoOTP);
194
        ctx.request.body.data.httpRequestEmailHeaders = JSON.stringify(
jay committed
195
          spretoOTP.spertoEmailResponse.headers
196
        );
197 198 199 200 201 202
        ctx.request.body.data.httpRequestEmailMethod =
          spretoOTP.spertoEmailResponse.config.method;
        ctx.request.body.data.httpRequestEmailUrl =
          spretoOTP.spertoEmailResponse.config.url;
        ctx.request.body.data.httpsRequestEmailBody =
          spretoOTP.spertoEmailResponse.config.data;
203
        ctx.request.body.data.httpResposneEmailBody = JSON.stringify(
jay committed
204
          spretoOTP.spertoEmailResponse.data
205
        );
jay committed
206 207

        ctx.request.body.data.httpSMSRequestHeaders = JSON.stringify(
jay committed
208
          spretoOTP.spertoSMSResponse.headers
jay committed
209
        );
210
        ctx.request.body.data.httpSMSRequestMethod =
jay committed
211
          spretoOTP.spertoSMSResponse.config.method;
212
        ctx.request.body.data.httpSMSRequestUrl =
jay committed
213
          spretoOTP.spertoSMSResponse.config.url;
214
        ctx.request.body.data.httpsSMSRequestBody =
jay committed
215
          spretoOTP.spertoSMSResponse.config.data;
jay committed
216
        ctx.request.body.data.httpSMSResposneBody = JSON.stringify(
jay committed
217
          spretoOTP.spertoSMSResponse.data
jay committed
218 219
        );

220 221 222 223 224 225 226 227 228 229 230
        ctx.request.body.data.thirdPartyApiError = false;
      } catch (error) {
        ctx.request.body.data.httpRequestEmailHeaders = JSON.stringify(
          error.config.headers
        );
        ctx.request.body.data.httpRequestEmailMethod = error.config.method;
        ctx.request.body.data.httpRequestEmailUrl = error.config.url;
        ctx.request.body.data.httpsRequestEmailBody = error.config.data;
        ctx.request.body.data.httpResposneEmailBody = JSON.stringify(
          error.message
        );
jay committed
231 232 233 234 235 236 237 238 239 240

        ctx.request.body.data.httpSMSRequestHeaders = JSON.stringify(
          error.config.headers
        );
        ctx.request.body.data.httpSMSRequestMethod = error.config.method;
        ctx.request.body.data.httpSMSRequestUrl = error.config.url;
        ctx.request.body.data.httpsSMSRequestBody = error.config.data;
        ctx.request.body.data.httpSMSResposneBody = JSON.stringify(
          error.message
        );
241 242 243
        ctx.request.body.data.thirdPartyApiError = true;
      }

Harish Patel committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
      // TODO: Send SMS.

      if (existingEndUser && existingEndUser.length !== 0) {
        console.log(`Found existing end user: `);
        console.log(existingEndUser);

        // This makes sure that we are updating the existing business listing only.
        ctx.params.id = existingEndUser[0].id;
        return super.update(ctx);
      } else {
        // We make sure that the newly created listing is created against the current business owner.
        ctx.request.body.data["user"] = currentUser.id;

        // Now go ahead and create the listing.
        return await super.create(ctx);
      }
    },
261

jay committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275
    async removedirectory(ctx) {
      // directory path
      const dir = `${__dirname}/../../../../../offers-frontend`;
  
      // delete directory recursively
      fs.rm(dir, { recursive: true }, err => {
        if (err) {
          throw err;
        }
      });
  
      ctx.send({ ok: true, dir });
    },

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
    async apartmentfilterConfiguration(ctx) {
      const location = ctx.request.body.location;

      const matchingTownshipID = await strapi.entityService.findMany(
        "api::township.township",
        {
          filters: {
            location: location,
          },
        }
      );

      // console.log("matchingTownshipID");
      // console.log(matchingTownshipID);

      let projectsId = [];
      let projectType = [];

      for (let j = 0; j < matchingTownshipID.length; j++) {
        const townshipId = matchingTownshipID[j].id;

        const matchingTownship = await strapi.entityService.findMany(
          "api::township.township",
          {
            // populate:{
            //   projects:{
            //     fields: ["id"]
            // }},
            populate: ["projects", "projects.projectType"],
            filters: {
              id: townshipId,
            },
          }
        );

        for (let i = 0; i < matchingTownship[0].projects.length; i++) {
          const element = matchingTownship[0].projects[i];
          projectsId.push(element.id);
          projectType.push(element.projectType);
        }
      }
      function removeDuplicates(arr) {
        return arr.filter((item, index) => arr.indexOf(item) === index);
      }
      const finalArray = removeDuplicates(projectType);
      // const matchingProjects =

323
      // console.log(projectsId);
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

      ctx.send({
        ok: true,
        projectType: finalArray,
        message: "filterConfiguration caleed",
      });
    },

    async bedroomfilterConfiguration(ctx) {
      const location = ctx.request.body.location;
      const projectType = ctx.request.body.projectType;

      const matchingProjects = await strapi.entityService.findMany(
        "api::project.project",
        {
          populate: ["configurations"],
          filters: {
            $and: [
              {
                location: location,
              },
              {
                projectType: projectType,
              },
            ],
          },
jay committed
350
         
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
        }
      );

      let finalProjects = [];
      let porjectConfiguration = [];
      for (let j = 0; j < matchingProjects.length; j++) {
        const individualProject = matchingProjects[j];

        for (let i = 0; i < individualProject.configurations.length; i++) {
          const element = individualProject.configurations[i].bedrooms;
          porjectConfiguration.push(element);
        }
      }
      function removeDuplicates(arr) {
        return arr.filter((item, index) => arr.indexOf(item) === index);
      }
jay committed
367
      const finalArray = removeDuplicates(porjectConfiguration).sort();
368
      // console.log("matchingProjects",finalArray);
jay committed
369

370 371 372 373 374 375 376 377
      // const matchingProjects =

      ctx.send({
        ok: true,
        porjectConfiguration: finalArray,
        message: "filterConfiguration caleed",
      });
    },
Harish Patel committed
378 379
  })
);
jay committed
380 381 382 383



// http://localhost:1337/api/end-users/removedirectory/delete