ingredientData.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. const Merchant = require("../models/merchant");
  2. const Ingredient = require("../models/ingredient");
  3. const InventoryAdjustment = require("../models/inventoryAdjustment.js");
  4. const helper = require("./helper.js");
  5. const xlsx = require("xlsx");
  6. const fs = require("fs");
  7. module.exports = {
  8. /*
  9. POST - create a single ingredient and then add to the merchant
  10. req.body = {
  11. ingredient: {
  12. name: name of ingredient,
  13. category: category of ingredient,
  14. unitType: category for the unit (mass, volume, length)
  15. },
  16. quantity: quantity of ingredient for current merchant,
  17. defaultUnit: default unit of measurement to display
  18. }
  19. Returns:
  20. Same as above, with the _id
  21. */
  22. createIngredient: function(req, res){
  23. let newIngredient = {...req.body};
  24. if(req.body.defaultUnit === "bottle"){
  25. newIngredient.ingredient.unitSize = helper.convertQuantityToBaseUnit(newIngredient.ingredient.unitSize, newIngredient.ingredient.unitType);
  26. }
  27. newIngredient = new Ingredient(newIngredient.ingredient);
  28. newIngredient.save()
  29. .then((ingredient)=>{
  30. newIngredient = {
  31. ingredient: ingredient,
  32. defaultUnit: req.body.defaultUnit
  33. }
  34. newIngredient.quantity = helper.convertQuantityToBaseUnit(req.body.quantity, req.body.defaultUnit);
  35. res.locals.merchant.inventory.push(newIngredient);
  36. return res.locals.merchant.save();
  37. })
  38. .then((response)=>{
  39. return res.json(newIngredient);
  40. })
  41. .catch((err)=>{
  42. if(typeof(err) === "string"){
  43. return res.json(err);
  44. }
  45. if(err.name === "ValidationError"){
  46. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  47. }
  48. return res.json("ERROR: UNABLE TO CREATE THE INGREDIENT");
  49. });
  50. },
  51. /*
  52. POST - Updates data for a single ingredient
  53. req.body = {
  54. id: id of the ingredient,
  55. name: new name of the ingredient,
  56. quantity: new quantity of the unit (in grams),
  57. category: new category of the unit,
  58. unit: new default unit of the ingredient,
  59. }
  60. */
  61. updateIngredient: function(req, res){
  62. Ingredient.findOne({_id: req.body.id})
  63. .then((ingredient)=>{
  64. ingredient.name = req.body.name,
  65. ingredient.category = req.body.category
  66. return ingredient.save();
  67. })
  68. .then((ingredient)=>{
  69. let updatedIngredient = {};
  70. for(let i = 0; i < res.locals.merchant.inventory.length; i++){
  71. if(res.locals.merchant.inventory[i].ingredient.toString() === req.body.id){
  72. res.locals.merchant.inventory[i].defaultUnit = req.body.unit;
  73. if(res.locals.merchant.inventory[i].quantity !== req.body.quantity){
  74. new InventoryAdjustment({
  75. date: new Date(),
  76. merchant: req.session.user,
  77. ingredient: req.body.id,
  78. quantity: req.body.quantity - res.locals.merchant.inventory[i].quantity
  79. }).save().catch(()=>{});
  80. res.locals.merchant.inventory[i].quantity = req.body.quantity;
  81. }
  82. updatedIngredient = {
  83. ingredient: ingredient,
  84. quantity: helper.convertQuantityToBaseUnit(req.body.quantity, req.body.unit),
  85. unit: req.body.unit
  86. }
  87. break;
  88. }
  89. }
  90. res.locals.merchant.save().catch((err)=>{throw err});
  91. return res.json(updatedIngredient);
  92. })
  93. .catch((err)=>{
  94. if(typeof(err) === "string"){
  95. return res.json(err);
  96. }
  97. if(err.name === "ValidationError"){
  98. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  99. }
  100. return res.json("ERROR: UNABLE TO UPDATE THE INGREDIENT");
  101. });
  102. },
  103. createFromSpreadsheet: function(req, res){
  104. //read file, get the correct sheet, create array from sheet
  105. let workbook = xlsx.readFile(req.file.path);
  106. fs.unlink(req.file.path, ()=>{});
  107. let sheets = Object.keys(workbook.Sheets);
  108. let sheet = {};
  109. for(let i = 0; i < sheets.length; i++){
  110. let str = sheets[i].toLowerCase();
  111. if(str === "ingredient" || str === "ingredients"){
  112. sheet = workbook.Sheets[sheets[i]];
  113. }
  114. }
  115. const array = xlsx.utils.sheet_to_json(sheet, {
  116. header: 1
  117. });
  118. //get property locations
  119. let locations = {};
  120. for(let i = 0; i < array[0].length; i++){
  121. switch(array[0][i].toLowerCase()){
  122. case "name": locations.name = i; break;
  123. case "category": locations.category = i; break;
  124. case "quantity": locations.quantity = i; break;
  125. case "unit": locations.unit = i; break;
  126. case "bottle size": locations.bottleSize = i; break;
  127. case "bottle unit": locations.bottleUnit = i; break;
  128. }
  129. }
  130. //Create ingredients
  131. let ingredients = [];
  132. let merchantData = [];
  133. for(let i = 1; i < array.length; i++){
  134. let ingredient = new Ingredient({
  135. name: array[i][locations.name],
  136. category: array[i][locations.category],
  137. unitType: helper.getUnitType(array[i][locations.unit].toLowerCase())
  138. });
  139. if(array[i][locations.unit] === "bottle"){
  140. ingredient.unitType = array[i][locations.bottleUnit];
  141. ingredient.unitSize = helper.convertQuantityToBaseUnit(array[i][locations.bottleSize], array[i][locations.bottleUnit]);
  142. }
  143. let merchantItem = {
  144. ingredient: ingredient,
  145. quantity: helper.convertQuantityToBaseUnit(array[i][locations.quantity], array[i][locations.unit]),
  146. defaultUnit: array[i][locations.unit]
  147. }
  148. merchantData.push(merchantItem);
  149. ingredients.push(ingredient);
  150. }
  151. for(let i = 0; i < merchantData.length; i++){
  152. res.locals.merchant.inventory.push(merchantData[i]);
  153. }
  154. //Update the database
  155. Promise.all([Ingredient.create(ingredients), res.locals.merchant.save()])
  156. .then((response)=>{
  157. return res.json(merchantData);
  158. })
  159. .catch((err)=>{
  160. if(typeof(err) === "string"){
  161. return res.json(err);
  162. }
  163. if(err.name === "ValidationError"){
  164. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  165. }
  166. return "ERROR: UNABLE TO CREATE YOUR INGREDIENTS";
  167. });
  168. },
  169. spreadsheetTemplate: function(req, res){
  170. let workbook = xlsx.utils.book_new();
  171. workbook.SheetNames.push("Ingredients");
  172. let workbookData = [];
  173. workbookData.push(["Name", "Category", "Quantity", "Unit", "Bottle Size", "Bottle Unit"]);
  174. workbookData.push(["Example Ingredient 1", "Produce", 100, "lbs"]);
  175. workbookData.push(["Example Ingredient 2", "Fruit", 3.24, "kg"]);
  176. workbookData.push(["Example Ingredient 3", "Beverage", 5, "bottle", 750, "ml"]);
  177. workbook.Sheets.Ingredients = xlsx.utils.aoa_to_sheet(workbookData);
  178. xlsx.writeFile(workbook, "SublineIngredients.xlsx");
  179. return res.download("SublineIngredients.xlsx", (err)=>{
  180. fs.unlink("SublineIngredients.xlsx", ()=>{});
  181. });
  182. },
  183. //DELETE - Removes an ingredient from the merchant's inventory
  184. removeIngredient: function(req, res){
  185. if(!req.session.user){
  186. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  187. return res.redirect("/");
  188. }
  189. Merchant.findOne({_id: req.session.user})
  190. .then((merchant)=>{
  191. for(let i = 0; i < merchant.inventory.length; i++){
  192. if(req.params.id === merchant.inventory[i].ingredient._id.toString()){
  193. merchant.inventory.splice(i, 1);
  194. break;
  195. }
  196. }
  197. return Promise.all([merchant.save(), Ingredient.deleteOne({_id: req.params.id})]);
  198. })
  199. .then((response)=>{
  200. return res.json({});
  201. })
  202. .catch((err)=>{
  203. if(typeof(err) === "string"){
  204. return res.json(err);
  205. }
  206. if(err.name === "ValidationError"){
  207. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  208. }
  209. return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
  210. });
  211. }
  212. }