ingredientData.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. if(!req.session.user){
  63. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  64. return res.redirect("/");
  65. }
  66. let updatedIngredient = {};
  67. Ingredient.findOne({_id: req.body.id})
  68. .then((ingredient)=>{
  69. ingredient.name = req.body.name,
  70. ingredient.category = req.body.category
  71. return ingredient.save();
  72. })
  73. .then((ingredient)=>{
  74. updatedIngredient.ingredient = ingredient;
  75. return Merchant.findOne({_id: req.session.user});
  76. })
  77. .then((merchant)=>{
  78. for(let i = 0; i < merchant.inventory.length; i++){
  79. if(merchant.inventory[i].ingredient.toString() === req.body.id){
  80. merchant.inventory[i].defaultUnit = req.body.unit;
  81. if(merchant.inventory[i].quantity !== req.body.quantity){
  82. new InventoryAdjustment({
  83. date: new Date(),
  84. merchant: req.session.user,
  85. ingredient: req.body.id,
  86. quantity: req.body.quantity - merchant.inventory[i].quantity
  87. }).save().catch(()=>{});
  88. merchant.inventory[i].quantity = req.body.quantity;
  89. }
  90. updatedIngredient.quantity = helper.convertQuantityToBaseUnit(req.body.quantity, req.body.unit);
  91. updatedIngredient.unit = req.body.unit;
  92. break;
  93. }
  94. }
  95. return merchant.save();
  96. })
  97. .then((merchant)=>{
  98. return res.json(updatedIngredient);
  99. })
  100. .catch((err)=>{
  101. if(typeof(err) === "string"){
  102. return res.json(err);
  103. }
  104. if(err.name === "ValidationError"){
  105. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  106. }
  107. return res.json("ERROR: UNABLE TO UDATE THE INGREDIENT");
  108. });
  109. },
  110. createFromSpreadsheet: function(req, res){
  111. if(!req.session.user){
  112. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  113. return res.redirect("/");
  114. }
  115. //read file, get the correct sheet, create array from sheet
  116. let workbook = xlsx.readFile(req.file.path);
  117. fs.unlink(req.file.path, ()=>{});
  118. let sheets = Object.keys(workbook.Sheets);
  119. let sheet = {};
  120. for(let i = 0; i < sheets.length; i++){
  121. let str = sheets[i].toLowerCase();
  122. if(str === "ingredient" || str === "ingredients"){
  123. sheet = workbook.Sheets[sheets[i]];
  124. }
  125. }
  126. const array = xlsx.utils.sheet_to_json(sheet, {
  127. header: 1
  128. });
  129. //get property locations
  130. let locations = {};
  131. for(let i = 0; i < array[0].length; i++){
  132. switch(array[0][i].toLowerCase()){
  133. case "name": locations.name = i; break;
  134. case "category": locations.category = i; break;
  135. case "quantity": locations.quantity = i; break;
  136. case "unit": locations.unit = i; break;
  137. case "bottle size": locations.bottleSize = i; break;
  138. case "bottle unit": locations.bottleUnit = i; break;
  139. }
  140. }
  141. //Create ingredients
  142. let ingredients = [];
  143. let merchantData = [];
  144. for(let i = 1; i < array.length; i++){
  145. let ingredient = new Ingredient({
  146. name: array[i][locations.name],
  147. category: array[i][locations.category],
  148. unitType: helper.getUnitType(array[i][locations.unit].toLowerCase())
  149. });
  150. if(array[i][locations.unit] === "bottle"){
  151. ingredient.unitType = array[i][locations.bottleUnit];
  152. ingredient.unitSize = helper.convertQuantityToBaseUnit(array[i][locations.bottleSize], array[i][locations.bottleUnit]);
  153. }
  154. let merchantItem = {
  155. ingredient: ingredient,
  156. quantity: helper.convertQuantityToBaseUnit(array[i][locations.quantity], array[i][locations.unit]),
  157. defaultUnit: array[i][locations.unit]
  158. }
  159. merchantData.push(merchantItem);
  160. ingredients.push(ingredient);
  161. }
  162. //Update the database
  163. Merchant.findOne({_id: req.session.user})
  164. .then((merchant)=>{
  165. for(let i = 0; i < merchantData.length; i++){
  166. merchant.inventory.push(merchantData[i]);
  167. }
  168. return Promise.all([Ingredient.create(ingredients), merchant.save()]);
  169. })
  170. .then((response)=>{
  171. return res.json(merchantData);
  172. })
  173. .catch((err)=>{
  174. if(typeof(err) === "string"){
  175. return res.json(err);
  176. }
  177. if(err.name === "ValidationError"){
  178. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  179. }
  180. return "ERROR: UNABLE TO CREATE YOUR INGREDIENTS";
  181. });
  182. },
  183. spreadsheetTemplate: function(req, res){
  184. if(!req.session.user){
  185. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  186. return res.redirect("/");
  187. }
  188. let workbook = xlsx.utils.book_new();
  189. workbook.SheetNames.push("Ingredients");
  190. let workbookData = [];
  191. workbookData.push(["Name", "Category", "Quantity", "Unit", "Bottle Size", "Bottle Unit"]);
  192. workbookData.push(["Example Ingredient 1", "Produce", 100, "lbs"]);
  193. workbookData.push(["Example Ingredient 2", "Fruit", 3.24, "kg"]);
  194. workbookData.push(["Example Ingredient 3", "Beverage", 5, "bottle", 750, "ml"]);
  195. workbook.Sheets.Ingredients = xlsx.utils.aoa_to_sheet(workbookData);
  196. xlsx.writeFile(workbook, "SublineIngredients.xlsx");
  197. return res.download("SublineIngredients.xlsx", (err)=>{
  198. fs.unlink("SublineIngredients.xlsx", ()=>{});
  199. });
  200. },
  201. //DELETE - Removes an ingredient from the merchant's inventory
  202. removeIngredient: function(req, res){
  203. if(!req.session.user){
  204. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  205. return res.redirect("/");
  206. }
  207. Merchant.findOne({_id: req.session.user})
  208. .then((merchant)=>{
  209. for(let i = 0; i < merchant.inventory.length; i++){
  210. if(req.params.id === merchant.inventory[i].ingredient._id.toString()){
  211. merchant.inventory.splice(i, 1);
  212. break;
  213. }
  214. }
  215. return Promise.all([merchant.save(), Ingredient.deleteOne({_id: req.params.id})]);
  216. })
  217. .then((response)=>{
  218. return res.json({});
  219. })
  220. .catch((err)=>{
  221. if(typeof(err) === "string"){
  222. return res.json(err);
  223. }
  224. if(err.name === "ValidationError"){
  225. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  226. }
  227. return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
  228. });
  229. }
  230. }