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

/**
 * end-user controller
 */

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

module.exports = createCoreController("api::end-user.end-user", () => ({
  async create(ctx) {
    // console.log("ctx", ctx.request.body);
    // Get user from user entity
    const currentUser = await strapi
      .query("plugin::users-permissions.user")
      .findOne({
        populate: ["user"],
        where: {
          $and: [{ email: ctx.request.body.data.email }],
        },
      });
    //   Check if its already existing in vendor entity
    console.log("currentUser", currentUser);
    console.log(
      "phoneNumber",
      ctx.request.body.data.mobileNo,
      ctx.request.body.data.email
    );
    let existingUser;
    existingUser = await strapi.entityService.findMany("api::end-user.end-user", {
      // fields: ["id"],
      filters: { phone: { $eq: ctx.request.body.data.mobileNo } },
    });
    console.log("existingUser> 1", existingUser);

    if (!existingUser) {
      existingUser = await strapi.entityService.findMany("api::end-user.end-user", {
        // fields: ["id"],
        filters: { email: { $eq: ctx.request.body.data.email } },
      });
    }
    console.log("existingUser > 2", existingUser);

    // Generate one time password (otp)
    const oneTimePassword = Math.floor(1000 + Math.random() * 9000);

    await strapi.entityService.update(
      "plugin::users-permissions.user",
      currentUser.id,
      {
        data: {
          oneTimePassword: `${oneTimePassword}`,
        },
      }
    );
    const date = new Date();
    // TODO: Code to send OTP on email
    // TODO: Code to send OTP on SMS

    console.log("ctx.request.body.data", ctx.request.body.data);
    console.log("existingUser", existingUser);
    if (existingUser && existingUser.length !== 0) {
    } else {
      ctx.request.body.data.user = currentUser.id;
      const response = await strapi.entityService.create("api::end-user.end-user", {
        data: {
          ...ctx.request.body.data,
          phone: ctx.request.body.data.mobileNo,
          publishedAt: date,
        },
      });
      console.log("response", response);
      return { otpSent: true, data: response };

      //   ctx.request.body.data.user = currentUser;
      //   console.log("ctx.request.body.data", ctx.request.body.data);
      //   return await super.create(ctx);
    }

    ctx.send({
      ok: true,
      message: "Existing vendor found, skipping creation only sent OTP.",
    });
  },

}));