userActions.js 11.4 KB
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
import {
  LOAD_USER_REQUEST,
  LOAD_USER_SUCCESS,
  LOAD_USER_FAIL,
  FORGOT_PASSWORD_REQUEST,
  FORGOT_PASSWORD_SUCCESS,
  FORGOT_PASSWORD_FAIL,
  RESET_PASSWORD_REQUEST,
  RESET_PASSWORD_SUCCESS,
  RESET_PASSWORD_FAIL,
  UPDATE_USER_PROFILE_REQUEST,
  UPDATE_USER_PROFILE_SUCCESS,
  UPDATE_USER_PROFILE_FAIL,
  REGISTER_USER_REQUEST,
  REGISTER_USER_SUCCESS,
  REGISTER_USER_FAIL,
  CLEAR_ERRORS,
  GET_END_USER_REQUEST,
  GET_END_USER_SUCCESS,
  GET_END_USER_FAIL
} from "../constants/userConstants";
import axios from "axios";
import { getSession } from "next-auth/react";
import qs from "qs";

// register a new user.
export const registerUser = userData => async dispatch => {
  try {
    dispatch({
      type: REGISTER_USER_REQUEST
    });

    // 1. # # # # # # # # # # # # #
    // First save the main user record.
    const config = {
      headers: {
        "Content-Type": "multipart/form-data"
      }
    };

    const userFormData = new FormData();
    userFormData.append("username", `${userData.mobile}-${userData.email}`);
    userFormData.append("email", userData.email);
    userFormData.append("password", userData.password);
    userFormData.append("role", userData.role);
    userFormData.append("phone", userData.mobile);
    // userFormData.append("approved", "pending");
    console.log("userFormData", userFormData);
    const response = await axios.post(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/auth/local/register`, userFormData, config);

    console.log(`Register user done:`);
    console.log(response);

    if (response?.data?.status == "fail") {
      return response;
    }
    // Immediately after user creation based on the role of the user we need to create entry into the corresponding extension table.

    // Do for End user
    if (userData.role === "endUser") {
      console.log("userdata", userData);
      // userData["userId"] = response.data.user.id;
      await registerEndUser({ ...userData, userId: response.data.user.id });
    }
    if (userData.role === "vendor") {
      console.log("userdata", userData);
      // userData["userId"] = response.data.user.id;
      await registerVendor({ ...userData, userId: response.data.user.id });
    }

    // console.log(`About to dispatch REGISTER_USER_SUCCESS`);
    dispatch({
      type: REGISTER_USER_SUCCESS
    });
  } catch (error) {
    console.log("Error while registering a user: ");
    console.log(error);

    dispatch({
      type: REGISTER_USER_FAIL,
      payload: error.response.data
    });
  }
};

const registerVendor = async vendorData => {
  const authUser = await axios.post(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/auth/local`, {
    identifier: vendorData.email,
    password: vendorData.password
  });
  console.log("jwt", authUser);
  const config = {
    headers: {
      Authorization: `Bearer ${authUser.data.jwt}`,
      "Content-Type": "application/json"
    }
  };

  const data = {
    data: {
      mobileNo: vendorData.mobile,
      name: vendorData.fullname,
      email: vendorData.email,
      user: authUser.data.user.id
    }
  };

  const response = await axios.post(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/vendors`, data, config);
  return response;
};

const registerEndUser = async vendorData => {
  const authUser = await axios.post(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/auth/local`, {
    identifier: vendorData.email,
    password: vendorData.password
  });
  console.log("jwt", authUser);
  const config = {
    headers: {
      Authorization: `Bearer ${authUser.data.jwt}`,
      "Content-Type": "application/json"
    }
  };

  const data = {
    data: {
      mobileNo: vendorData.mobile,
      name: vendorData.fullname,
      email: vendorData.email,
      user: authUser.data.user.id
    }
  };

  const response = await axios.post(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/end-users`, data, config);
  return response;
};

// register a new user.
export const loadUser = () => async dispatch => {
  const session = await getSession();
  if (session) {
    console.log("session", session);
    try {
      dispatch({
        type: LOAD_USER_REQUEST
      });

      const config = {
        headers: {
          Authorization: `Bearer ${session.jwt}`
        }
      };

      // Load the user.
      const response = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/users/me?populate[0]=profileImage&populate[1]=role`, config);
      console.log("response session", response);
      dispatch({
        type: LOAD_USER_SUCCESS,
        payload: { ...response.data }
      });
    } catch (error) {
      console.log("Error while loading a user: ");
      console.log(error);

      dispatch({
        type: LOAD_USER_FAIL,
        payload: error.response.data
      });
    }
  }
};

