ingredientData.js 12 KB

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