ingredientData.js 9.8 KB

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