ingredientData.js 11 KB

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