ingredientData.js 9.9 KB

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