transactionData.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. const Transaction = require("../models/transaction");
  2. const Merchant = require("../models/merchant");
  3. const helper = require("./helper.js");
  4. const ObjectId = require("mongoose").Types.ObjectId;
  5. module.exports = {
  6. /*
  7. POST - retrieves a list of transactions based on the filter
  8. req.body = {
  9. startDate: starting date to filter on,
  10. endDate: ending date to filter on,
  11. recipes: list of recipes to filter on
  12. }
  13. NOTE: May be a good idea to search recipes with for looping rather than query
  14. Needs some testing and playing with if so
  15. */
  16. getTransactions: function(req, res){
  17. if(!req.session.user){
  18. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  19. return res.redirect("/");
  20. }
  21. let objectifiedRecipes = [];
  22. for(let i = 0; i < req.body.recipes.length; i++){
  23. objectifiedRecipes.push(new ObjectId(req.body.recipes[i]));
  24. }
  25. let startDate = new Date(req.body.startDate);
  26. let endDate = new Date(req.body.endDate);
  27. endDate.setDate(endDate.getDate() + 1);
  28. Transaction.aggregate([
  29. {$match: {
  30. merchant: ObjectId(req.session.user),
  31. date: {
  32. $gte: startDate,
  33. $lt: endDate
  34. },
  35. recipes: {
  36. $elemMatch: {
  37. recipe: {
  38. $in: objectifiedRecipes
  39. }
  40. }
  41. }
  42. }},
  43. {$sort: {date: -1}}
  44. ])
  45. .then((transactions)=>{
  46. return res.json(transactions);
  47. })
  48. .catch((err)=>{
  49. return res.json("ERROR: UNABLE TO RETRIEVE YOUR TRANSACTIONS");
  50. });
  51. },
  52. /*
  53. GET - get transactions between two dates, sorted and group by date
  54. params:
  55. from: Date string
  56. to: Date string
  57. return:
  58. [{
  59. date: Date
  60. transactions:[[Recipe]]
  61. }]
  62. */
  63. getTransactionsByDate: function(req, res){
  64. if(!req.session.user){
  65. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  66. return res.redirect("/");
  67. }
  68. const from = new Date(req.params.from);
  69. const to = new Date(req.params.to);
  70. to.setDate(to.getDate() + 1);
  71. Transaction.aggregate([
  72. {$match: {
  73. merchant: ObjectId(req.session.user),
  74. date: {
  75. $gte: from,
  76. $lt: to
  77. }
  78. }},
  79. {$group: {
  80. _id: {$function: {
  81. body: "function(year, month, date){return `${year}-${month}-${date}`;}",
  82. args: [{$year: "$date"}, {$month: "$date"}, {$dayOfMonth: "$date"}],
  83. lang: "js"
  84. }},
  85. transactions: {$push: {
  86. _id: "$_id",
  87. recipes: "$recipes"
  88. }}
  89. }},
  90. {$project: {
  91. _id: 0,
  92. date: {$convert: {
  93. input: "$_id",
  94. to: "date"
  95. }},
  96. transactions: 1
  97. }},
  98. {$sort: {
  99. date: 1
  100. }}
  101. ])
  102. .then((transactions)=>{
  103. return res.json(transactions);
  104. })
  105. .catch((err)=>{
  106. console.log(err);
  107. return res.json("ERROR: UNABLE TO RETRIEVE DATA");
  108. });
  109. },
  110. /*
  111. POST - create a new transaction
  112. req.body = {
  113. date: date of the transaction,
  114. recipes: [{
  115. recipe: id of the recipe to add,
  116. quantity: quantity of the recipe sold (in main unit),
  117. }]
  118. ingredientUpdates: an object that contains all of the ingredients that
  119. need to be updated as well as the amount to change.
  120. keys = id
  121. values = quantity to change in grams
  122. }
  123. */
  124. createTransaction: function(req, res){
  125. if(!req.session.user){
  126. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  127. return res.redirect("/");
  128. }
  129. let newTransaction = new Transaction({
  130. merchant: req.session.user,
  131. date: new Date(req.body.date),
  132. device: "none",
  133. recipes: req.body.recipes
  134. });
  135. helper.updateIngredientQuantities(req.body.ingredientUpdates, req.session.user);
  136. newTransaction.save()
  137. .then((response)=>{
  138. return res.json(response);
  139. })
  140. .catch((err)=>{
  141. return res.json("ERROR: UNABLE TO CREATE NEW TRANSACTION");
  142. });
  143. },
  144. /*
  145. DELETE - Remove a transaction from the database
  146. */
  147. remove: function(req, res){
  148. if(!req.session.user){
  149. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  150. return res.redirect("/");
  151. }
  152. let merchant = {};
  153. let transaction = {};
  154. Merchant.findOne({_id: req.session.user})
  155. .then((response)=>{
  156. merchant = response;
  157. return Transaction.findOne({_id: req.params.id}).populate("recipes.recipe");
  158. })
  159. .then((response)=>{
  160. transaction = response;
  161. return Transaction.deleteOne({_id: req.params.id});
  162. })
  163. .then((response)=>{
  164. res.json();
  165. for(let i = 0; i < transaction.recipes.length; i++){
  166. const recipe = transaction.recipes[i].recipe;
  167. for(let j = 0; j < recipe.ingredients.length; j++){
  168. const ingredient = recipe.ingredients[j].ingredient;
  169. for(let k = 0; k < merchant.inventory.length; k++){
  170. if(ingredient.toString() === merchant.inventory[k].ingredient.toString()){
  171. merchant.inventory[k].quantity += recipe.ingredients[j].quantity * transaction.recipes[i].quantity;
  172. break;
  173. }
  174. }
  175. }
  176. }
  177. return merchant.save();
  178. })
  179. .catch((err)=>{
  180. return res.json("ERROR: UNABLE TO DELETE THE TRANSACTION");
  181. });
  182. },
  183. /*
  184. GET - Creates 5000 transactions for logged in merchant for testing
  185. */
  186. populate: function(req, res){
  187. if(!req.session.user){
  188. res.session.error = "Must be logged in to do that";
  189. return res.redirect("/");
  190. }
  191. function randomDate() {
  192. let now = new Date();
  193. let start = new Date();
  194. start.setFullYear(now.getFullYear() - 1);
  195. return new Date(start.getTime() + Math.random() * (now.getTime() - start.getTime()));
  196. }
  197. Merchant.findOne({_id: req.session.user})
  198. .then((merchant)=>{
  199. let newTransactions = [];
  200. for(let i = 0; i < 5000; i++){
  201. let newTransaction = new Transaction({
  202. merchant: merchant._id,
  203. date: randomDate(),
  204. recipes: []
  205. });
  206. let numberOfRecipes = Math.floor((Math.random() * 5) + 1);
  207. for(let j = 0; j < numberOfRecipes; j++){
  208. let recipeNumber = Math.floor(Math.random() * merchant.recipes.length);
  209. let randQuantity = Math.floor((Math.random() * 3) + 1);
  210. newTransaction.recipes.push({
  211. recipe: merchant.recipes[recipeNumber],
  212. quantity: randQuantity
  213. });
  214. }
  215. newTransactions.push(newTransaction);
  216. }
  217. Transaction.create(newTransactions)
  218. .then((transactions)=>{
  219. return res.redirect("/dashboard");
  220. })
  221. .catch((err)=>{
  222. return;
  223. });
  224. })
  225. .catch((err)=>{
  226. return;
  227. });
  228. }
  229. }