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