transactionData.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. const Transaction = require("../models/transaction");
  2. const Merchant = require("../models/merchant");
  3. module.exports = {
  4. /*
  5. GET - Creates 5000 transactions for logged in merchant for testing
  6. */
  7. populate: function(req, res){
  8. if(!req.session.user){
  9. res.session.error = "Must be logged in to do that";
  10. return res.redirect("/");
  11. }
  12. function randomDate() {
  13. let now = new Date();
  14. let start = new Date();
  15. start.setFullYear(now.getFullYear() - 1);
  16. return new Date(start.getTime() + Math.random() * (now.getTime() - start.getTime()));
  17. }
  18. Merchant.findOne({_id: req.session.user})
  19. .then((merchant)=>{
  20. let newTransactions = [];
  21. for(let i = 0; i < 5000; i++){
  22. let newTransaction = new Transaction({
  23. merchant: merchant._id,
  24. date: randomDate(),
  25. recipes: []
  26. });
  27. let numberOfRecipes = Math.floor((Math.random() * 5) + 1);
  28. for(let j = 0; j < numberOfRecipes; j++){
  29. let recipeNumber = Math.floor(Math.random() * merchant.recipes.length);
  30. let randQuantity = Math.floor((Math.random() * 3) + 1);
  31. newTransaction.recipes.push({
  32. recipe: merchant.recipes[recipeNumber],
  33. quantity: randQuantity
  34. });
  35. }
  36. newTransactions.push(newTransaction);
  37. }
  38. Transaction.create(newTransactions)
  39. .then((transactions)=>{
  40. return res.redirect("/dashboard");
  41. })
  42. .catch((err)=>{
  43. return;
  44. });
  45. })
  46. .catch((err)=>{
  47. return;
  48. });
  49. },
  50. /*
  51. DELETE - Remove a transaction from the database
  52. */
  53. remove: function(req, res){
  54. if(!req.session.user){
  55. req.session.error = "Must be logged in to do that";
  56. return res.redirect("/");
  57. }
  58. Transaction.deleteOne({_id: req.params.id})
  59. .then((response)=>{
  60. return res.json({});
  61. })
  62. .catch((err)=>{
  63. return res.json("Error: unable to delete the transaction");
  64. });
  65. }
  66. }