Skip to content

Commit

Permalink
Ready for 0.3-dev
Browse files Browse the repository at this point in the history
  • Loading branch information
guillecro committed Dec 19, 2024
1 parent ac9738e commit 976bde1
Show file tree
Hide file tree
Showing 23 changed files with 900 additions and 10 deletions.
110 changes: 110 additions & 0 deletions controllers/challengeController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
const models = require('../models');
const msg = require('../utils/messages');

exports.create = async (req, res) => {
try {
const {
dimensionId,
subdivisionId,
needsAndChallenges,
proposal,
inWords
} = req.body;

// create a new Challenge entry
const blogEntry = await models.Challenge.create({
dimensionId,
subdivisionId,
needsAndChallenges,
proposal,
inWords
});

return res.status(201).json(blogEntry);
} catch (error) {
console.error(error);
return res.status(500).json({ message: msg.error.default });
}
}

exports.stats = async (req, res) => {
try {
const cityId = parseInt(req.query.cityId) || null;
// count how many challenges per dimension
const countChallengesPerDimension = await models.Challenge.count({
attributes: ['dimensionId'],
include: [
{
model: models.Subdivision,
as: 'subdivision',
where: cityId ? { cityId: cityId } : {}
}
],
group: ['dimensionId']
});

// count how many challenges per city
const countChallengesInCity = await models.Challenge.count({
attributes: ['subdivision.cityId'],
include: [
{
model: models.Subdivision,
as: 'subdivision',
where: cityId ? { cityId: cityId } : {}
}
],
group: ['subdivision.cityId'],
});

// {
// "countChallengesPerDimension": [
// {
// "dimensionId": 1,
// "count": 2
// },
// {
// "dimensionId": 4,
// "count": 2
// },
// {
// "dimensionId": 2,
// "count": 1
// },
// {
// "dimensionId": 3,
// "count": 1
// },
// {
// "dimensionId": 6,
// "count": 1
// },
// {
// "dimensionId": 5,
// "count": 1
// },
// {
// "dimensionId": 7,
// "count": 1
// }
// ],
// "countChallengesInCity": [
// {
// "cityId": 1,
// "count": 5
// },
// {
// "cityId": 2,
// "count": 4
// }
// ]
// }

return res.status(200).json({
countChallengesPerDimension,
countChallengesInCity
});
} catch (error) {
console.error(error);
return res.status(500).json({ message: msg.error.default });
}
}
69 changes: 69 additions & 0 deletions controllers/faqController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
const models = require('../models');

exports.getAll = async (req, res) => {
try {
const faqs = await models.Faq.findAll({
order: [['order', 'ASC']]
});
return res.status(200).json(faqs);
} catch (error) {
console.error(error);
return res.status(500).json({ message: 'An error occurred' });
}
}

exports.getOne = async (req, res) => {
try {
const id = req.params.id;
const faq = await models.Faq.findOne({ where: { id } });
return res.status(200).json(faq);
} catch (error) {
console.error(error);
return res.status(500).json({ message: 'An error occurred' });
}
}

exports.create = async (req, res) => {
try {
const { order, question, answer } = req.body;
const faq = await models.Faq.create({ order, question, answer });
return res.status(201).json(faq);
} catch (error) {
console.error(error);
return res.status(500).json({ message: 'An error occurred' });
}
}

exports.edit = async (req, res) => {
try {
const id = req.params.id;
const { order, question, answer } = req.body;
const faq = await models.Faq.findOne({ where: { id } });
if (!faq) {
return res.status(404).json({ message: 'FAQ not found' });
}
faq.order = order;
faq.question = question;
faq.answer = answer;
await faq.save();
return res.status(200).json(faq);
} catch (error) {
console.error(error);
return res.status(500).json({ message: 'An error occurred' });
}
}

