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 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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | const { date } = require("joi");
const { models, sequelize } = require("../config/sequelize");
const { ApiError } = require("../utils/errorHandler");
const logger = require("../utils/logger");
const crypto = require("node:crypto");
/**
* Get all campaign (Service)
*/
exports.getCampaigns = async (userID, offset, limit) => {
// Check whether the limit and offset is valid
if (isNaN(limit) || limit < 0 || isNaN(offset) || offset < 0) {
return new ApiError("Invalid limit or offset values", 400);
}
// Get all campaign records using models.Campaign
const campaigns = await models.Campaign.findAndCountAll({
where: {
user_id: userID,
},
offset,
limit,
});
if (!campaigns) throw new ApiError("Sorry! No campaign found.", 404);
return campaigns;
};
/**
* Get one campaign by id (service)
*/
exports.getOneCampaign = async (userID, campaignID) => {
// Check if campaign id is provided
await checkCampaignExists(campaignID);
// Check campaign records belongs to user
await checkCampaignBelongsToUser(campaignID, userID);
// Get single campaign records using models.Campaign
const campaign = await models.Campaign.findOne({
where: {
id: campaignID,
user_id: userID,
},
});
if (!campaign) throw new ApiError("Sorry! Campaign not found.", 404);
return campaign;
};
/**
* Create a new campaign record (Service)
*/
exports.createCampaign = async (
userID,
name,
status,
brand_color,
postcard_front_img_path,
company_logo_path,
addresses,
) => {
if (brand_color === "") {
brand_color = "#9b87f5";
}
if (status === "") {
status = "Active";
}
addresses = await JSON.parse(addresses);
// logger.info(`addresses::${addresses}`);
const transaction = await sequelize.transaction();
try {
// 1. First Create the new campaign using models.Campaign
const campaignData = await models.Campaign.create(
{
user_id: userID,
name,
status,
brand_color,
postcard_front_img_url: postcard_front_img_path,
company_logo_url: company_logo_path,
},
{ transaction },
);
// 2. Then Create the new addressverification using models.Address
// Add campaign_id and user_id to each address
const addressesWithIds = addresses.map((address) => {
return {
...address,
user_id: userID,
campaign_id: campaignData.id,
};
});
// 3. Bulk create addresses
const addressesData = await models.Addresses.bulkCreate(addressesWithIds, {
transaction,
});
// 4. Map address_verifications with corresponding address IDs
const addressVerificationsWithIds = addresses.map((_, index) => ({
user_id: userID,
campaign_id: campaignData.id,
address_id: addressesData[index].id,
otp_code: generateOtp(),
expires_at: generateExpiryTime(),
}));
// 5. Bulk create address verifications
const addressVerificationData = await models.AddressVerification.bulkCreate(
addressVerificationsWithIds,
{ transaction },
);
await transaction.commit();
return { campaignData, addressesData, addressVerificationData };
} catch (error) {
await transaction.rollback();
throw error;
}
};
/**
* Update campaign record Service
*/
exports.updateCampaign = async (campaignID, userID, updatecampaignData) => {
const Allowed_fields = Object.freeze(["name", "status", "brand_color"]);
const filteredKeys = {};
for (const key of Allowed_fields) {
if (
updatecampaignData[key] !== undefined &&
updatecampaignData[key] !== ""
) {
filteredKeys[key] = updatecampaignData[key];
}
}
// Check campaign records exists
await checkCampaignExists(campaignID);
// Check campaign records belongs to user
await checkCampaignBelongsToUser(campaignID, userID);
// 1. First update the campaign using models.Campaign
const campaignData = await models.Campaign.update(
{
user_id: userID,
...filteredKeys,
campaign_end_at: filteredKeys.status === "Archived" ? Date.now() : null,
},
{
where: {
id: campaignID,
user_id: userID,
},
},
);
return { campaignData };
};
/**
* Delete campaign record Service
*/
exports.deleteCampaign = async (campaignID, userID) => {
// 1. First Check campaign records exists
await checkCampaignExists(campaignID);
// 2. Second check campaign records belongs to user
await checkCampaignBelongsToUser(campaignID, userID);
const transaction = await sequelize.transaction();
try {
// 3. Third delete all related records
await models.AddressVerification.destroy({
where: { campaign_id: campaignID },
transaction,
});
// 4. Then delete the campaign using models.Campaign
const result = await models.Campaign.destroy({
where: { id: campaignID, user_id: userID },
transaction,
});
await transaction.commit();
return result;
} catch (error) {
await transaction.rollback();
throw error;
}
};
async function checkCampaignExists(campaignID, transaction = false) {
try {
// Check if campaign exists
const campaignData = await models.Campaign.findOne({
where: {
id: campaignID,
},
...(transaction && { transaction }),
});
if (!campaignData)
throw new ApiError("Sorry! Campaign does not exists.", 404);
} catch (error) {
throw error;
}
}
async function checkCampaignBelongsToUser(
campaignID,
userID,
transaction = false,
) {
try {
// Check if campaign exists
const campaignData = await models.Campaign.findOne({
where: {
id: campaignID,
user_id: userID,
},
...(transaction && { transaction }),
});
if (!campaignData)
throw new ApiError("Sorry! Campaign does not belongs to this user.", 404);
} catch (error) {
throw error;
}
}
function generateOtp() {
// Use math function if not using node
// return Math.floor(Math.random() * 90000) + 10000;
return crypto.randomInt(10000, 100000);
}
function generateExpiryTime() {
return new Date(Date.now() + 10 * 24 * 60 * 60 * 1000).toISOString();
}
|