ingredientData.js 12 KB

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