ingredientData.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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": locations.bottle = i; break;
  142. case "bottle size": locations.bottleSize = 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. });
  153. let merchantItem = {
  154. ingredient: ingredient,
  155. quantity: helper.convertQuantityToBaseUnit(array[i][locations.quantity], array[i][locations.unit]),
  156. defaultUnit: array[i][locations.unit]
  157. }
  158. if(array[i][locations.bottle] === true){
  159. let quantity = array[i][locations.quantity] * array[i][locations.bottleSize];
  160. merchantItem.quantity = helper.convertQuantityToBaseUnit(quantity, array[i][locations.unit]);
  161. ingredient.unitType = "volume";
  162. ingredient.specialUnit = "bottle";
  163. ingredient.unitSize = helper.convertQuantityToBaseUnit(array[i][locations.bottleSize], array[i][locations.unit]);
  164. }else{
  165. let unitType = "";
  166. //TODO: this should probably be in a helper
  167. switch(array[i][locations.unit].toLowerCase()){
  168. case "g": unitType = "mass"; break;
  169. case "kg": unitType = "mass"; break;
  170. case "oz": unitType = "mass"; break;
  171. case "lb": unitType = "mass"; break;
  172. case "ml": unitType = "volume"; break;
  173. case "l": unitType = "volume"; break;
  174. case "tsp": unitType = "volume"; break;
  175. case "tbsp": unitType = "volume"; break;
  176. case "ozfl": unitType = "volume"; break;
  177. case "cup": unitType = "volume"; break;
  178. case "pt": unitType = "volume"; break;
  179. case "qt": unitType = "volume"; break;
  180. case "gal": unitType = "volume"; break;
  181. case "mm": unitType = "length"; break;
  182. case "cm": unitType = "length"; break;
  183. case "m": unitType = "length"; break;
  184. case "in": unitType = "length"; break;
  185. case "ft": unitType = "length"; break;
  186. default: unitType = "other";
  187. }
  188. ingredient.unitType = unitType;
  189. }
  190. merchantData.push(merchantItem);
  191. ingredients.push(ingredient);
  192. }
  193. //Update the database
  194. Ingredient.create(ingredients)
  195. .then((ingredients)=>{
  196. return Merchant.findOne({_id: req.session.user});
  197. })
  198. .then((merchant)=>{
  199. for(let i = 0; i < merchantData.length; i++){
  200. merchant.inventory.push(merchantData[i]);
  201. }
  202. return merchant.save();
  203. })
  204. .then((merchant)=>{
  205. return res.json(merchantData);
  206. })
  207. .catch((err)=>{
  208. if(typeof(err) === "string"){
  209. return res.json(err);
  210. }
  211. if(err.name === "ValidationError"){
  212. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  213. }
  214. return "ERROR: UNABLE TO CREATE YOUR INGREDIENTS";
  215. });
  216. },
  217. spreadsheetTemplate: function(req, res){
  218. if(!req.session.user){
  219. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  220. return res.redirect("/");
  221. }
  222. let workbook = xlsx.utils.book_new();
  223. workbook.SheetNames.push("Ingredients");
  224. let workbookData = [];
  225. workbookData.push(["Name", "Category", "Quantity", "Unit", "Bottle Size", "Bottle Unit"]);
  226. workbookData.push(["Example Ingredient 1", "Produce", 100, "lbs"]);
  227. workbookData.push(["Example Ingredient 2", "Fruit", 3.24, "kg"]);
  228. workbookData.push(["Example Ingredient 3", "Beverage", 5, "bottle", 750, "ml"]);
  229. workbook.Sheets.Ingredients = xlsx.utils.aoa_to_sheet(workbookData);
  230. xlsx.writeFile(workbook, "SublineIngredients.xlsx");
  231. return res.download("SublineIngredients.xlsx", (err)=>{
  232. fs.unlink("SublineIngredients.xlsx", ()=>{});
  233. });
  234. },
  235. //DELETE - Removes an ingredient from the merchant's inventory
  236. removeIngredient: function(req, res){
  237. if(!req.session.user){
  238. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  239. return res.redirect("/");
  240. }
  241. Merchant.findOne({_id: req.session.user})
  242. .then((merchant)=>{
  243. for(let i = 0; i < merchant.inventory.length; i++){
  244. if(req.params.id === merchant.inventory[i].ingredient._id.toString()){
  245. merchant.inventory.splice(i, 1);
  246. break;
  247. }
  248. }
  249. return Promise.all([merchant.save(), Ingredient.deleteOne({_id: req.params.id})]);
  250. })
  251. .then((response)=>{
  252. return res.json({});
  253. })
  254. .catch((err)=>{
  255. if(typeof(err) === "string"){
  256. return res.json(err);
  257. }
  258. if(err.name === "ValidationError"){
  259. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  260. }
  261. return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
  262. });
  263. },
  264. }