Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented Referral System, code formatted and fixed some typos #62

Merged
merged 5 commits into from
Aug 26, 2020
Merged
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
40 changes: 22 additions & 18 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const mongoose = require("mongoose");
const MongoStore = require("connect-mongo")(session);
const connectDB = require("./config/db");
const flash = require("connect-flash");
var cookieParser = require("cookie-parser");

// Load config
dotenv.config({ path: "./config/config.env" });
Expand All @@ -40,19 +41,19 @@ app.use(express.json());

// Method override
app.use(
methodOverride(function(req, res) {
if (req.body && typeof req.body === "object" && "_method" in req.body) {
// look in urlencoded POST bodies and delete it
let method = req.body._method;
delete req.body._method;
return method;
}
})
methodOverride(function (req, res) {
if (req.body && typeof req.body === "object" && "_method" in req.body) {
// look in urlencoded POST bodies and delete it
let method = req.body._method;
delete req.body._method;
return method;
}
})
);

// Logging
if (process.env.NODE_ENV === "development") {
app.use(morgan("dev"));
app.use(morgan("dev"));
}

// EJS
Expand All @@ -65,14 +66,17 @@ app.use(expressLayouts);

// Sessions
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
})
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
})
);

// cookie middleware
app.use(cookieParser());

// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
Expand Down Expand Up @@ -110,6 +114,6 @@ const PORT = process.env.PORT || 3000;

// Server Listening
app.listen(
PORT,
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
);
PORT,
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
);
1 change: 0 additions & 1 deletion middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ module.exports = {
if (req.isAuthenticated()) {
return next();
} else {
req.flash("error_msg", "Password or Email does not match");
res.redirect("/");
}
},
Expand Down
40 changes: 20 additions & 20 deletions models/Transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,26 @@ const mongoose = require("mongoose");
var Float = require("mongoose-float").loadType(mongoose);

