Blame view

redux/actions/userActions.js 11.4 KB
jay committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
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,
jaymehta committed
17 18 19 20
  CLEAR_ERRORS,
  GET_END_USER_REQUEST,
  GET_END_USER_SUCCESS,
  GET_END_USER_FAIL
jay committed
21 22 23
} from "../constants/userConstants";
import axios from "axios";
import { getSession } from "next-auth/react";
jaymehta committed
24
import qs from "qs";
jay committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

// 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();
jay committed
42
    userFormData.append("username", `${userData.mobile}-${userData.email}`);
jay committed
43 44 45
    userFormData.append("email", userData.email);
    userFormData.append("password", userData.password);
    userFormData.append("role", userData.role);
jay committed
46
    userFormData.append("phone", userData.mobile);
jaymehta committed
47
    // userFormData.append("approved", "pending");
jay committed
48
    console.log("userFormData", userFormData);
jay committed
49 50 51 52 53
    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);

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

    // Do for End user
jaymehta committed
60 61 62 63
    if (userData.role === "endUser") {
      console.log("userdata", userData);
      // userData["userId"] = response.data.user.id;
      await registerEndUser({ ...userData, userId: response.data.user.id });
jay committed
64
    }
jay committed
65 66 67 68
    if (userData.role === "vendor") {
      console.log("userdata", userData);
      // userData["userId"] = response.data.user.id;
      await registerVendor({ ...userData, userId: response.data.user.id });
jay committed
69 70
    }

jay committed
71
    // console.log(`About to dispatch REGISTER_USER_SUCCESS`);
jay committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85
    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
    });
  }
};

jay committed
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
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;
};

jaymehta committed
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
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;
};

jay committed
138 139 140 141
// register a new user.
export const loadUser = () => async dispatch => {
  const session = await getSession();
  if (session) {
jaymehta committed
142
    console.log("session", session);
jay committed
143 144 145 146 147 148 149 150 151 152 153 154
    try {
      dispatch({
        type: LOAD_USER_REQUEST
      });

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

      // Load the user.
jaymehta committed
155 156
      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);
jay committed
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
      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);
};
jaymehta committed
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

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;
};
jaymehta committed
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

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}`
    }
  };
.  
jaymehta committed
386
  if (status == "approved") {
jaymehta committed
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    rejectionReason = "";
  }
  const response = await axios.put(
    `${process.env.NEXT_PUBLIC_BACKEND_API_URL}/api/experiences/${activityId}`,
    {
      data: {
        approved: status,
        rejectionReason
      }
    },
    config
  );

  return response;
};
jaymehta committed
402 403 404

export const getCurrentEndUser = () => async dispatch => {
  try {
jaymehta committed
405
    // console.log("here action");
jaymehta committed
406
    const session = await getSession();
jaymehta committed
407 408 409
    if (!session) {
      return;
    }
410
    console.log("session action", session);
jaymehta committed
411 412 413 414 415 416 417 418 419 420 421 422 423
    dispatch({
      type: GET_END_USER_REQUEST
    });

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

    const query = {
      populate: ["user"],
424
      filters: {
jaymehta committed
425 426 427 428 429 430 431 432 433 434 435 436 437
        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);
438
    console.log("response enduser", response);
jaymehta committed
439 440 441 442 443 444 445 446 447 448 449 450 451 452
    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
    });
  }
};