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

Finally Done with this issue #56

Merged
merged 2 commits into from
Aug 24, 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
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);
3 changes: 2 additions & 1 deletion public/css/style.css

Large diffs are not rendered by default.

65 changes: 65 additions & 0 deletions public/css/tailwind.css
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,71 @@ body {
width: 75vw;
}

.tradebyte-logo {
color: #1955E4;
text-shadow: 1px 2px 40px rgba(0, 0, 0, 0.5)
}

.line {
border: 1.5px solid #8e9aad;
}

.user-profile {
border-radius: 100px;
border: 10px solid #1955E4;
width: 130px;
height: 130px;
}

.tick {
height: 22px;
width: 22px;
border-radius: 50%;
background-color: #38cda0;
color: white;
}

.tick-background {
background: #a9f7e6;
border-radius: 29px;
color: #1b9b7f;
}

.tab-color {
border-radius: 10px;
border-color: #1955E4;
color: #1955E4;
}

.view-link {
color: #1955E4;
}

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

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

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


.table-content {
overflow: scroll;
overflow-x: scroll;
overflow-y: auto;
}

.transaction-companySymbol {
color: rgb(0, 0, 0);
font-weight: 700;
font-size: 1.1rem;
}

@tailwind components;

.symbolicon {
Expand Down
42 changes: 30 additions & 12 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 @@ -25,19 +26,36 @@ router.post("/", ensureAuth, async(req, res) => {
// why ensureGuest here?
let amount = Number(req.body.addAmount); // type cast amount to number as body parser take it as string
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 },
{ balance: finalAmont },
{
new: true, // it will create a new one, if it doesn't exist
runValidators: true, // it check weather the fields are valid or not
}
);
// 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");
}

try {
req.body.user = req.user.id;
const updateBalance = await User.findOneAndUpdate({ _id: req.user.id }, { balance: finalAmont }, {
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(updateBalance);
res.redirect("/");
} catch (err) {
console.error(err);
res.render("error/500");
}
});

module.exports = router;
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
6 changes: 6 additions & 0 deletions routes/api/portfolio.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@ const { ensureAuth, ensureGuest } = require("../../middleware/auth");
// @route GET /portfolio
// @access Private
router.get("/", ensureAuth, (req, res) => {

let user = req.user;
console.log(user)

// Check1
let avatar = req.user.image;

res
.status(200)
.render("portfolio", { layout: "layouts/app", avatar, 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;
49 changes: 24 additions & 25 deletions views/addBalance.ejs
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
<main class="md:col-span-4 bg-gray-300 md:ml-56 lg:ml-64 md:pr-14 w-full rounded">
<div class="container px-5 py-10 mx-auto md:px-auto">
<header>
<h2 class="text-blue-700 text-4xl font-semibold leading-none tracking-wider"> <a href="/portfolio"><i class="fas fa-arrow-left"></i></a> AddBalance
</h2>
</header>
<div>
<div class="relative text--600 mt-12 shadow-md rounded-b-lg py-4 pl-2 font-bold">
<h3 class="underline sm:no-underline md:line-through lg:underline xl:no-underline text-blue-700"> Your Current Balance:
<%= user.balance%>
</h3>
</div>
<div class="container py-16 mx-auto">
<form action="/addBalance" method="POST" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
<div class="mb-5">
<label class="block text-gray-700 text-xl font-bold mb-2">
Enter amount
</label>
<input type="number" class="shadow appearance-none border rounded w-full 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=" mt-2 bg-blue-500 hover:bg-blue-400 text-white font-bold py-2 px-6 rounded-full focus:outline-none focus:shadow-outline " />
</div>
</form>
</div>
<section class="text-gray-700 body-font md:ml-56 lg:ml-64 md:mx-auto md:pr-14 w-screen inline">
<div class="container px-5 py-10 mx-auto md:px-auto">
<div class="my-4 absolute-center">
<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-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="button text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" />
</div>
</form>
</div>

</div>
</main>
</div>
</section>
Loading