Sfoglia il codice sorgente

Add square stuff back into code.
Fix all data for registering a new square user.

Lee Morgan 5 anni fa
parent
commit
b9b0e4bb98
4 ha cambiato i file con 162 aggiunte e 7 eliminazioni
  1. 152 0
      controllers/squareData.js
  2. 1 4
      models/merchant.js
  3. 6 0
      routes.js
  4. 3 3
      views/otherPages/register.ejs

+ 152 - 0
controllers/squareData.js

@@ -0,0 +1,152 @@
+const Merchant = require("../models/merchant.js");
+const Recipe = require("../models/recipe.js");
+
+const axios = require("axios");
+const helper = require("./helper.js");
+
+module.exports = {
+    //GET - Redirects user to Square OAuth page
+    redirect: function(req, res){
+        return res.redirect(`${process.env.SQUARE_ADDRESS}/oauth2/authorize?client_id=${process.env.SUBLINE_SQUARE_APPID}&scope=INVENTORY_READ+ITEMS_READ+MERCHANT_PROFILE_READ+ORDERS_READ+PAYMENTS_READ`);
+    },
+
+    authorize: function(req, res){
+        const code = req.url.slice(req.url.indexOf("code=") + 5, req.url.indexOf("&"));
+        const url = `${process.env.SQUARE_ADDRESS}/oauth2/token?`;
+        let data = {
+            client_id: process.env.SUBLINE_SQUARE_APPID,
+            client_secret: process.env.SUBLINE_SQUARE_APPSECRET,
+            grant_type: "authorization_code",
+            code: code
+        };
+    
+        axios.post(url, data)
+            .then((response)=>{
+                data = response.data;
+                return Merchant.findOne({posId: data.merchant_id});
+            })
+            .then((merchant)=>{
+                if(merchant){
+                    merchant.posAccessToken = data.access_token;
+    
+                    return merchant.save()
+                        .then((merchant)=>{
+                            req.session.user = merchant._id;
+                            return res.redirect("/dashboard");
+                        })
+                        .catch((err)=>{
+                            req.session.error = "ERROR: UNABLE TO CREATE NEW USER";
+                            return res.redirect("/");
+                        })
+                }else{
+                    req.session.merchantId = data.merchant_id;
+                    req.session.accessToken = data.access_token;
+    
+                    return res.redirect("/merchant/create/square");
+                }
+            })
+            .catch((err)=>{
+                req.session.error = "ERROR: UNABLE TO RETRIEVE DATA FROM SQUARE";
+                return res.redirect("/");
+            });
+    },
+
+    createMerchant: function(req, res){
+        let merchant = {}
+    
+        axios.get(`${process.env.SQUARE_ADDRESS}/v2/merchants/${req.session.merchantId}`, {
+            headers: {
+                Authorization: `Bearer ${req.session.accessToken}`
+            }
+        })
+            .then((response)=>{
+                req.session.merchantId = undefined;
+
+                let expirationDate = new Date();
+                expirationDate.setDate(expirationDate.getDate() + 90);
+    
+                merchant = new Merchant({
+                    name: response.data.merchant.business_name,
+                    pos: "square",
+                    posId: response.data.merchant.id,
+                    posAccessToken: req.session.accessToken,
+                    lastUpdatedTime: new Date(),
+                    createdAt: new Date(),
+                    squareLocation: response.data.merchant.main_location_id,
+                    status: [],
+                    inventory: [],
+                    recipes: [],
+                    session: {
+                        sessionId: helper.generateId(25),
+                        expiration: expirationDate
+                    }
+                });
+
+                req.session.accessToken = undefined;
+
+                let items = axios.post(`${process.env.SQUARE_ADDRESS}/v2/catalog/search`, {
+                    object_types: ["ITEM"]
+                }, {
+                    headers: {
+                        Authorization: `Bearer ${merchant.posAccessToken}`
+                    }
+                });
+
+                let location = axios.get(`${process.env.SQUARE_ADDRESS}/v2/locations/${response.data.merchant.main_location_id}`, {
+                    headers: {
+                        Authorization: `Bearer ${merchant.posAccessToken}`
+                    }
+                });
+
+                return Promise.all([items, location]);
+            })
+            .then((response)=>{
+                merchant.email = response[1].data.location.business_email;
+                let recipes = [];
+                
+                for(let i = 0; i < response[0].data.objects.length; i++){
+                    if(response[0].data.objects[i].item_data.variations.length > 1){
+                        for(let j = 0; j < response[0].data.objects[i].item_data.variations.length; j++){
+                            let recipe = new Recipe({
+                                posId: response[0].data.objects[i].item_data.variations[j].id,
+                                merchant: merchant._id,
+                                name: `${response[0].data.objects[i].item_data.name} '${response[0].data.objects[i].item_data.variations[j].item_variation_data.name}'`,
+                                price: response[0].data.objects[i].item_data.variations[j].item_variation_data.price_money.amount
+                            });
+    
+                            recipes.push(recipe);
+                            merchant.recipes.push(recipe);
+                        }
+                    }else{
+                        let recipe = new Recipe({
+                            posId: response[0].data.objects[i].item_data.variations[0].id,
+                            merchant: merchant._id,
+                            name: response[0].data.objects[i].item_data.name,
+                            price: response[0].data.objects[i].item_data.variations[0].item_variation_data.price_money.amount,
+                            ingredients: []
+                        });
+    
+                        recipes.push(recipe);
+                        merchant.recipes.push(recipe);
+                    }
+                }
+    
+                return Promise.all([Recipe.create(recipes), merchant.save()]);
+            })
+            .then((response)=>{
+                req.session.user = response[1].session.sessionId;
+    
+                return res.redirect("/dashboard");
+            })
+            .catch((err)=>{
+                if(typeof(err) === "string"){
+                    req.session.error = err;
+                }else if(err.name === "ValidationError"){
+                    req.session.error = err.errors[Object.keys(err.errors)[0]].properties.message;
+                }else{
+                    req.session.error = "ERROR: UNABLE TO CREATE NEW USER";
+                }
+                return res.redirect("/");
+            });
+    },
+}

