transactionData.js 8.9 KB

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