From a02836c622002bef16aac66b64892023b99d0382 Mon Sep 17 00:00:00 2001 From: Eduardo Mathias <ems19@inf.ufpr.br> Date: Wed, 7 Jun 2023 11:11:18 -0300 Subject: [PATCH] [ADD] GET PUBLICATIONS AND ACTIVITIES --- src/libs/models/activity.js | 80 ++++++++++++++ src/libs/models/userActivity.js | 29 +++++ src/libs/routes_v1/activity.js | 176 ++++++++++++++++++++++++++++++ src/libs/routes_v1/publication.js | 115 +++++++++---------- 4 files changed, 343 insertions(+), 57 deletions(-) create mode 100644 src/libs/models/activity.js create mode 100644 src/libs/models/userActivity.js create mode 100644 src/libs/routes_v1/activity.js diff --git a/src/libs/models/activity.js b/src/libs/models/activity.js new file mode 100644 index 00000000..f5a1cda2 --- /dev/null +++ b/src/libs/models/activity.js @@ -0,0 +1,80 @@ +const Sequelize = require("sequelize"); +const db = require('../db/postgres.js'); +const libs = `${process.cwd()}/libs`; + +var Activity = db.define("Activity",{ + id:{ + type: Sequelize.STRING, + allowNull:false, + unique: true, + primaryKey: true + }, + type:{ + type: Sequelize.STRING, + allowNull:false + }, + title:{ + type: Sequelize.STRING, + allowNull:false, + }, + subtitle:{ + type: Sequelize.STRING + }, + date:{ + type: Sequelize.DATE, + allowNull:false + }, + authors:{ + type: Sequelize.STRING, + }, + text:{ + type: Sequelize.STRING, + allowNull: false + }, + name_headline:{ + type: Sequelize.STRING, + allowNull:false + }, + resume_headline:{ + type:Sequelize.STRING, + allowNull:false + }, + date_headline:{ + type: Sequelize.DATE, + allowNull:false + }, + local_headline:{ + type:Sequelize.STRING, + allowNull:false + }, + additional_headline:{ + type:Sequelize.STRING + }, + is_draft:{ + type:Sequelize.BOOLEAN, + allowNull:false, + defaultValue: true + }, + is_headline:{ + type:Sequelize.BOOLEAN, + allowNull: false, + defaultValue: false + } + +}, +{timestamps: false}); + +Activity.generateObjectId = function(){ + var timestamp = (new Date().getTime() / 1000 | 0).toString(16); + return timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, function() { + return (Math.random() * 16 | 0).toString(16); + }).toLowerCase(); +} + +const setObjectId = act => { + act.id = Activity.generateObjectId() +}; + +Activity.beforeCreate(setObjectId); + +module.exports = Activity; \ No newline at end of file diff --git a/src/libs/models/userActivity.js b/src/libs/models/userActivity.js new file mode 100644 index 00000000..2c1f8b56 --- /dev/null +++ b/src/libs/models/userActivity.js @@ -0,0 +1,29 @@ +const Sequelize = require("sequelize"); +const db = require('../db/postgres.js'); +const libs = `${process.cwd()}/libs`; +const User = require(`${libs}/models/user`); +const Activity = require(`${libs}/models/activity`); + +var userActivity = db.define("userActivity",{ + id:{ + type: Sequelize.INTEGER, + allowNull:false, + unique: true, + primaryKey: true + }, + user_id:{ + type: Sequelize.STRING, + allowNull:false, + }, + activity_id:{ + type: Sequelize.STRING, + allowNull:false + } +}, +{timestamps: false}); + +userActivity.hasMany(User, {foreignKey: 'id'}); +userActivity.hasMany(Activity, {foreignKey: 'id'}); + +module.exports = userActivity; + diff --git a/src/libs/routes_v1/activity.js b/src/libs/routes_v1/activity.js new file mode 100644 index 00000000..87ba5d1e --- /dev/null +++ b/src/libs/routes_v1/activity.js @@ -0,0 +1,176 @@ +const express = require('express'); + +const activityApp = express(); + +const libs = `${process.cwd()}/libs`; + +const config = require(`${libs}/config`); + +const log = require(`${libs}/log`)(module); + +const Activity = require(`${libs}/models/activity`); + +const response = require(`${libs}/middlewares/response`); + +const email = require(`${libs}/middlewares/email`); + +const passport = require('passport'); + +const fileWorker = require('./file.controller.js'); + +let upload = require('../middlewares/multer.config.js'); + +function emailSyntax(email) { + const regex = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; + return regex.test(email); +} + +activityApp.get('/', async (req, res, next) => { + const page = parseInt(req.query.page) || 1; + const pageSize = parseInt(req.query.pageSize) || 5; + try { + const totalCount = await Activity.count(); + const offset = (page - 1) * pageSize; + + const acts = await Activity.findAll({ + offset, + limit: pageSize, + where: { + is_draft: false + }, + order:[ + ['date', 'DESC']] + }); + + res.json({ + page, + pageSize, + totalCount, + data: acts, + }); + } catch (error) { + console.error(error); + res.status(500).json({ error: 'An error occurred' }); + } +}); + +activityApp.get('/', async (req, res, next) => { + const page = parseInt(req.query.page) || 1; + const pageSize = parseInt(req.query.pageSize) || 5; + try { + const totalCount = await Activity.count(); + const offset = (page - 1) * pageSize; + + const acts = await Activity.findAll({ + offset, + limit: pageSize, + where: { + is_draft: acts + }, + order:[ + ['date', 'DESC']] + }); + + res.json({ + page, + pageSize, + totalCount, + data: acts, + }); + } catch (error) { + console.error(error); + res.status(500).json({ error: 'An error occurred' }); + } + }); + +activityApp.get('/:id', (req, res, next) => { + Activity.findByPk(req.params.id).then((act) => { + if (!act) { + res.statusCode = 404; + res.json({ msg: "A atividade não está cadastrada" }); + } else { + req.result = act.toJSON(); + next(); + } + }).catch(function (err) { + log.error(err); + return next(err); + }); +}, response('activity')); + +activityApp.post('/', async (req, res, next) => { + let data = JSON.parse(req.body.data); + let pb = await Publication.create({ + id: 0, + filter: data.categoria, + title: data.title, + authors: data.autores, + organization: data.organizacao, + year: data.ano, + text: data.texto, + link: data.link, + upload: _file_id, + is_draft: data.rascunho, + is_homepage: data.homepage + }).catch(function (err) { + log.error(err); + let errors = []; + for (let errName in err.errors) { + errors.push(err.errors[errName].message); + } + log.error(errors); + res.statusCode = 400; + return res.json({ err, errors }); + // handle error; + }); + req.result = pb.toJSON(); + next(); +}, response('publication')); + +activityApp.put('/:id', passport.authenticate('bearer', { session: false }), async (req, res, next) => { + let pb = await Publication.findByPk(req.params.id).catch(function (err) { + if (err) { + log.error(err); + return next({ err }); + } + }) + if (!pb) { + res.statusCode = 404; + return next({ + err: { + message: 'Publicação não encontrada' + } + }); + } + pb.filter = req.body.categoria || pb.filter; + pb.title = req.body.title || pb.title; + pb.authors = req.body.autores || pb.authors; + pb.organization= req.body.organizacao || pb.organization; + pb.year= req.body.ano || pb.year; + pb.text= req.body.texto || pb.text; + pb.link= req.body.link || pb.link; + pb.upload= req.body.upload || pb.upload; + pb.is_homepage= req.body.homepage || pb.is_homepage; + + pb.save().catch(err => { + if (err) { + log.error(err); + return next({ message: 'Erro ao atualizar publicacao' }); + } + }) + let p = p.toJSON(); + res.json({ publication: p }); + +}); + +activityApp.delete('/:id', passport.authenticate('bearer', { session: false }), async (req, res, next) => { + await Publication.destroy({where:{id:req.params.id}}).catch(function (err) { + if (err) { + log.error(err); + return next({ err }); + } +}); + return next({ msg: 'Publication Deleted', status: 200 }); +}); + +module.exports = activityApp; diff --git a/src/libs/routes_v1/publication.js b/src/libs/routes_v1/publication.js index 972928c7..e29abd7e 100644 --- a/src/libs/routes_v1/publication.js +++ b/src/libs/routes_v1/publication.js @@ -27,26 +27,65 @@ function emailSyntax(email) { return regex.test(email); } -pubApp.get('/', passport.authenticate('bearer', { session: false }), async (req, res, next) => { - let up = await UserPublication.findAll({ where: { user_id: req.user.id } }).catch(function (err) { - if (err) { - log.error(err); - return next(err); - } - }); - console.log(up); - let publications = []; - for (let _id in up.publication_id) { - let pb = await Publication.findByPk(_id).catch(function (err) { - if (err) { - log.error(err); - return next(err); +pubApp.get('/', async (req, res, next) => { + const page = parseInt(req.query.page) || 1; // Current page number + const pageSize = parseInt(req.query.pageSize) || 5; // Number of items per page + try { + const totalCount = await Publication.count(); + const offset = (page - 1) * pageSize; + + const publis = await Publication.findAll({ + offset, + limit: pageSize, + where: { + is_draft: false } }); - publications.push(pb); + + res.json({ + page, + pageSize, + totalCount, + data: publis, + }); + } catch (error) { + console.error(error); + res.status(500).json({ error: 'An error occurred' }); } - next(); -}, response('publications')); +}); + +pubApp.get('/drafts', async (req, res, next) => { + const page = parseInt(req.query.page) || 1; // Current page number + const pageSize = parseInt(req.query.pageSize) || 5; // Number of items per page + + try { + // Count total number of items + const totalCount = await Publication.count(); + + // Calculate offset based on page and pageSize + const offset = (page - 1) * pageSize; + + // Query the database with pagination options + const drafts = await Publication.findAll({ + offset, + limit: pageSize, + where: { + is_draft: true + } + }); + + res.json({ + page, + pageSize, + totalCount, + data: drafts, + }); + } catch (error) { + console.error(error); + res.status(500).json({ error: 'An error occurred' }); + } +}); + pubApp.get('/:id', (req, res, next) => { Publication.findByPk(req.params.id).then((pb) => { @@ -80,40 +119,7 @@ pubApp.post('/', upload.single('file'), async (req, res, next) => { text: data.texto, link: data.link, upload: _file_id, - is_draft: false, - is_homepage: data.homepage - }).catch(function (err) { - log.error(err); - let errors = []; - for (let errName in err.errors) { - errors.push(err.errors[errName].message); - } - log.error(errors); - res.statusCode = 400; - return res.json({ err, errors }); - // handle error; - }); - req.result = pb.toJSON; -}, response('publication')); - -pubApp.post('/rascunho', upload.single('file'), passport.authenticate('bearer', { session: false }), async (req, res, next) => { - let _file_id = null - if(req.file){ - _file_id = await fileWorker.uploadFile(req.file); - if(!_file_id) - console.log("NAO ARQUIVO");} - let data = JSON.parse(req.body.data); - let pb = await Publication.create({ - id: 0, - filter: data.categoria, - title: data.title, - authors: data.autores, - organization: data.organizacao, - year: data.ano, - text: data.texto, - link: data.link, - upload: _file_id, - is_draft: true, + is_draft: data.rascunho, is_homepage: data.homepage }).catch(function (err) { log.error(err); @@ -126,14 +132,9 @@ pubApp.post('/rascunho', upload.single('file'), passport.authenticate('bearer', return res.json({ err, errors }); // handle error; }); - let up = await Publication.create({ - user_id: req.user.id, - publication_id: pb.id - }) req.result = pb.toJSON(); - next(); -},response('rascunho')); +}, response('publication')); pubApp.put('/:id', passport.authenticate('bearer', { session: false }), async (req, res, next) => { let pb = await Publication.findByPk(req.params.id).catch(function (err) { -- GitLab