diff --git a/controllers/subscriptionsController.js b/controllers/subscriptionsController.js new file mode 100644 index 0000000..435e123 --- /dev/null +++ b/controllers/subscriptionsController.js @@ -0,0 +1,105 @@ +const User = require('../model/User'); +const Subscription = require('../model/Subscription'); +const { updateEmployee } = require('./employeesController'); + + +const getAllSubscriptions = async (req, res) => { + const subscriptions = await Subscription.find(); + if (!subscriptions) return res.status(204).json({ 'message': 'No subscriptions found' }); + res.json(subscriptions); +} + + +const getSubscription = async (req, res) => { + console.log(req?.params?.id) + if (!req?.params?.id) return res.status(400).json({ "message": 'Subscription ID required' }); + const subscription = await Subscription.findOne({ _id: req.params.id }).exec(); + if (!subscription) { + return res.status(204).json({ 'message': `Subscription ID ${req.params.id} not found` }); + } + res.json(subscription); +} + +const getUserSubscriptions = async (req, res) => { + if (!req?.params?.id) return res.status(400).json({ "message": 'User ID required' }); + //console.log(req?.query?.page); + //TODO: add pagination filter + Date filter + const limit = 5; + let options = {} + if(req?.query?.page){ + //let page = (!req?.query?.page ? req?.query?.page : 1); + options = { limit: limit, skip: limit*(req.query.page-1), sort: [{"date": "desc" }] }; + }else{ + options = { sort: [{"date": "desc" }] }; + } + console.log(options) + const user = await User.findOne({ _id: req.params.id }).populate({path:'subscriptions',options}).exec(); + if (!user) return res.status(204).json({ 'message': 'No users found' }); + const subscriptions = user.subscriptions; +// console.log(observations); + res.json(subscriptions); +} + +const createNewSubscription = async (req, res) => { + // console.log('This is a new oservation body received...') + console.log(req.body); + console.log(req.params.id); + + let user = await User.findOne({ _id: req.params.id }); + if (!user) return res.status(204).json({ 'message': 'No users found' }); + req.body.user = user; + console.log(req.body); + try { + const result = await Subscription.create(req.body); + // console.log(req.body.observationTypes.snowpack); + user.subscriptions.push(result.toObject({ getters: true })); + user.pro = true; + user.expiresAt = req.body.expiresAt; + let saveResult = await user.save(); + // console.log(saveResult) + return res.status(201).json({'subscriptions': user.subscriptions, 'subscriptionId': result._id}); + } catch (err) { + console.log('error') + console.error(err); + res.status(500).json({ 'message': 'Error creating subscription' }); + } +} + +const editSubscription = async (req, res) =>{ + const { id } = req.params; + //console.log('------------edit user form body -------') + console.log(req.body); + console.log(id); + if (!id) return res.status(400).json({ "message": 'Subscription ID required' }); + // console.log(id); + let subscription = await Subscription.findOne({ _id: id }).exec(); + if (!subscription) { + return res.status(204).json({ 'message': `Subscription ID ${id} not found` }); + } + + subscription = {...subscription,...req.body}; + subscription.save(); + + try{ + // console.log('user saved') + let response = await subscription.save(); + + // console.log("----received from the app---"); + res.status(200).json(subscription); + }catch (e){ + console.log(e); + res.json({'message': e}); + } + + +} + + + +module.exports = { + getAllSubscriptions, + getUserSubscriptions, + getSubscription, + createNewSubscription, + editSubscription, +} \ No newline at end of file diff --git a/controllers/usersController.js b/controllers/usersController.js index 8b6e3b3..3a3ecc0 100644 --- a/controllers/usersController.js +++ b/controllers/usersController.js @@ -19,9 +19,12 @@ const deleteUser = async (req, res) => { const getUser = async (req, res) => { //const { id } = req.body; - const { id } = req.params; + const { id, populate } = req.params; if (!id) return res.status(400).json({ "message": 'User ID required' }); - const user = await User.findOne({ _id: id }).exec(); + let user; + if (populate) user = await User.findOne({ _id: id }).populate('observations').populate('payments').exec(); + else user = await User.findOne({ _id: id }).exec(); + if (!user) { return res.status(204).json({ 'message': `User ID ${id} not found` }); } @@ -66,31 +69,30 @@ const editUser = async (req, res) =>{ && req.body.terrainType && req.body.conditionsType) req.body.status = true; - // console.log("-----received from the app---"); - // console.log(req.body); - // console.log("--------"); - if (req.body.blocked){ user.blocked = true; user.name = "Anonimous"; user.lastName = ""; user.email = user._id+"@anonimous"; } else{ - user.name = req.body.name; - user.lastName = req.body.lastName; - user.username = req.body.username; - user.gender = req.body.gender - user.professionalOrientation = req.body.professionalOrientation - user.snowEducationLevel = req.body.snowEducationLevel - user.snowExperienceLevel = req.body.snowExperienceLevel - user.avalanchExposure = req.body.avalanchExposure - user.terrainType = req.body.terrainType - user.conditionsType = req.body.conditionsType - user.status = req.body.status - user.age = req.body.age - user.twitterProfile = req.body.twitterProfile - user.instagraProfile = req.body.instagraProfile + if (req.body.name) user.name = req.body.name; + if (req.body.lastName) user.lastName = req.body.lastName; + if (req.body.username) user.username = req.body.username; + if (req.body.gender) user.gender = req.body.gender; + if (req.body.professionalOrientation) user.professionalOrientation = req.body.professionalOrientation + if (req.body.snowEducationLevel) user.snowEducationLevel = req.body.snowEducationLevel + if (req.body.snowExperienceLevel) user.snowExperienceLevel = req.body.snowExperienceLevel + if (req.body.avalanchExposure) user.avalanchExposure = req.body.avalanchExposure + if (req.body.terrainType) user.terrainType = req.body.terrainType + if (req.body.conditionsType) user.conditionsType = req.body.conditionsType + if (req.body.license) user.license = req.body.license + if (req.body.status) user.status = req.body.status + if (req.body.age) user.age = req.body.age + if (req.body.twitterProfile) user.twitterProfile = req.body.twitterProfile + if (req.body.instagraProfile) user.instagraProfile = req.body.instagraProfile } + // console.log('------- updated user ----') + // console.log(user); //let response = await User.findOne({_id: id},req.body) try{ // console.log('user saved') @@ -100,7 +102,7 @@ const editUser = async (req, res) =>{ let aux = { 'roles':user.roles, '_id':user._id, 'status': user.status , - 'username' : user.username, + 'username': user.username, 'name': user.name, 'lastName': user.lastName, 'email': user.email, @@ -111,10 +113,12 @@ const editUser = async (req, res) =>{ 'snowEducationLevel': user.snowEducationLevel, 'snowExperienceLevel': user.snowExperienceLevel, 'age': user.age, + 'license':user.license, 'instagraProfile': user.instagraProfile, 'twitterProfile': user.twitterProfile, 'terrainType': user.terrainType} - console.log(aux); + // console.log('------- aux user ----') + // console.log(aux); //console.log("----------------------------"); res.status(200).json(aux); }catch (e){ diff --git a/middleware/verifyJWT.js b/middleware/verifyJWT.js index 164e594..9ca5c97 100644 --- a/middleware/verifyJWT.js +++ b/middleware/verifyJWT.js @@ -4,7 +4,7 @@ const verifyJWT = (req, res, next) => { const authHeader = req.headers.authorization || req.headers.Authorization; if (!authHeader?.startsWith('Bearer ')) return res.sendStatus(401); const token = authHeader.split(' ')[1]; - // console.log(token) + // console.log(token) jwt.verify( token, process.env.ACCESS_TOKEN_SECRET, diff --git a/model/Subscription.js b/model/Subscription.js new file mode 100644 index 0000000..7a003d9 --- /dev/null +++ b/model/Subscription.js @@ -0,0 +1,44 @@ + +const mongoose = require('mongoose'); +const Schema = mongoose.Schema; + +const subscriptionSchema = new Schema({ + type: { + type: String, + required: false + }, + status: { + type: String, + required: true + }, + expiresAt:{ + type: Number, + required: false + }, + stripeId: { + type: String, + required: true, + unique: true, + }, + invoiceId:{ + type: String, + required: true, + }, + user: { + type: Schema.Types.ObjectId, + ref: "User", + required: true + } +}); + +subscriptionSchema.pre('remove', function(next) { + console.log('remove subscription from users after deletion') + let index = this.user.payments.indexOf(this._id); + if (index > -1) { + this.user.subscriptions.splice(index, 1); + this.user.save(); + } + next(); +}); + +module.exports = mongoose.model('Subscription', subscriptionSchema); \ No newline at end of file diff --git a/model/Track.js b/model/Track.js index 665cd26..608ed49 100644 --- a/model/Track.js +++ b/model/Track.js @@ -1,21 +1,6 @@ const mongoose = require('mongoose'); const Schema = mongoose.Schema; -const pointSchema = new mongoose.Schema({ - type: { - type: String, - enum: ['Point'], - default: 'Point', - required: true - }, - coordinates: { - type: [Number], - index: '2dsphere', - required: true - }, - // index: '2dsphere', -}); - const trackSchema = new Schema({ title: { type: String, @@ -25,11 +10,6 @@ const trackSchema = new Schema({ type: Date, required: false }, - location: { - type: pointSchema, - index: '2dsphere', - required: true - }, status: { type: Number, default: 0, diff --git a/model/User.js b/model/User.js index fda3a43..51c0246 100644 --- a/model/User.js +++ b/model/User.js @@ -89,6 +89,32 @@ const userSchema = new Schema({ type: Boolean, default: false }, + license:{ + pro: { + type: Boolean, + default: false + }, + expiresAt:{ + type: Number, + required: false + }, + last_invoice: { + type: String, + required: false, + }, + stripeId: { + type: String, + unique: true, + }, + }, + // pro: { + // type: Boolean, + // default: false + // }, + // expiresAt:{ + // type: Number, + // required: false + // }, googleUserId: String, appleUserId: String, refreshToken: String, @@ -96,7 +122,17 @@ const userSchema = new Schema({ type: Schema.Types.ObjectId, ref: "Observation", required: false - }] + }], + tracks: [{ + type: Schema.Types.ObjectId, + ref: "Track", + required: false + }], + // subscriptions: [{ + // type: Schema.Types.ObjectId, + // ref: "Subscription", + // required: false + // }] }, { timestamps: true diff --git a/routes/api/subscriptions.js b/routes/api/subscriptions.js new file mode 100644 index 0000000..810f5aa --- /dev/null +++ b/routes/api/subscriptions.js @@ -0,0 +1,23 @@ +const express = require('express'); +const router = express.Router(); +const subscriptionsController = require('../../controllers/subscriptionsController'); +const ROLES_LIST = require('../../config/roles_list'); +const verifyRoles = require('../../middleware/verifyRoles'); + +router.route('/') + .get(verifyRoles(ROLES_LIST.User, ROLES_LIST.Editor), subscriptionsController.getAllSubscriptions) + + // .put(verifyRoles(ROLES_LIST.User, ROLES_LIST.Editor), paymentsController.updatePayment) + // .delete(verifyRoles(ROLES_LIST.User), paymentsController.deletePayment); + +router.route('/:id') + .get(verifyRoles(ROLES_LIST.User, ROLES_LIST.Editor),subscriptionsController.getSubscription); + +router.route('/:id') + .put(verifyRoles(ROLES_LIST.User), subscriptionsController.editSubscription); + +router.route('/user/:id') + //.get(verifyRoles(ROLES_LIST.User, ROLES_LIST.Editor),paymentsController.getUserPayments) + .post(verifyRoles(ROLES_LIST.User, ROLES_LIST.Editor), subscriptionsController.createNewSubscription); + +module.exports = router; \ No newline at end of file diff --git a/routes/api/users.js b/routes/api/users.js index 33aa14b..81f446b 100644 --- a/routes/api/users.js +++ b/routes/api/users.js @@ -2,6 +2,7 @@ const express = require('express'); const router = express.Router(); const usersController = require('../../controllers/usersController'); const observationsController = require('../../controllers/observationsController'); +const subscriptionsController = require('../../controllers/subscriptionsController'); const ROLES_LIST = require('../../config/roles_list'); const verifyRoles = require('../../middleware/verifyRoles'); @@ -15,6 +16,9 @@ router.route('/:id/observations') // .put(observationsController.updateObservation) // .delete(observationsController.deleteObservation); +// router.route('/:id/subscriptions') +// .get(verifyRoles(ROLES_LIST.User), subscriptionsController.getUserSubscriptions) + router.route('/:id') .put(verifyRoles(ROLES_LIST.User), usersController.editUser); diff --git a/server.js b/server.js index 653c236..13278ef 100644 --- a/server.js +++ b/server.js @@ -70,6 +70,7 @@ app.use(verifyJWT); app.use('/employees', require('./routes/api/employees')); app.use('/users', require('./routes/api/users')); app.use('/observations', require('./routes/api/observations')); +//app.use('/subscriptions', require('./routes/api/subscriptions')); app.all('*', (req, res) => { res.status(404);