ingredientData.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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.name.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.name.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. ingredient.unitType = "volume";
  178. ingredient.specialUnit = "bottle";
  179. ingredient.unitSize = helper.convertQuantityToBaseUnit(array[i][locations.bottleSize], array[i][locations.unit]);
  180. }else{
  181. let unitType = "";
  182. //TODO: this should probably be in a helper
  183. switch(array[i][locations.unit].toLowerCase()){
  184. case "g": unitType = "mass"; break;
  185. case "kg": unitType = "mass"; break;
  186. case "oz": unitType = "mass"; break;
  187. case "lb": unitType = "mass"; break;
  188. case "ml": unitType = "volume"; break;
  189. case "l": unitType = "volume"; break;
  190. case "tsp": unitType = "volume"; break;
  191. case "tbsp": unitType = "volume"; break;
  192. case "ozfl": unitType = "volume"; break;
  193. case "cup": unitType = "volume"; break;
  194. case "pt": unitType = "volume"; break;
  195. case "qt": unitType = "volume"; break;
  196. case "gal": unitType = "volume"; break;
  197. case "mm": unitType = "length"; break;
  198. case "cm": unitType = "length"; break;
  199. case "m": unitType = "length"; break;
  200. case "in": unitType = "length"; break;
  201. case "ft": unitType = "length"; break;
  202. default: unitType = "other";
  203. }
  204. ingredient.unitType = unitType;
  205. }
  206. merchantData.push(merchantItem);
  207. ingredients.push(ingredient);
  208. }
  209. //Update the database
  210. Ingredient.create(ingredients)
  211. .then((ingredients)=>{
  212. return Merchant.findOne({_id: req.session.user});
  213. })
  214. .then((merchant)=>{
  215. for(let i = 0; i < merchantData.length; i++){
  216. merchant.inventory.push(merchantData[i]);
  217. }
  218. return merchant.save();
  219. })
  220. .then((merchant)=>{
  221. return res.json(merchantData);
  222. })
  223. .catch((err)=>{
  224. if(typeof(err) === "string"){
  225. return res.json(err);
  226. }
  227. if(err.name === "ValidationError"){
  228. return res.json(err.errors.name.properties.message);
  229. }
  230. return "ERROR: UNABLE TO CREATE YOUR INGREDIENTS";
  231. });
  232. },
  233. spreadsheetTemplate: function(req, res){
  234. if(!req.session.user){
  235. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  236. return res.redirect("/");
  237. }
  238. let workbook = xlsx.utils.book_new();
  239. workbook.SheetNames.push("Ingredients");
  240. let workbookData = [];
  241. workbookData.push(["Name", "Category", "Quantity", "Unit", "Bottle", "Bottle Size"]);
  242. workbookData.push(["Example Ingredient 1", "Produce", 100, "lbs"]);
  243. workbookData.push(["Example Ingredient Two", "Beverage", 5, "ml", "TRUE", 750]);
  244. workbook.Sheets.Ingredients = xlsx.utils.aoa_to_sheet(workbookData);
  245. xlsx.writeFile(workbook, "SublineIngredients.xlsx");
  246. return res.download("SublineIngredients.xlsx", (err)=>{
  247. fs.unlink("SublineIngredients.xlsx", ()=>{});
  248. });
  249. },
  250. //DELETE - Removes an ingredient from the merchant's inventory
  251. removeIngredient: function(req, res){
  252. if(!req.session.user){
  253. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  254. return res.redirect("/");
  255. }
  256. Merchant.findOne({_id: req.session.user})
  257. .then((merchant)=>{
  258. for(let i = 0; i < merchant.inventory.length; i++){
  259. if(req.params.id === merchant.inventory[i].ingredient._id.toString()){
  260. merchant.inventory.splice(i, 1);
  261. break;
  262. }
  263. }
  264. return merchant.save()
  265. })
  266. .then((merchant)=>{
  267. return Ingredient.deleteOne({_id: req.params.id});
  268. })
  269. .then((ingredient)=>{
  270. return res.json({});
  271. })
  272. .catch((err)=>{
  273. if(typeof(err) === "string"){
  274. return res.json(err);
  275. }
  276. if(err.name === "ValidationError"){
  277. return res.json(err.errors.name.properties.message);
  278. }
  279. return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
  280. });
  281. },
  282. }