transactionData.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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. return res.json("ERROR: UNABLE TO RETRIEVE DATA");
  107. });
  108. },
  109. /*
  110. POST - create a new transaction
  111. req.body = {
  112. date: date of the transaction,
  113. recipes: [{
  114. recipe: id of the recipe to add,
  115. quantity: quantity of the recipe sold (in main unit),
  116. }]
  117. ingredientUpdates: an object that contains all of the ingredients that
  118. need to be updated as well as the amount to change.
  119. keys = id
  120. values = quantity to change in grams
  121. }
  122. */
  123. createTransaction: function(req, res){
  124. if(!req.session.user){
  125. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  126. return res.redirect("/");
  127. }
  128. let newTransaction = new Transaction({
  129. merchant: req.session.user,
  130. date: new Date(req.body.date),
  131. device: "none",
  132. recipes: req.body.recipes
  133. });
  134. helper.updateIngredientQuantities(req.body.ingredientUpdates, req.session.user);
  135. newTransaction.save()
  136. .then((response)=>{
  137. return res.json(response);
  138. })
  139. .catch((err)=>{
  140. if(typeof(err) === "string"){
  141. return res.json(err);
  142. }
  143. if(err.name === "ValidationError"){
  144. return res.json(err.errors.name.properties.message);
  145. }
  146. return res.json("ERROR: UNABLE TO CREATE NEW TRANSACTION");
  147. });
  148. },
  149. /*
  150. DELETE - Remove a transaction from the database
  151. */
  152. remove: function(req, res){
  153. if(!req.session.user){
  154. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  155. return res.redirect("/");
  156. }
  157. let merchant = {};
  158. let transaction = {};
  159. Merchant.findOne({_id: req.session.user})
  160. .then((response)=>{
  161. merchant = response;
  162. return Transaction.findOne({_id: req.params.id}).populate("recipes.recipe");
  163. })
  164. .then((response)=>{
  165. transaction = response;
  166. return Transaction.deleteOne({_id: req.params.id});
  167. })
  168. .then((response)=>{
  169. res.json();
  170. for(let i = 0; i < transaction.recipes.length; i++){
  171. const recipe = transaction.recipes[i].recipe;
  172. for(let j = 0; j < recipe.ingredients.length; j++){
  173. const ingredient = recipe.ingredients[j].ingredient;
  174. for(let k = 0; k < merchant.inventory.length; k++){
  175. if(ingredient.toString() === merchant.inventory[k].ingredient.toString()){
  176. merchant.inventory[k].quantity += recipe.ingredients[j].quantity * transaction.recipes[i].quantity;
  177. break;
  178. }
  179. }
  180. }
  181. }
  182. return merchant.save();
  183. })
  184. .catch((err)=>{
  185. if(typeof(err) === "string"){
  186. return res.json(err);
  187. }
  188. if(err.name === "ValidationError"){
  189. return res.json(err.errors.name.properties.message);
  190. }
  191. return res.json("ERROR: UNABLE TO DELETE THE TRANSACTION");
  192. });
  193. },
  194. /*
  195. GET - Creates 5000 transactions for logged in merchant for testing
  196. */
  197. populate: function(req, res){
  198. if(!req.session.user){
  199. res.session.error = "Must be logged in to do that";
  200. return res.redirect("/");
  201. }
  202. function randomDate() {
  203. let now = new Date();
  204. let start = new Date();
  205. start.setFullYear(now.getFullYear() - 1);
  206. return new Date(start.getTime() + Math.random() * (now.getTime() - start.getTime()));
  207. }
  208. Merchant.findOne({_id: req.session.user})
  209. .then((merchant)=>{
  210. let newTransactions = [];
  211. for(let i = 0; i < 5000; i++){
  212. let newTransaction = new Transaction({
  213. merchant: merchant._id,
  214. date: randomDate(),
  215. recipes: []
  216. });
  217. let numberOfRecipes = Math.floor((Math.random() * 5) + 1);
  218. for(let j = 0; j < numberOfRecipes; j++){
  219. let recipeNumber = Math.floor(Math.random() * merchant.recipes.length);
  220. let randQuantity = Math.floor((Math.random() * 3) + 1);
  221. newTransaction.recipes.push({
  222. recipe: merchant.recipes[recipeNumber],
  223. quantity: randQuantity
  224. });
  225. }
  226. newTransactions.push(newTransaction);
  227. }
  228. Transaction.create(newTransactions)
  229. .then((transactions)=>{
  230. return res.redirect("/dashboard");
  231. })
  232. .catch((err)=>{
  233. return;
  234. });
  235. })
  236. .catch((err)=>{
  237. return;
  238. });
  239. }
  240. }