+ 1 - 4
models/merchant.js

@@ -24,10 +24,7 @@ const MerchantSchema = new mongoose.Schema({
         },
         index: true
     },
-    password: {
-        type: String,
-        required: [true, "MUST PROVIDE A PASSWORD"],
-    },
+    password: String,
     pos: {
         type: String,
         required: true

+ 6 - 0
routes.js

@@ -8,6 +8,7 @@ const orderData = require("./controllers/orderData.js");
 const informationPages = require("./controllers/informationPages.js");
 const emailVerification = require("./controllers/emailVerification.js");
 const passwordReset = require("./controllers/passwordReset.js");
+const squareData = require("./controllers/squareData.js");
 
 const session = require("./middleware.js").verifySession;
 const banner = require("./middleware.js").formatBanner;
@@ -78,4 +79,9 @@ module.exports = function(app){
     app.post("/reset/email", passwordReset.generateCode);
     app.get("/reset/:id/:code", banner, passwordReset.enterPassword);
     app.post("/reset", passwordReset.resetPassword);
+
+    //Square
+    app.get("/squarelogin", squareData.redirect);
+    app.get("/squareauth", squareData.authorize);
+    app.get("/merchant/create/square", squareData.createMerchant);
 }

+ 3 - 3
views/otherPages/register.ejs

@@ -50,11 +50,11 @@
 
             <input class="buttonDisabled" type="submit" value="Sign Up with Email">
 
-            <!-- <h1>OR</h1>
+            <h1>OR</h1>
 
-            <a class="button buttonWithBorder" href="/cloverlogin">Sign Up with Clover</a>
+            <!-- <a class="button buttonWithBorder" href="/cloverlogin">Sign Up with Clover</a> -->
 
-            <a class="button buttonWithBorder" href="/squarelogin">Sign Up with Square</a> -->
+            <a class="button buttonWithBorder" href="/squarelogin">Sign Up with Square</a>
 
             <a class="link" href="/login">Already have an account? Please Sign In</a>
         </form>