ingredientData.js 12 KB

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