ingredientData.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. const Merchant = require("../models/merchant");
  2. const Ingredient = require("../models/ingredient");
  3. const InventoryAdjustment = require("../models/inventoryAdjustment.js");
  4. const helper = require("./helper.js");
  5. const xlsx = require("xlsx");
  6. const fs = require("fs");
  7. module.exports = {
  8. /*
  9. POST - create a single ingredient and then add to the merchant
  10. req.body = {
  11. ingredient: {
  12. name: name of ingredient,
  13. category: category of ingredient,
  14. unitType: category for the unit (mass, volume, length)
  15. },
  16. quantity: quantity of ingredient for current merchant,
  17. defaultUnit: default unit of measurement to display
  18. }
  19. Returns:
  20. Same as above, with the _id
  21. */
  22. createIngredient: function(req, res){
  23. if(!req.session.user){
  24. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  25. return res.redirect("/");
  26. }
  27. let newIngredient = {};
  28. if(req.body.ingredient.specialUnit === "bottle"){
  29. newIngredient = new Ingredient({
  30. name: req.body.ingredient.name,
  31. category: req.body.ingredient.category,
  32. unitType: req.body.ingredient.unitType,
  33. specialUnit: req.body.ingredient.specialUnit,
  34. unitSize: helper.convertQuantityToBaseUnit(req.body.ingredient.unitSize, req.body.defaultUnit)
  35. });
  36. }else{
  37. newIngredient = new Ingredient(req.body.ingredient);
  38. }
  39. let ingredientPromise = newIngredient.save();
  40. let merchantPromise = Merchant.findOne({_id: req.session.user});
  41. Promise.all([ingredientPromise, merchantPromise])
  42. .then((response)=>{
  43. newIngredient = {
  44. ingredient: response[0],
  45. defaultUnit: req.body.defaultUnit
  46. }
  47. if(response[0].specialUnit === "bottle"){
  48. newIngredient.quantity = req.body.quantity * response[0].unitSize;
  49. }else{
  50. newIngredient.quantity = helper.convertQuantityToBaseUnit(req.body.quantity, req.body.defaultUnit);
  51. }
  52. response[1].inventory.push(newIngredient);
  53. return response[1].save();
  54. })
  55. .then((response)=>{
  56. return res.json(newIngredient);
  57. })
  58. .catch((err)=>{
  59. if(typeof(err) === "string"){
  60. return res.json(err);
  61. }
  62. if(err.name === "ValidationError"){
  63. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  64. }
  65. return res.json("ERROR: UNABLE TO CREATE THE INGREDIENT");
  66. });
  67. },
  68. /*
  69. POST - Updates data for a single ingredient
  70. req.body = {
  71. id: id of the ingredient,
  72. name: new name of the ingredient,
  73. quantity: new quantity of the unit (in grams),
  74. category: new category of the unit,
  75. unit: new default unit of the ingredient,
  76. unitSize: unit size for special unit, if any
  77. }
  78. */
  79. updateIngredient: function(req, res){
  80. if(!req.session.user){
  81. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  82. return res.redirect("/");
  83. }
  84. let updatedIngredient = {};
  85. Ingredient.findOne({_id: req.body.id})
  86. .then((ingredient)=>{
  87. ingredient.name = req.body.name,
  88. ingredient.category = req.body.category
  89. //TODO: Handle this in the class
  90. if(ingredient.specialUnit === "bottle"){
  91. ingredient.unitSize = req.body.unitSize;
  92. }
  93. return ingredient.save();
  94. })
  95. .then((ingredient)=>{
  96. updatedIngredient.ingredient = ingredient;
  97. return Merchant.findOne({_id: req.session.user});
  98. })
  99. .then((merchant)=>{
  100. for(let i = 0; i < merchant.inventory.length; i++){
  101. if(merchant.inventory[i].ingredient.toString() === req.body.id){
  102. merchant.inventory[i].defaultUnit = req.body.unit;
  103. if(merchant.inventory[i].quantity !== req.body.quantity){
  104. new InventoryAdjustment({
  105. date: new Date(),
  106. merchant: req.session.user,
  107. ingredient: req.body.id,
  108. quantity: req.body.quantity - merchant.inventory[i].quantity
  109. }).save().catch(()=>{});
  110. merchant.inventory[i].quantity = req.body.quantity;
  111. }
  112. updatedIngredient.quantity = helper.convertQuantityToBaseUnit(req.body.quantity, req.body.unit);
  113. updatedIngredient.unit = req.body.unit;
  114. break;
  115. }
  116. }
  117. return merchant.save();
  118. })
  119. .then((merchant)=>{
  120. return res.json(updatedIngredient);
  121. })
  122. .catch((err)=>{
  123. if(typeof(err) === "string"){
  124. return res.json(err);
  125. }
  126. if(err.name === "ValidationError"){
  127. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  128. }
  129. return res.json("ERROR: UNABLE TO UDATE THE INGREDIENT");
  130. });
  131. },
  132. createFromSpreadsheet: function(req, res){
  133. if(!req.session.user){
  134. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  135. return res.redirect("/");
  136. }
  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": locations.bottle = i; break;
  160. case "bottle size": locations.bottleSize = 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. });
  171. let merchantItem = {
  172. ingredient: ingredient,
  173. quantity: helper.convertQuantityToBaseUnit(array[i][locations.quantity], array[i][locations.unit]),
  174. defaultUnit: array[i][locations.unit]
  175. }
  176. if(array[i][locations.bottle] === true){
  177. let quantity = array[i][locations.quantity] * array[i][locations.bottleSize];
  178. merchantItem.quantity = helper.convertQuantityToBaseUnit(quantity, array[i][locations.unit]);
  179. ingredient.unitType = "volume";
  180. ingredient.specialUnit = "bottle";
  181. ingredient.unitSize = helper.convertQuantityToBaseUnit(array[i][locations.bottleSize], array[i][locations.unit]);
  182. }else{
  183. let unitType = "";
  184. //TODO: this should probably be in a helper
  185. switch(array[i][locations.unit].toLowerCase()){
  186. case "g": unitType = "mass"; break;
  187. case "kg": unitType = "mass"; break;
  188. case "oz": unitType = "mass"; break;
  189. case "lb": unitType = "mass"; break;
  190. case "ml": unitType = "volume"; break;
  191. case "l": unitType = "volume"; break;
  192. case "tsp": unitType = "volume"; break;
  193. case "tbsp": unitType = "volume"; break;
  194. case "ozfl": unitType = "volume"; break;
  195. case "cup": unitType = "volume"; break;
  196. case "pt": unitType = "volume"; break;
  197. case "qt": unitType = "volume"; break;
  198. case "gal": unitType = "volume"; break;
  199. case "mm": unitType = "length"; break;
  200. case "cm": unitType = "length"; break;
  201. case "m": unitType = "length"; break;
  202. case "in": unitType = "length"; break;
  203. case "ft": unitType = "length"; break;
  204. default: unitType = "other";
  205. }
  206. ingredient.unitType = unitType;
  207. }
  208. merchantData.push(merchantItem);
  209. ingredients.push(ingredient);
  210. }
  211. //Update the database
  212. Ingredient.create(ingredients)
  213. .then((ingredients)=>{
  214. return Merchant.findOne({_id: req.session.user});
  215. })
  216. .then((merchant)=>{
  217. for(let i = 0; i < merchantData.length; i++){
  218. merchant.inventory.push(merchantData[i]);
  219. }
  220. return merchant.save();
  221. })
  222. .then((merchant)=>{
  223. return res.json(merchantData);
  224. })
  225. .catch((err)=>{
  226. if(typeof(err) === "string"){
  227. return res.json(err);
  228. }
  229. if(err.name === "ValidationError"){
  230. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  231. }
  232. return "ERROR: UNABLE TO CREATE YOUR INGREDIENTS";
  233. });
  234. },
  235. spreadsheetTemplate: function(req, res){
  236. if(!req.session.user){
  237. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  238. return res.redirect("/");
  239. }
  240. let workbook = xlsx.utils.book_new();
  241. workbook.SheetNames.push("Ingredients");
  242. let workbookData = [];
  243. workbookData.push(["Name", "Category", "Quantity", "Unit", "Bottle", "Bottle Size"]);
  244. workbookData.push(["Example Ingredient 1", "Produce", 100, "lbs"]);
  245. workbookData.push(["Example Ingredient Two", "Beverage", 5, "ml", "TRUE", 750]);
  246. workbook.Sheets.Ingredients = xlsx.utils.aoa_to_sheet(workbookData);
  247. xlsx.writeFile(workbook, "SublineIngredients.xlsx");
  248. return res.download("SublineIngredients.xlsx", (err)=>{
  249. fs.unlink("SublineIngredients.xlsx", ()=>{});
  250. });
  251. },
  252. //DELETE - Removes an ingredient from the merchant's inventory
  253. removeIngredient: function(req, res){
  254. if(!req.session.user){
  255. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  256. return res.redirect("/");
  257. }
  258. Merchant.findOne({_id: req.session.user})
  259. .then((merchant)=>{
  260. for(let i = 0; i < merchant.inventory.length; i++){
  261. if(req.params.id === merchant.inventory[i].ingredient._id.toString()){
  262. merchant.inventory.splice(i, 1);
  263. break;
  264. }
  265. }
  266. return merchant.save()
  267. })
  268. .then((merchant)=>{
  269. return Ingredient.deleteOne({_id: req.params.id});
  270. })
  271. .then((ingredient)=>{
  272. return res.json({});
  273. })
  274. .catch((err)=>{
  275. if(typeof(err) === "string"){
  276. return res.json(err);
  277. }
  278. if(err.name === "ValidationError"){
  279. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  280. }
  281. return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
  282. });
  283. },
  284. }