| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347 |
- const axios = require("axios");
- const bcrypt = require("bcryptjs");
- const mailgun = require("mailgun-js")({apiKey: process.env.MG_SUBLINE_APIKEY, domain: "mail.thesubline.net"});
- const Merchant = require("../models/merchant");
- const Recipe = require("../models/recipe");
- const InventoryAdjustment = require("../models/inventoryAdjustment");
- const Validator = require("./validator.js");
- const Helper = require("./helper.js");
- const WelcomeEmail = require("../emails/welcomeEmail.js");
- module.exports = {
- /*
- POST - Create a new merchant with no POS system
- req.body = {
- name: retaurant name,
- email: registration email,
- password: password,
- confirmPassword: confirmation password
- }
- Redirects to /dashboard
- */
- createMerchantNone: async function(req, res){
- let validation = await Validator.merchant(req.body);
- if(validation !== true){
- req.session.error = validation;
- return res.redirect("/");
- }
- if(req.body.password === req.body.confirmPassword){
- let salt = bcrypt.genSaltSync(10);
- let hash = bcrypt.hashSync(req.body.password, salt);
- let merchant = new Merchant({
- name: req.body.name,
- email: req.body.email.toLowerCase(),
- password: hash,
- pos: "none",
- lastUpdatedTime: Date.now(),
- createdAt: Date.now(),
- status: ["unverified"],
- inventory: [],
- recipes: [],
- verifyId: Helper.generateId(15)
- });
- merchant.save()
- .then((merchant)=>{
- req.session.user = merchant._id;
- const mail = merchant.email.split("@");
- const mailgunData = {
- from: "The Subline <clientsupport@thesubline.net>",
- to: merchant.email,
- subject: "Welcome to The Subline!",
- html: WelcomeEmail({
- name: merchant.name,
- link: `${process.env.SITE}/verify/${merchant.verifyId}/${mail[0]}`
- })
- }
- mailgun.messages().send(mailgunData, (err, body)=>{});
- const mailgunList = mailgun.lists("clientsupport@mail.thesubline.com");
- const memberData = {
- subscribed: true,
- address: merchant.email,
- name: merchant.name,
- vars: {}
- }
- mailgunList.members().create(memberData, (err, data)=>{});
- return res.redirect("/dashboard");
- })
- .catch((err)=>{
- req.session.error = "ERROR: UNABLE TO CREATE ACCOUNT AT THIS TIME";
- return res.redirect("/");
- });
- }else{
- req.session.error = "PASSWORDS DO NOT MATCH";
- return res.redirect("/");
- }
- },
- /*
- POST - Creates new Clover merchant
- Redirects to /dashboard
- */
- createMerchantClover: async function(req, res){
- axios.get(`${process.env.CLOVER_ADDRESS}/v3/merchants/${req.session.merchantId}?access_token=${req.session.accessToken}`)
- .then((response)=>{
- let merchant = new Merchant({
- name: response.data.name,
- pos: "clover",
- posId: req.session.merchantId,
- posAccessToken: req.session.accessToken,
- lastUpdatedTime: Date.now(),
- createdAt: Date.now(),
- inventory: [],
- recipes: []
- });
- axios.get(`${process.env.CLOVER_ADDRESS}/v3/merchants/${req.session.merchantId}/items?access_token=${req.session.accessToken}`)
- .then((response)=>{
- let recipes = [];
- for(let i = 0; i < response.data.elements.length; i++){
- let recipe = new Recipe({
- posId: response.data.elements[i].id,
- merchant: merchant,
- name: response.data.elements[i].name,
- price: response.data.elements[i].price,
- ingredients: []
- });
- recipes.push(recipe);
- merchant.recipes.push(recipe);
- }
- Recipe.create(recipes)
- .catch((err)=>{
- req.session.error = "ERROR: UNABLE TO CREATE YOUR RECIPES FROM CLOVER."
- })
- merchant.save()
- .then((newMerchant)=>{
- req.session.accessToken = undefined;
- req.session.user = newMerchant._id;
- return res.redirect("/dashboard");
- })
- .catch((err)=>{
- req.session.error = "ERROR: UNABLE TO SAVE DATA FROM CLOVER";
- return res.redirect("/");
- });
- })
- .catch((err)=>{
- req.session.error = "ERROR: UNABLE TO RETRIEVE DATA FROM CLOVER";
- return res.redirect("/");
- })
-
- })
- .catch((err)=>{
- req.session.error = "ERROR: UNABLE TO RETRIEVE DATA FROM CLOVER";
- return res.redirect("/");
- });
- },
- createMerchantSquare: 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;
- return 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,
- inventory: [],
- recipes: []
- });
- })
- .then((newMerchant)=>{
- req.session.accessToken = undefined;
- merchant = newMerchant;
-
- return axios.post(`${process.env.SQUARE_ADDRESS}/v2/catalog/search`, {
- object_types: ["ITEM"]
- }, {
- headers: {
- Authorization: `Bearer ${merchant.posAccessToken}`
- }
- });
- })
- .then((response)=>{
- let recipes = [];
-
- for(let i = 0; i < response.data.objects.length; i++){
- if(response.data.objects[i].item_data.variations.length > 1){
- for(let j = 0; j < response.data.objects[i].item_data.variations.length; j++){
- let recipe = new Recipe({
- posId: response.data.objects[i].item_data.variations[j].id,
- merchant: merchant._id,
- name: `${response.data.objects[i].item_data.name} '${response.data.objects[i].item_data.variations[j].item_variation_data.name}'`,
- price: response.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.data.objects[i].item_data.variations[0].id,
- merchant: merchant._id,
- name: response.data.objects[i].item_data.name,
- price: response.data.objects[i].item_data.variations[0].item_variation_data.price_money.amount,
- ingredients: []
- });
- recipes.push(recipe);
- merchant.recipes.push(recipe);
- }
- }
- return Recipe.create(recipes);
- })
- .then((recipes)=>{
- return merchant.save();
- })
- .then((merchant)=>{
- req.session.user = merchant._id;
- return res.redirect("/dashboard");
- })
- .catch((err)=>{
- banner.createError("ERROR: UNABLE TO CREATE NEW USER AT THIS TIME");
- });
- },
- //PUT - Update the default unit for a single ingredient
- ingredientDefaultUnit: function(req, res){
- if(!req.session.user){
- req.session.error = "MUST BE LOGGED IN TO DO THAT";
- return res.redirect("/");
- }
- Merchant.findOne({_id: req.session.user})
- .then((merchant)=>{
- for(let i = 0; i < merchant.inventory.length; i++){
- if(merchant.inventory[i].ingredient.toString() === req.params.id){
- merchant.inventory[i].defaultUnit =req.params.unit;
- }
- }
- return merchant.save()
- })
- .then((merchant)=>{
- return res.json({});
- })
- .catch((err)=>{
- return res.json("ERROR: UNABLE TO UPDATE DEFAULT UNIT");
- });
- },
- /*
- POST - Update the quantity for a merchant inventory item
- req.body = [{
- id: id of ingredient to update,
- quantity: change in quantity
- }]
- */
- updateMerchantIngredient: function(req, res){
- if(!req.session.user){
- req.session.error = "MUST BE LOGGED IN TO DO THAT";
- return res.redirect("/");
- }
- for(let i = 0; i < req.body.length; i++){
- let validation = Validator.quantity(req.body[i].quantity);
- if(validation !== true){
- return res.json(validation);
- }
- }
- let adjustments = [];
- Merchant.findOne({_id: req.session.user})
- .then((merchant)=>{
- for(let i = 0; i < req.body.length; i++){
- let updateIngredient;
- for(let j = 0; j < merchant.inventory.length; j++){
- if(merchant.inventory[j].ingredient.toString() === req.body[i].id){
- updateIngredient = merchant.inventory[j];
- break;
- }
- }
- adjustments.push(new InventoryAdjustment({
- date: Date.now(),
- merchant: req.session.user,
- ingredient: req.body[i].id,
- quantity: req.body[i].quantity - updateIngredient.quantity,
- }));
- updateIngredient.quantity = req.body[i].quantity;
- }
- return merchant.save();
- })
- .then((newMerchant)=>{
- res.json({});
- InventoryAdjustment.create(adjustments).catch(()=>{});
- return;
- })
- .catch((err)=>{
- return res.json("ERROR: UNABLE TO UPDATE DATA");
- });
- },
- /*
- POST - Changes the users password
- req.body = {
- pass: new password,
- confirmPass: new password confirmation,
- hash: hashed version of old password
- }
- */
- updatePassword: function(req, res){
- let validation = Validator.password(req.body.pass, req.body.confirmPass);
- if(validation !== true){
- return res.json(validation);
- }
- Merchant.findOne({password: req.body.hash})
- .then((merchant)=>{
- if(merchant){
- let salt = bcrypt.genSaltSync(10);
- let hash = bcrypt.hashSync(req.body.pass, salt);
- merchant.password = hash;
- return merchant.save();
- }else{
- req.session.error = "ERROR: UNABLE TO RETRIEVE USER DATA";
- return res.redirect("/");
- }
- })
- .then((merchant)=>{
- req.session.error = "PASSWORD SUCCESSFULLY RESET. PLEASE LOG IN";
- return res.redirect("/");
- })
- .catch((err)=>{});
- }
- }
|