Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
/node_modules
/node_modules

.env
1 change: 0 additions & 1 deletion controllers/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ const email = require('../models/insertdata');
const userType = require('../server/auth/usertype');

const price = (price) => {
console.log('price', price);
if (price < 0 || isNaN(price))
return 422;
return price = Math.trunc(price);
Expand Down
48 changes: 34 additions & 14 deletions controllers/company.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const Settings = require('../models/insertdata');
const check = require('./common.js');
const tip = require('../models/tip');
const transaction = require('../models/transactions');
const history = require('../models/history');
const addCompany = async (ctx) => {

const res = await Settings.addCompany(ctx.request.body); //ctx.request.body
Expand Down Expand Up @@ -60,9 +61,9 @@ const editItem = async (ctx) => {
}

const getItems = async (ctx) => {
console.log('in controller getting items');
const userEmail = await adminPrivilege.userEmail(ctx.headers.authorization.slice(7));
const isAdmin = await adminPrivilege.checkUserType(ctx.headers.authorization.slice(7));
console.log('======LOGGER\n', userEmail, 'is retrieving the list of items', '\n======');

if (isAdmin) {
ctx.status = 201;
Expand All @@ -78,14 +79,14 @@ const getItems = async (ctx) => {
const getCompanyPage = async (ctx) => {
const email = await adminPrivilege.userEmail(ctx.headers.authorization.slice(7));
const isAdmin = await adminPrivilege.checkUserType(ctx.headers.authorization.slice(7));
if (isAdmin) {
console.log('is admin', email);
console.log('======LOGGER\n', email, 'requested company page\n admin status:', isAdmin,'\n======');
if (isAdmin === 'not found') {
return ctx.status = 403;
} else if (isAdmin) {
const data = await Settings.getCompanyPage(email);
data ? ctx.response.body = data : ctx.status = 404;
} else if (!isAdmin) {
console.log('not admin', email);
const data = await Settings.getUserPage(email);
console.log('data',data);
data ? ctx.response.body = data : ctx.status = 404;
}
}
Expand All @@ -111,7 +112,6 @@ const updateSettings = async (ctx) => {
const isAdmin = await adminPrivilege.checkUserType(ctx.headers.authorization.slice(7));
if (isAdmin) {
const data = await Settings.editSettings(ctx.request.body);
console.log('data', data);
data ? ctx.status = 200 : ctx.status = 418;
}

Expand All @@ -121,27 +121,47 @@ const listUsers = async (ctx) => {
const email = await adminPrivilege.userEmail(ctx.headers.authorization.slice(7));
const isAdmin = await adminPrivilege.checkUserType(ctx.headers.authorization.slice(7));
if (isAdmin) {
console.log('admin');
console.log('ADMIN');
const data = await tip.listUsersForAdmin(email, isAdmin);
data ? ctx.body = data : ctx.status = 404;
} else if (!isAdmin) {
console.log('not admin');
console.log('NOT ADMIN');
const data = await tip.listUsersForUser(email, isAdmin);
data ? ctx.body = data : ctx.status = 404;
} else {
ctx.status = 403
}
}

const getAdminTransactions = async (ctx) => {
console.log('TRANSACTIO NCONTROLLER');
const email = await adminPrivilege.userEmail(ctx.headers.authorization.slice(7));
const isAdmin = await adminPrivilege.checkUserType(ctx.headers.authorization.slice(7));
if (isAdmin) {
const data = await transaction.getAdminTransactions();
console.log('a very long list', data);
ctx.body = await history.getHistory(email, isAdmin);
ctx.status = 200;
} else if (!isAdmin) {
const fullHistory = await history.getUserHistory(email);
const filteredHistory = userHistory(fullHistory);
const transactionsInfo = {
recentTransactions: filteredHistory,
userToUserCompTotal: companyTotal(fullHistory.history, 'UserToUser'),
userSpentCompTotal: companyTotal(fullHistory.history, 'UserSpent'),
};
ctx.body = transactionsInfo;
ctx.status = 200;
}
return data
}

const companyTotal = (filteredHistory, type) => {
return filteredHistory.filter (transaction => {
return transaction.type == type;
}).reduce ((acc, transaction) => {
return Number(acc) + Number(transaction.amount);
}, 0);
}

const userHistory = (fullHistory) => {
return fullHistory.history.filter ((transaction) => {
return transaction.from.id == fullHistory.user.id || transaction.to.id == fullHistory.user.id;
});
}

module.exports = {
Expand Down
6 changes: 2 additions & 4 deletions controllers/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ const adminPrivilege = require('../server/auth/usertype');
const catalog = require('../models/catalog');

const add = async (ctx) => {
console.log('controller, adding a user...');
console.log('======LOGGER, adding a user...');
const companyEmail = await adminPrivilege.userEmail(ctx.headers.authorization.slice(7));
const isAdmin = await adminPrivilege.checkUserType(ctx.headers.authorization.slice(7));
console.log('isAdmin?', isAdmin, companyEmail);
if (isAdmin) {
const res = await setUser.addUser(companyEmail, ctx.request.body)
return (res) ? ctx.status = 200 : ctx.status = 409;
Expand All @@ -21,7 +20,7 @@ const buyItem = async (ctx) => {
const userEmail = await adminPrivilege.userEmail(ctx.headers.authorization.slice(7));
const isAdmin = await adminPrivilege.checkUserType(ctx.headers.authorization.slice(7));
if (!isAdmin) {
console.log('a user is buying...');
console.log('======LOGGER a user is buying...');
const res = await catalog.buy(userEmail, urlId, ctx.request.body);
(res) ? ctx.status = 201 : ctx.body = 'ops... something went wrong';
} else {
Expand All @@ -48,7 +47,6 @@ const edit = async (ctx) => {
const signup = async (ctx) => {
const userId = ctx.request.query;
const data = await setUser.signup(ctx.request.body, userId); // to be replaced with ctx.request.body
console.log('data', data);
if (!data) {
ctx.status = 401;
} else {
Expand Down
8 changes: 1 addition & 7 deletions controllers/wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,14 @@ async function addFunds (ctx) {
data ? ctx.status = 200 : ctx.body = 'Operation failed';
}

// async function transferFunds (ctx) {
// const data = await Transaction.transferFunds(ctx.request.body.senderID, ctx.request.body.receiverID, ctx.request.body.amount);
// data ? ctx.status = 200 : ctx.body = 'Transaction failed';
// }

async function tipUser (ctx) {
const email = await adminPrivilege.userEmail(ctx.headers.authorization.slice(7));

const data = await tip.tipUser(ctx.request.body.id, ctx.request.body.amount, ctx.request.body.reason, email)
data ? ctx.status = 200 : ctx.body = 'Transaction failed';

}

module.exports = {
addFunds,
// transferFunds,
tipUser
}
47 changes: 47 additions & 0 deletions models/aws.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// const uuid = require('uuid/v4');
const AWS = require('aws-sdk');
require('dotenv').config()

sendToAWS = async (profilePicBase64, filename) => {
////// file names and id
// var fileName = Object.keys(ctx.request.body.fields)[0];
var albumPhotosKey = 'zendama/';
var photoKey = albumPhotosKey + filename;

///////// amazon webservices
const albumBucketName = process.env.AWS_FOLDER;
const bucketRegion = process.env.AWS_BUCKET_REGION;
const IdentityPoolId = process.env.AWS_IDENT_POOL_ID;

await AWS.config.update({
region: bucketRegion,
credentials: new AWS.CognitoIdentityCredentials({
IdentityPoolId: IdentityPoolId
})
});

var s3 = new AWS.S3({
apiVersion: '2006-03-01',
params: {Bucket: albumBucketName}
});

//////// stack exchange answer
buf = new Buffer(profilePicBase64.replace(/^data:image\/\w+;base64,/, ""),'base64')
var data = {
Bucket: process.env.AWS_BUCKET,
Key: photoKey,
Body: buf,
ContentEncoding: 'base64',
ContentType: 'image/jpeg',
ACL: 'public-read',
};
let loc;
return new Promise((resolve, reject) => {
s3.upload(data, (err, data) => {
if (err) reject(err);
resolve(data.Location);
});
})
}

module.exports = sendToAWS;
19 changes: 12 additions & 7 deletions models/catalog.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ const Company = mongoose.model('Companies', Schemas.AdminSchema);
const User = mongoose.model('Users', Schemas.UserSchema);
const Catalog = mongoose.model('Catalog', Schemas.CatalogSchema);
const Domo = require('../zendomo.js');

const history = require('./history');

const add = async (product, companyEmail, isService) => {
console.log('add item', product, companyEmail, isService);
let company = new Company(); //I need to check if I really need this
company = await Company.find({email: companyEmail});
let newProduct = new Catalog();
newProduct = product;
newProduct.picture = await sendToAWS(product.picture,product.name);
newProduct.isService = isService;
if (!newProduct.isService) {
newProduct.schedule = null;
Expand All @@ -20,13 +20,18 @@ const add = async (product, companyEmail, isService) => {
await company[0].save();
}

const buy = async (userEmail, idItem, infoProduct) => { //Need to be tested
console.log('USER BUYING', userEmail, idItem, infoProduct);
const buy = async (userEmail, idItem, infoProduct) => {
const user = await User.find({email: userEmail});
console.log('user', user);
await Domo.purchase(user[0]._id, infoProduct.price);
//Need to send an email to the admin
//now store arguments
const receiverInfo = await Company.find({email: user[0].company})
const senderInfo = await User.find({email: userEmail});
const receiver = receiverInfo[0];
const sender = senderInfo[0];
const financialReceiver = await Domo.getOneUser(receiver._id);
const financialSender = await Domo.getOneUser(sender._id);
const response = history.history(receiver, sender, infoProduct.price, 'UserSpent', infoProduct.name, user[0].company, financialSender, financialReceiver);
const addTransaction = await history.saveHistory(response, sender.company);
console.log('======LOGGER \n product bought', addTransaction, '\n======');
}

const del = async (companyEmail, companyId) => {
Expand Down
73 changes: 73 additions & 0 deletions models/history.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const Schemas = require('./schemas');
const Company = mongoose.model('Companies', Schemas.AdminSchema);
const User = mongoose.model('Users', Schemas.UserSchema);
const Domo = require('../zendomo.js');
const mailer = require('../server/mailer/mailer');
const Token = mongoose.model('Tokens', Schemas.TokenSchema);

const history = (receiver, sender, amount, transactionType, reason, companyEmail, financialSender, financialReceiver) => {
return {
from: {
id: sender._id,
username: sender.username,
profilePic: sender.profilePic || sender.logo,
},
to: {
id: receiver._id,
username: receiver.username,
profilePic: receiver.profilePic || receiver.logo,
},
amount: amount,
type: transactionType,
reason: reason,
fromBalanceTokens: financialSender.tokens,
fromBalanceCredits: financialSender.credits,
toBalanceTokens: financialReceiver.tokens,
toBalanceCredits: financialReceiver.credits,
_id: financialSender.tradeId + ':' + financialReceiver.tradeId, //transaction id
date: Date.now(),
company: companyEmail,
}
}

const saveHistory = async (history, companyEmail) => {
const company = await Company.find({email: companyEmail});
company[0].history.push(history);
await company[0].save();
return true;
}

const getHistory = async (email, isAdmin) => {
if (isAdmin) {
const company = await Company.find({email:email});
return {
adminDetails: {username: 'bla', profilePic: null},
transactions: company[0].history,
}
} else if (!isAdmin) {
const user = await User.find({email:email});
return {
adminDetails: {username: 'bla', profilePic: null},
transactions: user[0].history,
}
} else {
ctx.status = 403;
}
}

const getUserHistory = async (email) => {
const user = await User.find({email:email});
const companyEmail = user[0].company;
const companyInfo = await Company.find({email: companyEmail});
const companyHistory = companyInfo[0].history;
return {history: companyHistory, user:user[0]};
}

module.exports = {
history,
saveHistory,
getHistory,
getUserHistory,
}
Loading