ingredientData.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. const Ingredient = require("../models/ingredient");
  2. const helper = require("./helper.js");
  3. const xlsx = require("xlsx");
  4. const fs = require("fs");
  5. module.exports = {
  6. /*
  7. POST - create a single ingredient and then add to the merchant
  8. req.body = {
  9. ingredient: {
  10. name: name of ingredient,
  11. category: category of ingredient,
  12. convert: {
  13. toMass: Number
  14. toVolume: Number
  15. toLength: Number
  16. }
  17. unit: String
  18. }
  19. quantity: quantity of ingredient for current merchant,
  20. }
  21. Returns:
  22. Same as above, with the _id
  23. */
  24. createIngredient: function(req, res){
  25. let newIngredient = new Ingredient({
  26. name: req.body.ingredient.name,
  27. category: req.body.ingredient.category,
  28. unit: req.body.ingredient.unit,
  29. convert: req.body.ingredient.category,
  30. ingredients: []
  31. })
  32. newIngredient.save()
  33. .then((ingredient)=>{
  34. newIngredient = {
  35. ingredient: ingredient._id,
  36. quantity: req.body.quantity,
  37. }
  38. res.locals.merchant.inventory.push(newIngredient);
  39. return res.locals.merchant.save();
  40. })
  41. .then((response)=>{
  42. return res.json(newIngredient);
  43. })
  44. .catch((err)=>{
  45. if(typeof(err) === "string") return res.json(err);
  46. if(err.name === "ValidationError"){
  47. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  48. }
  49. return res.json("ERROR: UNABLE TO CREATE THE INGREDIENT");
  50. });
  51. },
  52. /*
  53. PUT: Updates data for a single ingredient
  54. req.body = {
  55. ingredient: {
  56. id: String (id of Ingredient)
  57. name: String
  58. category: String
  59. unit: String
  60. convert: {
  61. toMass: Number
  62. toVolume: Number
  63. toLength: Number
  64. }
  65. }
  66. quantity: Number
  67. }
  68. response = Ingredient
  69. */
  70. updateIngredient: function(req, res){
  71. Ingredient.findOne({_id: req.body.id})
  72. .then((ingredient)=>{
  73. ingredient.name = req.body.ingredient.name;
  74. ingredient.category = req.body.ingredient.category;
  75. ingredient.convert = req.body.ingredient.convert;
  76. ingredient.unit = req.body.ingredient.unit;
  77. //find and update ingredient on merchant
  78. for(let i = 0; i < res.locals.merchant.inventory.length; i++){
  79. if(res.locals.merchant.inventory[i].ingredient.toString() === req.body.id){
  80. res.locals.merchant.inventory[i].quantity = req.body.quantity;
  81. break;
  82. }
  83. }
  84. return Promise.all([ingredient.save(), res.locals.merchant.save()])
  85. })
  86. .then((response)=>{
  87. return res.json({
  88. ingredient: response[0],
  89. quantity: req.body.quantity,
  90. });
  91. })
  92. .catch((err)=>{
  93. if(err.name === "ValidationError"){
  94. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  95. }
  96. return res.json("ERROR: UNABLE TO UPDATE DATA");
  97. });
  98. },
  99. /*
  100. PUT: updates subingredients on an ingredient
  101. req.body = {
  102. id: String (top-level ingredient id),
  103. ingredients: [{
  104. ingredient: String (id)
  105. quantity: Number
  106. }]
  107. }
  108. response = Ingredient
  109. error response = '$' delimited String
  110. */
  111. updateSubIngredients: function(req, res){
  112. let popMerchant = res.locals.merchant.populate("inventory.ingredient").execPopulate();
  113. let stack = [];
  114. Promise.all([Ingredient.findOne({_id: req.body.id}), popMerchant])
  115. .then((response)=>{
  116. response[0].ingredients = req.body.ingredients;
  117. // Check ingredients for circular references
  118. let isCircular = (ingredient, original)=>{
  119. if(ingredient.ingredients.length === 0) {
  120. stack.pop();
  121. return false;
  122. }
  123. for(let i = 0; i < ingredient.ingredients.length; i++){
  124. for(let j = 0; j < res.locals.merchant.inventory.length; j++){
  125. if(res.locals.merchant.inventory[j].ingredient._id.toString() === ingredient.ingredients[i].ingredient.toString()){
  126. let next = res.locals.merchant.inventory[j].ingredient;
  127. stack.push(next);
  128. if(next._id.toString() === original._id.toString()) return true;
  129. return isCircular(next, original);
  130. }
  131. }
  132. }
  133. }
  134. for(let i = 0; i < req.body.ingredients.length; i++){
  135. for(let j = 0; j < res.locals.merchant.inventory.length; j++){
  136. if(res.locals.merchant.inventory[j].ingredient._id.toString() === req.body.ingredients[i].ingredient){
  137. let ingredient = res.locals.merchant.inventory[j].ingredient;
  138. stack = [ingredient];
  139. if(ingredient._id.toString() === req.body.id) throw "circular";
  140. if(isCircular(ingredient, response[0]) === true) throw "circular";
  141. break;
  142. }
  143. }
  144. }
  145. return Promise.all([response[0].save(), res.locals.merchant.save()])
  146. })
  147. .then((response)=>{
  148. return res.json(response[0]);
  149. })
  150. .catch((err)=>{
  151. if(err === "circular"){
  152. let string = "YOU ATTEMPTED TO MAKE A CIRCULAR REFERENCE";
  153. if(stack.length === 1){
  154. string += `$${stack[0].name} CONTAINS ${stack[0].name}`;
  155. }else{
  156. for(let i = 0; i < stack.length; i++){
  157. if(i === stack.length - 1){
  158. string += `$${stack[i].name} CONTAINS ${stack[0].name}`;
  159. break;
  160. }
  161. string += `$${stack[i].name} CONTAINS ${stack[i+1].name}`;
  162. }
  163. }
  164. return res.json(string);
  165. }
  166. return res.json("ERROR: UNABLE TO UPDATE YOUR SUB-INGREDIENTS");
  167. });
  168. },
  169. createFromSpreadsheet: function(req, res){
  170. //read file, get the correct sheet, create array from sheet
  171. let workbook = xlsx.readFile(req.file.path);
  172. fs.unlink(req.file.path, ()=>{});
  173. let sheets = Object.keys(workbook.Sheets);
  174. let sheet = {};
  175. for(let i = 0; i < sheets.length; i++){
  176. let str = sheets[i].toLowerCase();
  177. if(str === "ingredient" || str === "ingredients"){
  178. sheet = workbook.Sheets[sheets[i]];
  179. }
  180. }
  181. const array = xlsx.utils.sheet_to_json(sheet, {
  182. header: 1
  183. });
  184. //get property locations
  185. let locations = {};
  186. for(let i = 0; i < array[0].length; i++){
  187. switch(array[0][i].toLowerCase()){
  188. case "name": locations.name = i; break;
  189. case "category": locations.category = i; break;
  190. case "quantity": locations.quantity = i; break;
  191. case "unit": locations.unit = i; break;
  192. case "bottle size": locations.bottleSize = i; break;
  193. case "bottle unit": locations.bottleUnit = i; break;
  194. }
  195. }
  196. //Create ingredients
  197. let ingredients = [];
  198. let merchantData = [];
  199. for(let i = 1; i < array.length; i++){
  200. let ingredient = new Ingredient({
  201. name: array[i][locations.name],
  202. category: array[i][locations.category],
  203. unitType: helper.getUnitType(array[i][locations.unit].toLowerCase())
  204. });
  205. if(array[i][locations.unit] === "bottle"){
  206. ingredient.unitType = array[i][locations.bottleUnit];
  207. ingredient.unitSize = helper.convertQuantityToBaseUnit(array[i][locations.bottleSize], array[i][locations.bottleUnit]);
  208. }
  209. let merchantItem = {
  210. ingredient: ingredient,
  211. quantity: helper.convertQuantityToBaseUnit(array[i][locations.quantity], array[i][locations.unit]),
  212. defaultUnit: array[i][locations.unit]
  213. }
  214. merchantData.push(merchantItem);
  215. ingredients.push(ingredient);
  216. }
  217. for(let i = 0; i < merchantData.length; i++){
  218. res.locals.merchant.inventory.push(merchantData[i]);
  219. }
  220. //Update the database
  221. Promise.all([Ingredient.create(ingredients), res.locals.merchant.save()])
  222. .then((response)=>{
  223. return res.json(merchantData);
  224. })
  225. .catch((err)=>{
  226. if(typeof(err) === "string"){
  227. return res.json(err);
  228. }
  229. if(err.name === "ValidationError"){
  230. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  231. }
  232. return "ERROR: UNABLE TO CREATE YOUR INGREDIENTS";
  233. });
  234. },
  235. spreadsheetTemplate: function(req, res){
  236. let workbook = xlsx.utils.book_new();
  237. workbook.SheetNames.push("Ingredients");
  238. let workbookData = [];
  239. workbookData.push(["Name", "Category", "Quantity", "Unit", "Bottle Size", "Bottle Unit"]);
  240. workbookData.push(["Example Ingredient 1", "Produce", 100, "lbs"]);
  241. workbookData.push(["Example Ingredient 2", "Fruit", 3.24, "kg"]);
  242. workbookData.push(["Example Ingredient 3", "Beverage", 5, "bottle", 750, "ml"]);
  243. workbook.Sheets.Ingredients = xlsx.utils.aoa_to_sheet(workbookData);
  244. xlsx.writeFile(workbook, "SublineIngredients.xlsx");
  245. return res.download("SublineIngredients.xlsx", (err)=>{
  246. fs.unlink("SublineIngredients.xlsx", ()=>{});
  247. });
  248. },
  249. //DELETE - Removes an ingredient from the merchant's inventory
  250. removeIngredient: function(req, res){
  251. for(let i = 0; i < res.locals.merchant.inventory.length; i++){
  252. if(req.params.id === res.locals.merchant.inventory[i].ingredient._id.toString()){
  253. res.locals.merchant.inventory.splice(i, 1);
  254. break;
  255. }
  256. }
  257. Promise.all([res.locals.merchant.save(), Ingredient.deleteOne({_id: req.params.id})])
  258. .then((response)=>{
  259. return res.json({});
  260. })
  261. .catch((err)=>{
  262. if(typeof(err) === "string"){
  263. return res.json(err);
  264. }
  265. if(err.name === "ValidationError"){
  266. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  267. }
  268. return res.json("ERROR: UNABLE TO RETRIEVE DATA");
  269. });
  270. }
  271. }