Skip to content

Commit

Permalink
Finally Done with this issue
Browse files Browse the repository at this point in the history
  • Loading branch information
somyaranjan26 committed Aug 24, 2020
1 parent 901fb3a commit 509ec32
Show file tree
Hide file tree
Showing 14 changed files with 297 additions and 241 deletions.
28 changes: 28 additions & 0 deletions models/Transaction.js
Original file line number Diff line number Diff line change
@@ -1 +1,29 @@
// Adding / Spending Balance History

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,
},
});

module.exports = mongoose.model("Transaction", TransactionSchema);
2 changes: 1 addition & 1 deletion public/css/style.css

Large diffs are not rendered by default.

13 changes: 13 additions & 0 deletions public/css/tailwind.css
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,19 @@ body {
.view-link {
color: #1955E4;
}

.view-link:hover {
color: #0d338a;
}

.button {
background-color: #1955E4;
}

.button:hover {
background-color: #0d338a;
}


.table-content {
overflow: scroll;
Expand Down
17 changes: 15 additions & 2 deletions routes/api/addBalance.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const express = require("express");
const router = express.Router();
const { ensureAuth, ensureGuest } = require("../../middleware/auth");
const User = require("../../models/User");
const Transaction = require("../../models/Transaction");

// @desc // Add Balance page
// @route GET /
Expand All @@ -24,6 +25,7 @@ router.post("/", ensureAuth, async (req, res) => {
let finalAmont = amount + req.user.balance;

try {
// Updating balance to user's schema.
req.body.user = req.user.id;
const updateBalance = await User.findOneAndUpdate(
{ _id: req.user.id },
Expand All @@ -33,8 +35,19 @@ router.post("/", ensureAuth, async (req, res) => {
runValidators: true, // it check weather the fields are valid or not
}
);
console.log(updateBalance);
res.redirect("/");
// Adding new transaction details on Transaction Schema.
const transactionDetails = 'Balance Added to Wallet'
const transactionOpration = 'Deposit'
const transactionUser = req.user.id
const updateTransactoin = await Transaction.create(
{ details: transactionDetails,
amount: amount,
opration: transactionOpration,
user: transactionUser
})

console.log(updateTransactoin);
res.redirect("/done");
} catch (err) {
console.error(err);
res.render("error/500");
Expand Down
28 changes: 20 additions & 8 deletions routes/api/cart.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,37 @@ router.get("/:symbol", ensureAuth, async (req, res) => {
// @desc To buy
// @route POST /cart/buy
router.post("/buy", ensureAuth, async (req, res) => {
let data = req.body;
let user = req.user;
let stockPrice = data.stockPrice;
let noOfStock = data.noOfStock;
let totalAmount = parseFloat(stockPrice * noOfStock).toFixed(4);
const user = req.user;
const symbol = req.body.companySymbol;
const { latestPrice } = await getPrice(symbol);;
const noOfStock = req.body.noOfStock;
const totalAmount = parseFloat(latestPrice * noOfStock).toFixed(4);

const data = {
companySymbol: symbol,
stockPrice: latestPrice,
noOfStock: noOfStock,
totalAmount: totalAmount,
}

console.log(data)

try {
if (totalAmount > req.user.balance) {
let ExtraBalance = totalAmount - req.user.balance;
res.render("transaction", {
res.render("transaction/transaction", {
layout: "layouts/app",
href: "/buy",
ExtraBalance,
message: "Insufficent Balance",
});
} else {
res.render("transaction", {
res.render("transaction/transaction", {
data,
user,
totalAmount,
message: "Order Review",
layout: "layouts/app",
href: "/buy",
});
}
} catch (err) {
Expand Down
1 change: 1 addition & 0 deletions routes/api/portfolio.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const { ensureAuth, ensureGuest } = require("../../middleware/auth");
// @access Private
router.get("/", ensureAuth, (req, res) => {
let user = req.user;
console.log(user)
res
.status(200)
.render("portfolio", { layout: "layouts/app", user, href: "/portfolio" });
Expand Down
94 changes: 93 additions & 1 deletion routes/api/transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const express = require("express");
const router = express.Router();
const { ensureAuth } = require("../../middleware/auth");
const User = require("../../models/User");
const Transaction = require("../../models/Transaction");
const getPrice = require("../../helpers/getPrice");

// @desc To Buy Transaction Page
// @route POST transaction/confirm
Expand All @@ -14,6 +16,8 @@ router.put("/confirm", ensureAuth, async (req, res) => {

req.body.user = req.user.id;

console.log(req.body)

const updatedUser = await User.findOneAndUpdate(
{ _id: req.user.id },
{ balance: balance, $push: { stock: req.body } },
Expand All @@ -22,12 +26,100 @@ router.put("/confirm", ensureAuth, async (req, res) => {
runValidators: true, // it check weather the fields are valid or not
}
);
console.log(updatedUser);

// Add data transaction
// Adding new transaction details on Transaction Schema.
const transactionDetails = `Added ${req.body.noOfStock} ${req.body.companySymbol} stock`
const transactionOpration = 'Debited';
const transactionUser = req.user.id;
const transactionAmount = Number(req.body.totalAmount);

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

console.log(updateTransactoin);
res.redirect("/done");
} catch (err) {
console.error(err);
res.render("error/500");
}
});

// @desc To View Transaction History
// @route POST /transaction
// @access Private
router.get('/', ensureAuth, async (req,res) => {
const user = req.user;
try {
const transactions = await Transaction.find({ user: req.user.id })
.populate('user')
.sort({ created: 'desc'})
.lean()

res.render('transaction/history', {
transactions,
user,
layout: "layouts/app",
href: "/transaction",
})
} catch (err) {
console.error(err)
res.render('error/500')
}
});

// @desc To Sell Stock
// @route POST /transaction/sell
// @access Private
router.post("/sell/:id", ensureAuth, async (req,res) => {
try {
const user = await User.findById(req.user.id)

// get number of stocks and amount of stock
user.stock.forEach( async (stock) => {
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 transactionUser = req.user.id;

// update balance get real time update
const { high } = await getPrice(stock.companySymbol);
const totalAmount = high * stock.noOfStock
const newBalance = req.user.balance + totalAmount

// Added to Transaction
const updateTransaction = await Transaction.create(
{ details: transactionDetails,
amount: totalAmount,
opration: transactionOpration,
user: transactionUser
});

// Update the User Balance and Deleted the Sold Stock
const updatedBalance = await User.findOneAndUpdate(
{ _id: req.user.id },
{ balance: newBalance, $pull: { stock: { _id: req.params.id } } }
);

console.log(updatedBalance)
console.log(updateTransaction)
console.log(newBalance)
}
});



res.redirect('/done');
} catch (err) {
console.error(err)
res.render('error/500')
}
});


module.exports = router;
8 changes: 5 additions & 3 deletions views/addBalance.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,23 @@
<h2 class="text-gray-700 lg:text-6xl text-5xl font-semibold leading-none tracking-wider px-5">Add Balance</h2>
</div>
<hr class="line">

<div class="container py-16 mx-auto">
<h3>Your Current Balance: <%= user.balance%></h3>
<form action="/addBalance" method="POST" class="bg-white shadow-md rounded px-8 pt-6 pb-8 my-6">
<div class=" mb-4">
<form action="/addBalance" method="POST" class="bg-white shadow-md rounded-lg px-8 pt-6 pb-8 my-6">
<div class="text-center mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2">
Enter amount
</label>
<input type="number"
class="shadow appearance-none border rounded w-4/5 py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
name="addAmount" placeholder="amount" />
<input type="submit" value="Add"
class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" />
class="button text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" />
</div>
</form>
</div>

</div>
</section>

6 changes: 4 additions & 2 deletions views/cart.ejs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<div class="relative md:ml-56 lg:ml-64 py-6 px-3 w-full">
<div class="relative bg-white mx-auto max-w-6xl text-gray-600 mt-6 shadow-xl rounded-lg">

<!-- search Box if Required -->
<!-- <div class="relative bg-white mx-auto max-w-6xl text-gray-600 mt-6 shadow-xl rounded-lg">
<lable type="submit" class="absolute left-0 top-0 mt-3 ml-4">
<svg class="h-4 w-4 fill-current" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
version="1.1" id="Capa_1" x="0px" y="0px" viewBox="0 0 56.966 56.966"
Expand All @@ -11,7 +13,7 @@
<input
class="bg-white focus:outline-none focus:outline-none border border-gray-300 rounded-lg mr-6 pl-10 pr-4 py-2 px-4 block w-full appearance-none leading-normal"
type="search" placeholder="Search">
</div>
</div> -->
<div class="mx-auto max-w-6xl flex flex-col w-full px-4 md:py-12 md:px-8 text-gray-800">
<form action="/cart/buy" method="POST">
<h1 class="text-2xl lg:text-4xl font-bold mt-8 mb-4 flex">
Expand Down
4 changes: 4 additions & 0 deletions views/partials/_nav.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@
href="/addBalance">+ Add Balance</a>
<!-- only for development purpose i added ADD BALANCE button here on navbar. -->

<a class="block px-4 py-2 mt-2 text-sm font-semibold text-gray-900 hover:text-blue-800 focus:text-blue-900 hover:bg-blue-100 focus:bg-blue-200 focus:outline-none focus:shadow-outline flex <%= href === '/trasaction' ? 'border tab-color border-l-8': '' %>"
href="/transaction">$ Transactions History</a>
<!-- only for development purpose i added TRANSACTION HISTORY button here on navbar. -->

<a class="block px-4 py-2 mt-2 text-sm font-semibold text-gray-900 hover:text-blue-800 focus:text-blue-900 hover:bg-blue-100 focus:bg-blue-200 focus:outline-none focus:shadow-outline flex <%= href === '/auth/logout' ? 'border tab-color border-l-8': '' %>"
href="/auth/logout"><svg class="w-6 ml-2 mr-1" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd"
Expand Down
Loading

0 comments on commit 509ec32

Please sign in to comment.