exports.delete = async (req, res) => {
try {
const id = req.params.id;
const faq = await models.Faq.findOne({ where: { id } });
if (!faq) {
return res.status(404).json({ message: 'FAQ not found' });
}
await faq.destroy();
return res.status(200).json({ message: 'FAQ deleted' });
} catch (error) {
console.error(error);
return res.status(500).json({ message: 'An error occurred' });
}
}
69 changes: 69 additions & 0 deletions controllers/initiativeController.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,75 @@ exports.getAll = async (req, res) => {

exports.create = async (req, res) => {
try {
const {
name,
description,
needsAndOffers,
dimensionIds,
subdivisionId
} = req.body;
const userId = req.user.id;

// get the user
const user = await models.User.findOne({
where: { id: userId },
include: [
{
model: models.Subdivision,
as: 'subdivision',
}
]
});

if(!user) {
return res.status(404).json({ message: 'Usuario no encontrado' });
}

// get the dimensions
const dimensions = await models.Dimension.findAll({
where: {
id: dimensionIds,
}
});

// TODO: check if the subdivisionId exists and the city of the subdivision is the same as the user's city

const t = await models.sequelize.transaction();
try {
// create the contact
const contact = {
fullname: req.body.contact.fullname,
email: req.body.contact.email,
phone: req.body.contact.phone,
keepPrivate: req.body.contact.keepPrivate,
}

const newContact = await models.InitiativeContact.create(contact, { transaction: t });

// create the initiative
const initiative = {
name,
description,
needsAndOffers,
contactId: newContact.id,
subdivisionId: subdivisionId,
authorId: user.id,
}

const newInitiative = await models.Initiative.create(initiative, { transaction: t });

// add the dimensions
await newInitiative.addDimensions(dimensions, { transaction: t });

await t.commit();

} catch(error){
console.error(error);
await t.rollback();
return res.status(500).json({ message: 'Error al crear la iniciativa' });
}

return res.status(201).json({ message: 'Iniciativa creada' });

} catch (error) {
console.error(error);
Expand Down
41 changes: 35 additions & 6 deletions controllers/utilsController.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
const { faker } = require('@faker-js/faker');
const models = require('../models');
const dayjs = require('dayjs');
const msg = require('../utils/messages');
const UtilsHelper = require('../helpers/utilsHelper');

exports.getConfigs = async (req, res) => {
try {
const keys = req.query.keys ? req.query.keys.split(',') : null;

const configs = await UtilsHelper.getConfigs(keys);

return res.status(200).json(configs);
} catch (error) {
console.error(error);
res.status(500).json({ message: msg.error.default });
}
}

exports.getSubdivisions = async (req, res) => {
try {
Expand All @@ -23,6 +38,20 @@ exports.getSubdivisions = async (req, res) => {
}
}

exports.getDimensions = async (req, res) => {
try {
// get all dimensions
const dimensions = await models.Dimension.findAll({
attributes: ['id', 'name'],
});

return res.status(200).json(dimensions);
} catch (error) {
console.error(error);
res.status(500).json({ message: msg.error.default });
}
}

exports.somethingForUsers = async (req, res) => {
try {
console.log('req.user', req.user);
Expand All @@ -40,17 +69,17 @@ exports.generateBlogPosts = async (req, res) => {
const sections = await models.BlogSection.findAll();
const authors = await models.User.findAll();

for(let i = 0; i < 100; i++) {
for(let i = 0; i < 50; i++) {
const category = categories[Math.floor(Math.random() * categories.length)];
const section = sections[Math.floor(Math.random() * sections.length)];
const author = authors[Math.floor(Math.random() * authors.length)];

await models.BlogEntry.create({
title: `Post ${i + 1}`,
subtitle: `This is the subtitle for post ${i + 1}`,
text: `This is the content for post ${i + 1}`,
imageUrl: 'https://placecats.com/300/200',
slug: `post-${i + 1}`,
title: faker.lorem.words({min: 8, max: 16}),
subtitle: faker.lorem.sentence(16),
text: faker.lorem.paragraphs({min: 12, max: 24}),
imageUrl: faker.image.urlPicsumPhotos({ width: 1024, height: 768, grayscale: false, blur: 0 }),
slug: faker.lorem.slug(5),
authorId: author.id,
categoryId: category.id,
sectionId: section.id,
Expand Down
59 changes: 59 additions & 0 deletions helpers/utilsHelper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const models = require('../models');

exports.getConfigs = async (keys) => {
try {
const configs = await models.Config.findAll({
where: keys ? { key: keys } : null,
});

// for every config, check the type and parse the value
configs.forEach(config => {
switch (config.type) {
case 'string':
config.value = config.value;
break;
case 'number':
config.value = parseInt(config.value, 10);
break;
case 'boolean':
config.value = config.value === 'true';
break;
case 'json':
config.value = JSON.parse(config.value);
break;
default:
config.value = config.value;
break;
}
});

const formattedConfigs = {};
configs.forEach(config => {
formattedConfigs[config.key] = config.value;
});

return formattedConfigs;
} catch (error) {
throw error;
}
}

exports.saveConfig = async (key, value) => {
try {
const config = await models.Config.findOne({
where: { key: key }
});

if (!config) {
throw new Error('Config not found');
}

// make sure to save the value as a string
config.value = value.toString();
await config.save();

return config;
} catch (error) {
throw error;
}
}
Loading

0 comments on commit 976bde1

Please sign in to comment.