ingredientData.js 9.6 KB

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