ingredientData.js 10 KB

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