Skip to content

Commit

Permalink
payment and subscription models added
Browse files Browse the repository at this point in the history
  • Loading branch information
Roger Calaf authored and Roger Calaf committed Dec 23, 2024
1 parent aa67f32 commit b17e3f0
Show file tree
Hide file tree
Showing 9 changed files with 241 additions and 44 deletions.
105 changes: 105 additions & 0 deletions controllers/subscriptionsController.js
Original file line number Diff line number Diff line change
@@ -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,
}
48 changes: 26 additions & 22 deletions controllers/usersController.js
Original file line number Diff line number Diff line change
Expand Up @@ -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` });
}
Expand Down Expand Up @@ -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')
Expand All @@ -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,
Expand All @@ -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){
Expand Down
2 changes: 1 addition & 1 deletion middleware/verifyJWT.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
44 changes: 44 additions & 0 deletions model/Subscription.js
Original file line number Diff line number Diff line change
@@ -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);
20 changes: 0 additions & 20 deletions model/Track.js
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -25,11 +10,6 @@ const trackSchema = new Schema({
type: Date,
required: false
},
location: {
type: pointSchema,
index: '2dsphere',
required: true
},
status: {
type: Number,
default: 0,
Expand Down
38 changes: 37 additions & 1 deletion model/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,50 @@ 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,
observations: [{
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
Expand Down
23 changes: 23 additions & 0 deletions routes/api/subscriptions.js
Original file line number Diff line number Diff line change
@@ -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;
4 changes: 4 additions & 0 deletions routes/api/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand All @@ -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);
Expand Down
1 change: 1 addition & 0 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit b17e3f0

Please sign in to comment.