end-user.js 3.24 KB
"use strict";

/**
 * end-user controller
 */

const { factories } = require("@strapi/strapi");

module.exports = factories.createCoreController(
  "api::end-user.end-user",
  ({ strapi: Strapi }) => ({
    // Wrapping a core action (leaves core logic in place)
    async create(ctx) {
      console.log(ctx.request.body);
      const currentUser = ctx.state.user;

      // Find the linked user next.
      //   const existingUser = await strapi
      //     .query("plugin::users-permissions.user")
      //     .findOne({ username: ctx.request.body.data.mobileNo });

    //   const existingUserEntries = await strapi.entityService.findMany(
    //     "plugin::users-permissions.user",
    //     {
    //       // fields: ['title', 'description'],
    //       filters: { username: ctx.request.body.data.mobileNo },
    //     }
    //   );
    //   console.log(`Inside end-user create, found existingUserEntries: `);
    //   console.log(existingUserEntries);

    //   if (!existingUserEntries || existingUserEntries.length === 0) {
    //     throw new ValidationError(
    //       `Unable to resolve existing user with mobileNo: ${ctx.request.body.data.mobileNo}.`
    //     );
    //   }

    //   const existingUser = existingUserEntries[0];

      // 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 = {
        to: ctx.request.body.data.email,
        from: undefined,
        replyTo: undefined,
        subject: `Your one time password is: ${oneTimePassword}`,
        text: `Hello ${"Jay Mehta"}, Your one time password to login to your partner portal is ${oneTimePassword}`,
        html: `<p>Hello ${"Jay Mehta"}, <br></br>Your one time password to login to your partner portal is ${oneTimePassword}</p><br /> Best Regards, <br /> Team Hiranandani.`,
      };

      // 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}`,
          },
        }
      );

      // Send an email to the user.
      await strapi.plugin("email").service("email").send(emailToSend);

      // 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;

        console.log(`About to insert end user: `);
        console.log(ctx.request.body.data);

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