// update profile.
export const updateUserProfile = userData => async dispatch => {
  const session = await getSession();
  if (!session) {
    throw new Error("You are not authenticated currently. Only authenticated users can update their own profile.");
  }

  try {
    dispatch({
      type: UPDATE_USER_PROFILE_REQUEST
    });

    const config = {
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${session.jwt}`
      }
    };

    const response = await axios.put(
      `${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/users-permissions/users/me`,
      {
        password: userData.password,
        fullName: userData.fullName,
        aboutMe: userData.aboutMe
      },
      config
    );

    const profileImageFormData = new FormData();
    profileImageFormData.append("field", "profileImage");
    profileImageFormData.append("ref", "plugin::users-permissions.user");
    profileImageFormData.append("refId", response.data.id);
    profileImageFormData.append("files", userData.avatarFiles[0]);
    const profileImageUploadResponse = await axios.post(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/upload`, profileImageFormData, {
      headers: {
        Authorization: `Bearer ${session.jwt}`
      }
    });
    // console.log("Profile image update response:");
    // console.log(profileImageUploadResponse);

    dispatch({
      type: UPDATE_USER_PROFILE_SUCCESS,
      payload: response.data
    });
  } catch (error) {
    console.log("Error while updating a user profile: ");
    console.log(error);

    dispatch({
      type: UPDATE_USER_PROFILE_FAIL,
      payload: error.response.data
    });
  }
};

// forgot password.
export const forgotPassword = email => async dispatch => {
  try {
    dispatch({
      type: FORGOT_PASSWORD_REQUEST
    });

    const config = {
      headers: {
        "Content-Type": "application/json"
      }
    };

    const response = await axios.post(
      `${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/auth/forgot-password`,
      {
        email
      },
      config
    );

    dispatch({
      type: FORGOT_PASSWORD_SUCCESS,
      payload: response.data.ok ? "Please check your inbox for instructions to reset your password." : "Error generating reset password link"
    });
  } catch (error) {
    console.log("Error while generating password reset link: ");
    console.log(error);

    dispatch({
      type: FORGOT_PASSWORD_FAIL,
      payload: error.response.data
    });
  }
};

// reset password.
export const resetPassword = (code, password, passwordConfirmation) => async dispatch => {
  try {
    dispatch({
      type: RESET_PASSWORD_REQUEST
    });

    const config = {
      headers: {
        "Content-Type": "application/json"
      }
    };

    const response = await axios.post(
      `${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/auth/reset-password`,
      {
        code,
        password,
        passwordConfirmation
      },
      config
    );

    const { user, jwt } = response.data;

    dispatch({
      type: RESET_PASSWORD_SUCCESS,
      payload: jwt ? "Password reset successfully." : "Error while resetting password."
    });
  } catch (error) {
    console.log("Error while resetting password: ");
    console.log(error);

    dispatch({
      type: RESET_PASSWORD_FAIL,
      payload: error.response.data
    });
  }
};

// Clear errors
export const clearErrors = () => async dispatch => {
  dispatch({
    type: CLEAR_ERRORS
  });
};

/** End user record to be created alongwith user creation. */
/** This is an internal utility method which creates a end user when a user is created. */
export const finishEndUserOtpVerification = async verificationData => {
  // First save the main cp record.
  const config = {
    headers: {
      "Content-Type": "application/json"
    }
  };

  return await axios.post(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/end-users/finish-otp-verification`, verificationData, config);
};

export const updateUserApprovalStatus = async ({ status }) => {
  const session = await getSession();
  if (!session) {
    console.log("You are not authorized, please login");
  }
  const config = {
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${session.jwt}`
    }
  };

  const response = await axios.put(
    `${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/users/${session.id}`,
    {
      approved: status
    },
    config
  );

  return response;
};

export const updateApprovalStatusAdmin = async ({ status, userId, rejectionReason }) => {
  const session = await getSession();
  if (!session) {
    console.log("You are not authorized, please login");
  }
  const config = {
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${session.jwt}`
    }
  };
  if (!status == "rejected") {
    rejectionReason = "";
  }
  const response = await axios.put(
    `${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/users/${userId}`,
    {
      approved: status,
      rejectionReason
    },
    config
  );

  return response;
};

export const updateActivityStatusAdmin = async ({ status, activityId, rejectionReason }) => {
  const session = await getSession();
  if (!session) {
    console.log("You are not authorized, please login");
  }
  const config = {
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${session.jwt}`
    }
  };
  if (status == "approved") {
    rejectionReason = "";
  }
  const response = await axios.put(
    `${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/experiences/${activityId}`,
    {
      data: {
        approved: status,
        rejectionReason
      }
    },
    config
  );

  return response;
};

export const getCurrentEndUser = () => async dispatch => {
  try {
    // console.log("here action");
    const session = await getSession();
    if (!session) {
      return;
    }
    // console.log("session action", session);
    dispatch({
      type: GET_END_USER_REQUEST
    });

    const config = {
      headers: {
        "Content-type": "application/json",
        Authorization: `Bearer ${session.jwt}`
      }
    };

    const query = {
      populate: ["user"],
      filter: {
        user: {
          id: {
            $eq: session.id
          }
        }
      }
    };

    const queryString = qs.stringify(query, {
      encodeValuesOnly: true
    });
    console.log("querystring", query);
    const response = await axios.get(`${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/end-users/?${queryString}`, config);
    console.log("response", response);
    dispatch({
      type: GET_END_USER_SUCCESS,
      payload: response.data.data[0]
    });
  } catch (error) {
    console.log("Error while fetching end user: ");
    console.log(error);

    dispatch({
      type: GET_END_USER_FAIL,
      payload: error.response.data
    });
  }
};