admin.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const Merchant = require("../models/merchant.js");
  2. const Ingredient = require("../models/ingredient.js");
  3. const helper = require("./helper.js");
  4. const fs = require("fs");
  5. module.exports = {
  6. /*
  7. POST: Adding data for admins
  8. req.body = {
  9. password: String
  10. id: String <merchant id>
  11. }
  12. req.files = {
  13. ingredients: txt
  14. recipes: txt
  15. }
  16. */
  17. addData: function(req, res){
  18. if(req.body.password !== process.env.ADMIN_PASS) return res.json("bad password");
  19. Merchant.findOne({_id: req.body.id})
  20. .then((merchant)=>{
  21. //Ingredients
  22. let newIngredients = [];
  23. if(req.files.ingredients !== undefined){
  24. let ingredientData = fs.readFileSync(req.files.ingredients.tempFilePath).toString();
  25. fs.unlink(req.files.ingredients.tempFilePath, ()=>{});
  26. ingredientData = ingredientData.split("\n");
  27. merchant.inventory = [];
  28. for(let i = 0; i < ingredientData.length; i++){
  29. if(ingredientData[i] === "") continue;
  30. let data = ingredientData[i].split(",");
  31. let ingredient = new Ingredient({
  32. name: data[0],
  33. category: data[1],
  34. unitType: helper.getUnitType(data[3]),
  35. ingredients: []
  36. });
  37. let merchIngredient = {
  38. ingredient: ingredient._id,
  39. quantity: helper.convertQuantityToBaseUnit(data[2], data[3]),
  40. defaultUnit: data[3]
  41. };
  42. if(data[3].toLowerCase() === "bottle"){
  43. ingredient.unitType = data[5];
  44. ingredient.unitSize = helper.convertQuantityToBaseUnit(data[4], data[5])
  45. merchIngredient.defaultUnit = "bottle";
  46. }
  47. newIngredients.push(ingredient);
  48. merchant.inventory.push(merchIngredient);
  49. }
  50. }
  51. return Promise.all([
  52. merchant.save(),
  53. Ingredient.create(newIngredients)
  54. ]);
  55. })
  56. .then((response)=>{
  57. return res.redirect("/dashboard");
  58. })
  59. .catch((err)=>{
  60. console.log(err);
  61. return res.json("ERROR: A whoopsie has been made");
  62. });
  63. }
  64. }