瀏覽代碼

Users can now log in.
Still many bugs, can't do anything after logging in.

Lee Morgan 5 年之前
父節點
當前提交
47d0d29945

+ 3 - 2
controllers/helper.js

@@ -3,11 +3,11 @@ const axios = require("axios");
 const Transaction = require("../models/transaction.js");
 
 module.exports = {
-    getSquareData: function(merchant, data){
+    getSquareData: function(owner, merchant, data){
         let ingredients = {};
 
         return axios.post(`${process.env.SQUARE_ADDRESS}/v2/orders/search`, data, {
-            headers: {Authorization: `Bearer ${merchant.square.accessToken}`}
+            headers: {Authorization: `Bearer ${owner.square.accessToken}`}
         })
             .then((response)=>{
                 let transactions = [];
@@ -64,6 +64,7 @@ module.exports = {
                 return transactions;
             })
             .catch((err)=>{
+                console.log(err.response.data);
                 return "ERROR: UNABLE TO UPDATE DATA";
             });
     },

+ 17 - 12
controllers/otherData.js

@@ -1,4 +1,5 @@
 const Owner = require("../models/owner.js");
+const Merchant = require("../models/merchant.js");
 const Feedback = require("../models/feedback.js");
 
 const bcrypt = require("bcryptjs");
@@ -13,19 +14,22 @@ module.exports = {
     Redirects to /dashboard
     */
     login: function(req, res){
-        Owner.findOne({email: req.body.email.toLowerCase()})
-            .then((owner)=>{
-                if(owner !== null){
-                    bcrypt.compare(req.body.password, owner.password, async (err, result)=>{
+        let owner = Owner.findOne({email: req.body.email.toLowerCase()});
+        let merchant = Merchant.findOne({_id: req.session.merchant});
+
+        Promise.all([owner, merchant])
+            .then((response)=>{
+                if(response[0] !== null){
+                    bcrypt.compare(req.body.password, response[0].password, async (err, result)=>{
                         if(result === true){
                             //Check if email has not been verified
-                            if(owner.status.includes("unverified")){
+                            if(response[0].status.includes("unverified")){
                                 req.session.error = "PLEASE VERIFY YOUR EMAIL ADDRESS";
-                                return res.redirect(`/verify/email/${owner._id}`);
+                                return res.redirect(`/verify/email/${response[0]._id}`);
                             }
 
                             //Check for suspended account
-                            if(owner.status.includes("suspended")){
+                            if(response[0].status.includes("suspended")){
                                 req.session.error = "ACCOUNT SUSPENDED. PLEASE CONTACT SUPPORT IF THIS IS IN ERROR";
                                 return res.redirect("/");
                             }
@@ -33,7 +37,7 @@ module.exports = {
                             //Check for out of date access token
                             let cutoff = new Date();
                             cutoff.setDate(cutoff.getDate() + 1);
-                            if(owner.square !== undefined && owner.square.expires < cutoff){
+                            if(response[0].square !== undefined && response[0].square.expires < cutoff){
                                 let data = await axios.post(`${process.env.SQUARE_ADDRESS}/oauth2/token`, {
                                     client_id: process.env.SUBLINE_SQUARE_APPID,
                                     client_secret: process.env.SUBLINE_SQUARE_APPSECRET,
@@ -41,13 +45,14 @@ module.exports = {
                                     refresh_token: merchant.square.refreshToken
                                 });
 
-                                owner.square.accessToken = data.data.access_token;
-                                owner.square.expires = new Date(data.data.expires_at);
+                                response[0].square.accessToken = data.data.access_token;
+                                response[0].square.expires = new Date(data.data.expires_at);
 
-                                await owner.save();
+                                await response[0].save();
                             }
 
-                            req.session.owner = owner.session.sessionId;
+                            req.session.merchant = (response[1] === null) ? await Merchant.findOne({_id: response[0].merchants[0]}) : response[1];
+                            req.session.owner = response[0].session.sessionId;
                             return res.redirect("/dashboard");
                         }else{
                             req.session.error = "INVALID EMAIL OR PASSWORD";

+ 15 - 12
controllers/renderer.js

@@ -29,9 +29,9 @@ module.exports = {
     Renders inventoryPage
     */
     displayDashboard: function(req, res){
-        if(res.locals.merchant.status.includes("unverified")) {
+        if(res.locals.owner.status.includes("unverified")) {
             req.session.error = "PLEASE VERIFY YOUR EMAIL ADDRESS";
-            return res.redirect(`/verify/email/${res.locals.merchant._id}`);
+            return res.redirect(`/verify/email/${res.locals.owner._id}`);
         }
 
         res.locals.merchant
@@ -44,7 +44,7 @@ module.exports = {
 
                 return Transaction.aggregate([
                     {$match: {
-                        merchant: new ObjectId(res.locals.merchant._id),
+                        merchant: new ObjectId(merchant._id),
                         date: {$gte: firstDay},
                     }},
                     {$sort: {date: -1}},
@@ -55,7 +55,7 @@ module.exports = {
                 ]);      
             })
             .then(async (transactions)=>{
-                if(res.locals.pos !== "none"){
+                if(res.locals.merchant.pos !== "none"){
                     let latest = null;
                     if(transactions.length === 0){
                         let latestTransaction = await Transaction.find({merchant: res.locals.merchant._id}).sort({date: -1}).limit(1);
@@ -69,7 +69,7 @@ module.exports = {
                         let now = new Date();
 
                         let postData = {
-                            location_ids: [res.locals.merchant.square.location],
+                            location_ids: [res.locals.merchant.locationId],
                             query: {
                                 filter: {
                                     date_time_filter: {
@@ -91,7 +91,7 @@ module.exports = {
                         };
 
                         do{
-                            let newOrders = await helper.getSquareData(res.locals.merchant, postData);
+                            let newOrders = await helper.getSquareData(res.locals.owner, res.locals.merchant, postData);
                             postData.cursor = newOrders.cursor;
                             for(let i = 0; i < newOrders.length; i++){
                                 for(let j = 0; j < newOrders[i].recipes.length; j++){
@@ -103,13 +103,16 @@ module.exports = {
                     }
                 }
 
-                res.locals.merchant._id = undefined;
-                res.locals.password = undefined;
-                res.locals.merchant.status = undefined;
-                res.locals.square = undefined;
-                res.locals.session = undefined;
+                res.locals.merchant.owner = undefined;
+                res.locals.createdAt = undefined;
+                
+                res.locals.owner.password = undefined;
+                res.locals.owner.status = undefined;
+                res.locals.owner.square = undefined;
+                res.locals.owner.createdAt = undefined;
+                res.locals.owner.session = undefined;
 
-                return res.render("dashboardPage/dashboard", {merchant: res.locals.merchant, transactions: transactions});
+                return res.render("dashboardPage/dashboard", {owner: res.locals.owner, merchant: res.locals.merchant, transactions: transactions});
             })
             .catch((err)=>{
                 req.session.error = "ERROR: UNABLE TO RETRIEVE DATA";

+ 1 - 1
controllers/squareData.js

@@ -123,7 +123,7 @@ module.exports = {
                     }
                 });
 
-                return Promise.all([items, location]);
+                return Promise.all([items, location, merchant.save()]);
             })
             .then((response)=>{
                 if(owner.email === response[1].data.location.business_email) merchant.status = [];

+ 2 - 1
middleware.js

@@ -1,4 +1,5 @@
 const Owner = require("./models/owner.js");
+const Merchant = require("./models/merchant.js");
 
 const helper = require("./controllers/helper.js");
 
@@ -14,7 +15,7 @@ module.exports = {
         Promise.all([owner, merchant])
             .then((response)=>{
                 if(response[0] === null || response[1] === null) throw "login";
-                if(response[0]._id !== response[1].owner) throw "login";
+                if(response[0]._id.toString() !== response[1].owner.toString()) throw "login";
     
                 //Check if session is out of date
                 if(response[0].session.expiration < new Date()){

+ 0 - 1
models/owner.js

@@ -23,7 +23,6 @@ const OwnerSchema = new mongoose.Schema({
         accessToken: String,
         expires: Date,
         refreshToken: String,
-        location: String
     },
     createdAt: {
         type: Date,

+ 1 - 0
views/dashboardPage/dashboard.ejs

@@ -55,6 +55,7 @@
 
         <script>
             let data = {
+                owner: <%- JSON.stringify(owner) %>,
                 merchant: <%- JSON.stringify(merchant) %>,
                 transactions: <%- JSON.stringify(transactions) %>
             }

+ 25 - 18
views/dashboardPage/js/classes/Merchant.js

@@ -77,40 +77,47 @@ class MerchantIngredient{
 }
 
 class Merchant{
-    constructor(oldMerchant, transactions){
-        this._name = oldMerchant.name;
-        this._email = oldMerchant.email;
-        this._pos = oldMerchant.pos;
+        constructor(
+            name,
+            email,
+            pos,
+            ingredients,
+            recipes,
+            transactions
+        ){
+        this._name = name;
+        this._email = email;
+        this._pos = pos;
         this._ingredients = [];
         this._recipes = [];
         this._transactions = [];
         this._orders = [];
         
         //populate ingredients
-        for(let i = 0; i < oldMerchant.inventory.length; i++){
+        for(let i = 0; i < ingredients.length; i++){
             const ingredient = new Ingredient(
-                oldMerchant.inventory[i].ingredient._id,
-                oldMerchant.inventory[i].ingredient.name,
-                oldMerchant.inventory[i].ingredient.category,
-                oldMerchant.inventory[i].ingredient.unitType,
-                oldMerchant.inventory[i].defaultUnit,
+                ingredients[i].ingredient._id,
+                ingredients[i].ingredient.name,
+                ingredients[i].ingredient.category,
+                ingredients[i].ingredient.unitType,
+                ingredients[i].defaultUnit,
                 this,
-                oldMerchant.inventory[i].ingredient.unitSize
+                ingredients[i].ingredient.unitSize
             );
 
             const merchantIngredient = new MerchantIngredient(
                 ingredient,
-                oldMerchant.inventory[i].quantity,
+                ingredients[i].quantity,
             );
 
             this._ingredients.push(merchantIngredient);
         }
 
         //populate recipes
-        for(let i = 0; i < oldMerchant.recipes.length; i++){
+        for(let i = 0; i < recipes.length; i++){
             let ingredients = [];
-            for(let j = 0; j < oldMerchant.recipes[i].ingredients.length; j++){
-                const ingredient = oldMerchant.recipes[i].ingredients[j];
+            for(let j = 0; j < recipes[i].ingredients.length; j++){
+                const ingredient = recipes[i].ingredients[j];
                 for(let k = 0; k < this._ingredients.length; k++){
                     if(ingredient.ingredient === this._ingredients[k].ingredient.id){
                         ingredients.push({
@@ -123,9 +130,9 @@ class Merchant{
             }
 
             this._recipes.push(new Recipe(
-                oldMerchant.recipes[i]._id,
-                oldMerchant.recipes[i].name,
-                oldMerchant.recipes[i].price,
+                recipes[i]._id,
+                recipes[i].name,
+                recipes[i].price,
                 ingredients,
                 this
             ));

+ 8 - 1
views/dashboardPage/js/dashboard.js

@@ -23,7 +23,14 @@ const modalScript = require("./modal.js");
 
 const Merchant = require("./classes/Merchant.js");
 
-merchant = new Merchant(data.merchant, data.transactions);
+window.merchant = new Merchant(
+    data.merchant.name,
+    date.owner.email,
+    data.merchant.pos,
+    data.merchant.inventory,
+    data.merchant.recipes,
+    data.transactions
+);
 
 controller = {
     openStrand: function(strand, data = undefined){