All files / postcardotp-backend/src/services notificationPreferences.service.js

35.71% Statements 5/14
0% Branches 0/2
0% Functions 0/4
38.46% Lines 5/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 541x     1x             1x                                         1x                                 1x          
const { models } = require("../config/sequelize");
 
// Get all preferences for a user
const getAllPreferencesByUserId = async (userId) => {
  return await models.NotificationPreference.findAll({
    where: { user_id: userId },
  });
};
 
// Update preference by user and category
const updatePreferenceByCategory = async (userId, category, data) => {
  const [updated] = await models.NotificationPreference.update(
    {
      email_enabled: data.email_enabled,
      sms_enabled: data.sms_enabled,
    },
    {
      where: { user_id: userId, category },
    },
  );
 
  if (!updated) {
    throw new Error("Preference not found");
  }
 
  return await models.NotificationPreference.findOne({
    where: { user_id: userId, category },
  });
};
 
// Create default preferences (used during user creation)
const createDefaultPreferences = async (userId) => {
  const categories = [
    "Campaign Updates",
    "Account Activity",
    "Billing and Payments",
    "Marketing and Tips",
  ];
 
  const preferences = categories.map((category) => ({
    user_id: userId,
    category,
    email_enabled: true,
    sms_enabled: false,
  }));
  return await models.NotificationPreference.bulkCreate(preferences);
};
 
module.exports = {
  getAllPreferencesByUserId,
  updatePreferenceByCategory,
  createDefaultPreferences,
};