File: /var/www/javago-api-updates/src/services/auth/auth.services.js
import NotificationListDB from "../../models/notification_list.model.js";
import GroupCoffeeRunDB from "../../models/group_coffee_run.model.js";
import ResetPasswordDB from "../../models/resetpassword.model.js";
import { createPresignedPost } from "@aws-sdk/s3-presigned-post";
import appVersionDB from "../../models/app_versions.model.js";
import UserDB from "../../models/users.model.js";
import CafeDB from "../../models/cafes.model.js";
import notification from "../../helper/notification.js";
import { S3Client } from "@aws-sdk/client-s3";
import { Op } from "sequelize";
import CafeGoToOrders from "../../models/cafe_go_to_orders.model.js";
import inHouseOrder from "../../models/in_house_order.model.js";
import moment from "moment/moment.js";
import { messages } from "../../config/response.messages.js";
import User from "../../models/users.model.js";
import Order from "../../models/orders.model.js";
import NotificationList from "../../models/notification_list.model.js";
export async function findByEmail(userDetails) {
let userData = await UserDB.findOne({
attributes: [
"id",
"name",
"email",
"otp",
"profile_picture",
"address",
"notification_status",
"password",
"is_verified",
"is_active",
"is_deleted",
"type",
],
where: {
email: userDetails.email,
},
});
return userData;
}
export async function findById(userDetails) {
try {
let userData = await UserDB.findOne({
attributes: [
"id",
"name",
"email",
"otp",
"profile_picture",
"address",
"notification_status",
"password",
"is_verified",
"is_active",
"is_deleted",
"type",
"referral_code",
"referral_code_used",
"has_used_welcome_discount",
"remaining_awarded_stamps",
],
where: {
id: userDetails.user_id,
},
});
return userData;
} catch (error) {
console.log(error);
throw new Error(error);
}
}
export async function appVersionDetails(os_type) {
try {
let userData = await appVersionDB.findOne({
attributes: [
"id",
"force_update_status",
"os_type",
"version",
"normal_update_message",
"force_update_message",
],
where: {
os_type: os_type,
},
});
return userData;
} catch (error) {
console.log(error);
throw new Error(error);
}
}
export async function userList() {
try {
return await UserDB.findAll();
} catch (error) {
throw new Error(error);
}
}
export async function updateUser(userDetails, id) {
try {
return await UserDB.update(userDetails, {
where: {
id: id,
},
});
} catch (error) {
throw new Error(error);
}
}
export async function updateUserByEmail(userDetails, email) {
try {
return await UserDB.update(userDetails, {
where: {
email: email,
},
});
} catch (error) {
throw new Error(error);
}
}
export async function createUser(userDetails) {
try {
await UserDB.create(userDetails);
return true;
} catch (error) {
throw new Error(error);
}
}
export async function getUserEmail(data) {
try {
var result = await UserDB.findOne({
where: {
[Op.and]: [
{
email: data.email,
},
],
},
});
return result;
} catch (error) {
throw new Error(error);
}
}
export async function ForgotPasswordByEmail(email) {
let userData = await ResetPasswordDB.findOne({
where: {
email: email,
},
});
return userData;
}
export async function updateForgotPasswordByEmail(userDetails, email) {
try {
return await ResetPasswordDB.update(userDetails, {
where: {
email: email,
},
});
} catch (error) {
throw new Error(error);
}
}
export async function createForgotPassword(userDetails) {
try {
await ResetPasswordDB.create(userDetails);
return true;
} catch (error) {
throw new Error(error);
}
}
export async function getNotificationList(userDetails, query) {
try {
let getList = await NotificationListDB.paginate({
page: query.page,
paginate: 10,
order: [["id", "DESC"]],
include: [
{
model: UserDB,
as: "sender",
attributes: ["id", "name", "profile_picture"],
where: { is_deleted: 0, is_active: 1, is_verified: 1 },
required: false,
},
{
model: UserDB,
as: "reciever",
attributes: ["id"],
where: { is_deleted: 0, is_active: 1, is_verified: 1 },
include: [
{
model: inHouseOrder,
attributes: ["id"],
},
],
},
{
model: GroupCoffeeRunDB,
as: "group_coffee_run_data",
attributes: [
"cafe_id",
"group_id",
"request_endtime",
"request_unique_id",
"order_id",
"is_contributor_person",
"type",
"in_house_order_id",
],
required: false,
include: [
{
model: CafeDB,
required: false,
attributes: ["id"],
include: [
{
model: CafeGoToOrders,
required: false,
attributes: ["id"],
where: {
user_id: userDetails.user_id,
},
},
],
},
],
},
],
where: {
receiver_id: userDetails.user_id,
notification_type: { [Op.ne]: 1 },
},
});
for (let i = 0; i < getList.docs.length; i++) {
await NotificationListDB.update(
{ is_read: 1 },
{
where: {
id: getList.docs[i].id,
},
}
);
}
return getList;
} catch (error) {
throw new Error(error);
}
}
export async function getNotificationDetails(id) {
try {
let notification = {};
let getDetails = await NotificationList.findOne({
where: {
id: id,
},
});
if (getDetails) {
notification.id = getDetails.id;
notification.sender_id = getDetails.sender_id;
notification.receiver_id = getDetails.receiver_id;
notification.reference_id = getDetails.reference_id;
notification.notification_type = getDetails.notification_type;
notification.request_group_id = getDetails.request_group_id;
notification.is_read = getDetails.is_read;
notification.created_at = getDetails.created_at;
notification.updated_at = getDetails.updated_at;
if (getDetails.notification_type === 1) {
notification.title = "New Order Notification";
notification.description =
"You have received a new order. Please check your orders.";
} else if (getDetails.notification_type === 2) {
notification.title = "Group Coffee Run Notification";
notification.description =
"You have received a new group coffee run request. Please check your requests.";
} else if (getDetails.notification_type === 3) {
notification.title = "Order Collected Notification";
notification.description =
"Your order has been collected by the user. Please check your orders.";
} else if (getDetails.notification_type === 4) {
notification.title = "Order Cancelled Notification";
notification.description =
"Your order has been cancelled by the user. Please check your orders.";
} else if (getDetails.notification_type === 5) {
notification.title = "Order Completed Notification";
notification.description =
"Your order has been completed! Please collect it.";
} else if (getDetails.notification_type === 6) {
notification.title = "New Group Coffee Run Request";
notification.description =
"You have received a new group coffee run request. Please check your requests.";
} else if (getDetails.notification_type === 7) {
notification.title = "Coffee Run Request Notification";
notification.description =
"You have received a new coffee run request. Please check your requests.";
} else if (getDetails.notification_type === 8) {
notification.title = "Coffee Run Request Accepted Notification";
notification.description =
"Your coffee run request has been accepted. Please check your requests.";
} else if (getDetails.notification_type === 9) {
const getOrderDetail = await Order.findOne({
where: {
id: getDetails.reference_id,
},
attributes: ["id", "order_number", "group_coffee_run_id", "group_id"],
});
// Attach to notification object
return getOrderDetail;
} else if (getDetails.notification_type === 10) {
notification.title = "Order Ready Notification";
notification.description =
"Your order is Ready! Please collect it.";
// Fetch order detail
const getOrderDetail = await Order.findOne({
where: {
id: getDetails.reference_id,
},
attributes: ["id", "order_number", "group_coffee_run_id", "group_id"],
});
// Attach to notification object
return getOrderDetail;
} else if (getDetails.notification_type === 101) {
notification.title = "Order Complete Notification";
notification.description =
"Your order has been completed!";
// Fetch order detail
const getOrderDetail = await Order.findOne({
where: {
id: getDetails.reference_id,
},
attributes: ["id", "order_number", "group_coffee_run_id", "group_id"],
});
// Attach to notification object
return getOrderDetail;
} else {
notification.title = "";
notification.description = "";
}
}
// return notification;
} catch (error) {
console.error("Error in getNotificationDetails:", error);
throw error;
}
}
export async function getNotificationCount(user_id) {
try {
let count = await NotificationListDB.count({
where: {
receiver_id: user_id,
notification_type: { [Op.ne]: 1 },
is_read: 0,
},
});
return count;
} catch (error) {
throw new Error(error);
}
}
export async function updateCoffeeRunRequest(id, coffee_run_id) {
try {
const result = await NotificationListDB.update(
{ reference_id: coffee_run_id },
{
where: {
id: id,
},
}
);
return result[0];
} catch (error) {
throw new Error(error);
}
}
export async function createCoffeeRunRequest(data) {
try {
let check = await GroupCoffeeRunDB.findOne({
where: {
group_id: data.group_id,
request_endtime: {
[Op.gte]: moment().unix(),
},
},
});
if (check) {
throw new Error(messages.group_cafe_run_already_added);
} else {
var notificationData = data.users
.filter((e) => e != data.user.id)
.map((e) => {
return {
sender_id: data.user.id,
receiver_id: e,
notification_type: 7,
is_read: 0,
request_group_id: data.group_id,
created_at: moment().unix(),
updated_at: moment().unix(),
};
});
await NotificationListDB.bulkCreate(notificationData);
await notification.requestCoffeeRunNotification({
senderId: data.user.id,
userIds: data.users,
groupId: data.group_id,
});
}
} catch (error) {
throw new Error(error);
}
}
export async function removeNotification(id, data) {
try {
await NotificationListDB.destroy({
where: {
receiver_id: id.user_id,
id: parseInt(data.id),
},
});
return true;
} catch (error) {
throw new Error(error);
}
}
export async function removeAllNotification(user_id) {
try {
await NotificationListDB.destroy({
where: {
receiver_id: user_id,
},
});
return true;
} catch (error) {
throw new Error(error);
}
}
export async function s3BucketDetails(file_type) {
try {
let clientParams = {
region: process.env.AWS_SES_REGION,
credentials: {
accessKeyId: process.env.AWS_SES_ACCESS_KEYID,
secretAccessKey: process.env.AWS_SES_SECRET_ACCESS_KEY,
},
};
const prePath = "signed-url-demo/";
const Key = `${prePath}${
(Math.random() + 1).toString(36).substring(2) + file_type
}`;
let client = new S3Client(clientParams);
let res = createPresignedPost(client, {
Bucket: process.env.AWS_BUCKET_NAME,
Key,
Expires: 3600, //Seconds before the presigned post expires. 3600 by default.
});
return res;
} catch (error) {
throw new Error(error);
}
}
export async function updateReferralCode(userId) {
try {
const user = await UserDB.findOne({
where: { id: userId },
attributes: ["referral_code"],
});
if (user && user.referral_code) {
// Return the existing referral code
return user.referral_code;
}
let referralCode;
let isUnique = false;
while (!isUnique) {
referralCode = generateReferralCode();
const existingReferral = await UserDB.findOne({
where: {
referral_code: referralCode,
},
});
if (!existingReferral) {
isUnique = true;
}
}
// Update the user's referral code
const userReferral = await UserDB.update(
{ referral_code: referralCode },
{
where: {
id: userId,
},
}
);
return referralCode;
} catch (error) {
throw new Error(error);
}
}
function generateReferralCode(length = 6) {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let code = "";
for (let i = 0; i < length; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
return code;
}
export async function joinedByCode(data) {
try {
// Check if referral code exists
const referrer = await UserDB.findOne({
where: { referral_code: data.code },
});
if (!referrer) {
return {
status: 404,
message: "Referral code not found or is invalid!",
};
}
// Update the user's record with the used referral code
const [updatedRows] = await UserDB.update(
{ referral_code_used: data.code },
{ where: { id: data.userId } }
);
if (updatedRows === 0) {
return {
status: 404,
message: "User not found or update failed!",
};
}
return {
status: 200,
message: "Referral code used successfully.",
};
} catch (error) {
throw error;
}
}