ingredientData.js 12 KB

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