const TransactionSchema = new mongoose.Schema({
details: {
type: String,
required: true,
},
amount: {
type: Float,
required: true,
},
opration: {
type: String,
required: true
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
createdAt: {
type: Date,
default: Date.now,
},
details: {
type: String,
required: true,
},
amount: {
type: Float,
required: true,
},
operation: {
type: String,
required: true,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
createdAt: {
type: Date,
default: Date.now,
},
});

module.exports = mongoose.model("Transaction", TransactionSchema);
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"concurrently": "^5.3.0",
"connect-flash": "^0.1.1",
"connect-mongo": "^3.2.0",
"cookie-parser": "^1.4.5",
"cross-env": "^7.0.2",
"date-fns": "^2.15.0",
"dotenv": "^8.2.0",
Expand Down
2 changes: 1 addition & 1 deletion public/css/style.css

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions routes/api/addBalance.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ router.post("/", ensureAuth, async (req, res) => {

try {
// Updating balance to user's schema.
req.body.user = req.user.id;
// req.body.user = req.user.id;
const updateBalance = await User.findOneAndUpdate(
{ _id: req.user.id },
{ balance: finalAmont },
Expand All @@ -40,12 +40,12 @@ router.post("/", ensureAuth, async (req, res) => {

// Adding new transaction details on Transaction Schema.
const transactionDetails = "Balance Added to Wallet";
const transactionOpration = "Deposit";
const transactionOperation = "Deposit";
const transactionUser = req.user.id;
const updateTransactoin = await Transaction.create({
details: transactionDetails,
amount: amount,
opration: transactionOpration,
operation: transactionOperation,
user: transactionUser,
});

Expand Down
4 changes: 3 additions & 1 deletion routes/api/done.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ const { ensureAuth, ensureGuest } = require("../../middleware/auth");
// @route GET /done
// @access Private
router.get("/", ensureAuth, (req, res) => {
res.status(200).render("done");
const userId = req.user.id;
const host = req.headers.host;
res.status(200).render("done", { userId, host }); // pass userId for the share link generation
});

module.exports = router;
10 changes: 9 additions & 1 deletion routes/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const express = require("express");
const router = express.Router();
const { ensureAuth, ensureGuest } = require("../../middleware/auth");
const { ensureGuest } = require("../../middleware/auth");

// @desc Login/Landing page
// @route GET /
Expand All @@ -11,4 +11,12 @@ router.get("/", ensureGuest, (req, res) => {
res.status(200).render("login", { layout: "layouts/login" });
});

// @desc Login from Referral link
// @route GET /share/:id (will be redirected to login page)
// @access Public
router.get("/share/:id", ensureGuest, (req, res) => {
let user1 = req.params.id;
res.cookie("prevUser", user1, { expire: 36000 + Date.now() }).redirect("/");
});

module.exports = router;
89 changes: 79 additions & 10 deletions routes/api/portfolio.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,89 @@ const { ensureAuth, ensureGuest } = require("../../middleware/auth");

const totalData = require("../../config/data-total.json");

// import User and Transaction models
const User = require("../../models/User");
const Transaction = require("../../models/Transaction");

// @desc Portfolio page
// @route GET /portfolio
// @access Private
router.get("/", ensureAuth, (req, res) => {
let user = req.user;
router.get("/", ensureAuth, async (req, res) => {
let avatar = req.user.image;
res
.status(200)
.render("portfolio", {
layout: "layouts/app",
avatar,
totalData,
href: "/portfolio",
});
// See if prevUser cookie exists and the new user have balance of 10000 (amount for the newly created account)
if (req.cookies.prevUser !== "" && req.user.balance === 10000) {
try {
// Get the balance of the user who shared link
const { balance: prevUserBalance } = await User.findOne({
_id: req.cookies.prevUser,
});

// Update the balance of user who shared the share link
const updateBalanceForOtherUser = await User.findOneAndUpdate(
{ _id: req.cookies.prevUser },
{ balance: prevUserBalance + 100 }, // updating existing balance
{
new: true, // it will create a new one, if it doesn't exist
runValidators: true, // it check weather the fields are valid or not
}
);

console.log(updateBalanceForOtherUser);

// Update the balance of user who used the share link
const updateBalanceForCurrentUser = await User.findOneAndUpdate(
{ _id: req.user.id },
{ balance: req.user.balance + 50 },
{
new: true, // it will create a new one, if it doesn't exist
runValidators: true, // it check weather the fields are valid or not
}
);

console.log(updateBalanceForCurrentUser);

// Adding new transaction details on Transaction Schema for user who signed up using the share link
const transactionDetails =
"50$ Balance Added to Wallet from the share link";
const transactionOperation = "Debited";
const transactionUser = req.user.id;
const updateTransactoinForCurrentUser = await Transaction.create({
details: transactionDetails,
amount: 50,
operation: transactionOperation,
user: transactionUser,
});

console.log(updateTransactoinForCurrentUser);

// Adding new transaction details on Transaction Schema for the user who shared the link
const updateTransactoinForOtherUser = await Transaction.create({
details: "100$ Balance Added to Wallet from the shared link",
amount: 100,
operation: transactionOperation,
user: req.cookies.prevUser,
});

console.log(updateTransactoinForOtherUser);

// set prevUser cookie to empty string after one user signed up using it
res.cookie("prevUser", "");
} catch (err) {
console.error(err);
}
}

// If a cookie exists but the user has balance more than 10000 which means he already have an account, set the cookie value to empty
if (req.cookies.prevUser !== "" && req.user.balance !== 10000) {
res.cookie("prevUser", "");
}

res.status(200).render("portfolio", {
layout: "layouts/app",
avatar,
totalData,
href: "/portfolio",
});
});

module.exports = router;
8 changes: 4 additions & 4 deletions routes/api/transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,14 @@ router.put("/confirm", ensureAuth, async (req, res) => {
// Add data transaction
// Adding new transaction details on Transaction Schema.
const transactionDetails = `Added ${req.body.noOfStock} ${req.body.companySymbol} stock`;
const transactionOpration = "Debited";
const transactionOperation = "Debited";
const transactionUser = req.user.id;
const transactionAmount = Number(req.body.totalAmount);

const updateTransactoin = await Transaction.create({
details: transactionDetails,
amount: transactionAmount,
opration: transactionOpration,
operation: transactionOperation,
user: transactionUser,
});

Expand Down Expand Up @@ -101,7 +101,7 @@ router.post("/sell/:id", ensureAuth, async (req, res) => {
if (stock._id == req.params.id) {
// Adding new transaction details on Transaction Schema.
const transactionDetails = `Sold ${stock.noOfStock} stock of ${stock.companySymbol}`;
const transactionOpration = "Credit";
const transactionOperation = "Credit";
const transactionUser = req.user.id;

// update balance get real time update
Expand All @@ -113,7 +113,7 @@ router.post("/sell/:id", ensureAuth, async (req, res) => {
const updateTransaction = await Transaction.create({
details: transactionDetails,
amount: totalAmount,
opration: transactionOpration,
operation: transactionOperation,
user: transactionUser,
});

Expand Down
1 change: 1 addition & 0 deletions routes/api/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ router.post("/signup", ensureGuest, (req, res) => {
layout: "layouts/login",
errors,
firstName,
email,
lastName,
password1,
password2,
Expand Down
Loading