transactionData.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. POST - create a new transaction
  56. req.body = {
  57. date: date of the transaction,
  58. recipes: [{
  59. recipe: id of the recipe to add,
  60. quantity: quantity of the recipe sold (in main unit),
  61. }]
  62. ingredientUpdates: an object that contains all of the ingredients that
  63. need to be updated as well as the amount to change.
  64. keys = id
  65. values = quantity to change in grams
  66. }
  67. */
  68. createTransaction: function(req, res){
  69. if(!req.session.user){
  70. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  71. return res.redirect("/");
  72. }
  73. let newTransaction = new Transaction({
  74. merchant: req.session.user,
  75. date: new Date(req.body.date),
  76. device: "none",
  77. recipes: req.body.recipes
  78. });
  79. helper.updateIngredientQuantities(req.body.ingredientUpdates, req.session.user);
  80. newTransaction.save()
  81. .then((response)=>{
  82. return res.json(response);
  83. })
  84. .catch((err)=>{
  85. return res.json("ERROR: UNABLE TO CREATE NEW TRANSACTION");
  86. });
  87. },
  88. createFromSpreadsheet: function(req, res){
  89. if(!req.session.user){
  90. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  91. return res.redirect("/");
  92. }
  93. //read file, get the correct sheet, create array from sheet
  94. let workbook = xlsx.readFile(req.file.path);
  95. fs.unlink(req.file.path, ()=>{});
  96. let sheets = Object.keys(workbook.Sheets);
  97. let sheet = {};
  98. for(let i = 0; i < sheets.length; i++){
  99. let str = sheets[i].toLowerCase();
  100. if(str === "transaction" || str === "transactions"){
  101. sheet = workbook.Sheets[sheets[i]];
  102. }
  103. }
  104. const array = xlsx.utils.sheet_to_json(sheet, {
  105. header: 1
  106. });
  107. let locations = {};
  108. for(let i = 0; i < array[0].length; i++){
  109. switch(array[0][i].toLowerCase()){
  110. case "date": locations.date = i; break;
  111. case "recipes": locations.recipes = i; break;
  112. case "quantity": locations.quantity = i; break;
  113. }
  114. }
  115. Merchant.findOne({_id: req.session.user})
  116. .populate("recipes")
  117. .populate("inventory.ingredient")
  118. .then((merchant)=>{
  119. let transaction = new Transaction({
  120. merchant: req.session.user,
  121. recipes: []
  122. });
  123. if(array[1][0] === undefined){
  124. transaction.date = new Date(array[1][0]);
  125. }else{
  126. transaction.date = new Date();
  127. }
  128. let ingredients = [];
  129. for(let i = 1; i < array.length; i++){
  130. let exists = false;
  131. for(let j = 0; j < merchant.recipes.length; j++){
  132. if(merchant.recipes[j].name.toLowerCase() === array[i][locations.recipes]){
  133. transaction.recipes.push({
  134. recipe: merchant.recipes[j],
  135. quantity: array[i][locations.quantity]
  136. });
  137. for(let k = 0; k < merchant.recipes[j].ingredients.length; k++){
  138. ingredients.push({
  139. id: merchant.recipes[j].ingredients[k].ingredient,
  140. quantity: array[i][locations.quantity] * merchant.recipes[j].ingredients[k].quantity
  141. });
  142. }
  143. exists = true;
  144. break;
  145. }
  146. }
  147. if(exists !== true){
  148. throw `COULD NOT FIND RECIPE ${array[i][locations.recipes]}`;
  149. }
  150. }
  151. for(let i = 0; i < ingredients.length; i++){
  152. for(let j = 0; j < merchant.inventory.length; j++){
  153. if(merchant.inventory[j].ingredient._id.toString() === ingredients[i].id.toString()){
  154. merchant.inventory[j].quantity -= ingredients[i].quantity;
  155. break;
  156. }
  157. }
  158. }
  159. return Promise.all([transaction.save(), merchant.save()]);
  160. })
  161. .then((response)=>{
  162. return res.json(response[0]);
  163. })
  164. .catch((err)=>{
  165. if(typeof(err) === "string"){
  166. return res.json(err);
  167. }
  168. return res.json("ERROR: UNABLE TO CREATE YOUR TRANSACTION");
  169. });
  170. },
  171. spreadsheetTemplate: function(req, res){
  172. if(!req.session.user){
  173. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  174. return res.redirect("/");
  175. }
  176. Merchant.findOne({_id: req.session.user})
  177. .populate("recipes")
  178. .then((merchant)=>{
  179. let workbook = xlsx.utils.book_new();
  180. workbook.SheetNames.push("Transaction");
  181. let workbookData = [];
  182. workbookData.push(["Date", "Recipes", "Quantity", "", "Recipes Reference"]);
  183. for(let i = 0; i < merchant.recipes.length; i++){
  184. workbookData.push(["", "", "", "", merchant.recipes[i].name]);
  185. }
  186. workbookData[1][0] = "2020-02-29";
  187. workbookData[1][1] = "Example Recipe 1";
  188. workbookData[1][2] = 12;
  189. workbookData[2][1] = "Example Recipe 2";
  190. workbookData[2][2] = 7;
  191. workbook.Sheets.Transaction = xlsx.utils.aoa_to_sheet(workbookData);
  192. xlsx.writeFile(workbook, "SublineTransaction.xlsx");
  193. return res.download("SublineTransaction.xlsx", (err)=>{
  194. fs.unlink("SublineTransaction.xlsx", ()=>{});
  195. });
  196. })
  197. .catch((err)=>{});
  198. },
  199. /*
  200. DELETE - Remove a transaction from the database
  201. */
  202. remove: function(req, res){
  203. if(!req.session.user){
  204. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  205. return res.redirect("/");
  206. }
  207. let merchant = {};
  208. let transaction = {};
  209. Merchant.findOne({_id: req.session.user})
  210. .then((response)=>{
  211. merchant = response;
  212. return Transaction.findOne({_id: req.params.id}).populate("recipes.recipe");
  213. })
  214. .then((response)=>{
  215. transaction = response;
  216. return Transaction.deleteOne({_id: req.params.id});
  217. })
  218. .then((response)=>{
  219. res.json();
  220. for(let i = 0; i < transaction.recipes.length; i++){
  221. const recipe = transaction.recipes[i].recipe;
  222. for(let j = 0; j < recipe.ingredients.length; j++){
  223. const ingredient = recipe.ingredients[j].ingredient;
  224. for(let k = 0; k < merchant.inventory.length; k++){
  225. if(ingredient.toString() === merchant.inventory[k].ingredient.toString()){
  226. merchant.inventory[k].quantity += recipe.ingredients[j].quantity * transaction.recipes[i].quantity;
  227. break;
  228. }
  229. }
  230. }
  231. }
  232. return merchant.save();
  233. })
  234. .catch((err)=>{
  235. return res.json("ERROR: UNABLE TO DELETE THE TRANSACTION");
  236. });
  237. },
  238. /*
  239. GET - get transactions between two dates, sorted and group by date
  240. params:
  241. from: Date string
  242. to: Date string
  243. return:
  244. [{
  245. date: Date
  246. transactions:[[Recipe]]
  247. }]
  248. */
  249. getTransactionsByDate: function(req, res){
  250. if(!req.session.user){
  251. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  252. return res.redirect("/");
  253. }
  254. const from = new Date(req.params.from);
  255. const to = new Date(req.params.to);
  256. to.setDate(to.getDate() + 1);
  257. Transaction.aggregate([
  258. {$match: {
  259. merchant: ObjectId(req.session.user),
  260. date: {
  261. $gte: from,
  262. $lt: to
  263. }
  264. }},
  265. {$group: {
  266. _id: {$function: {
  267. body: "function(year, month, date){return `${year}-${month}-${date}`;}",
  268. args: [{$year: "$date"}, {$month: "$date"}, {$dayOfMonth: "$date"}],
  269. lang: "js"
  270. }},
  271. transactions: {$push: {
  272. _id: "$_id",
  273. recipes: "$recipes"
  274. }}
  275. }},
  276. {$project: {
  277. _id: 0,
  278. date: {$convert: {
  279. input: "$_id",
  280. to: "date"
  281. }},
  282. transactions: 1
  283. }},
  284. {$sort: {
  285. date: 1
  286. }}
  287. ])
  288. .then((transactions)=>{
  289. return res.json(transactions);
  290. })
  291. .catch((err)=>{
  292. return res.json("ERROR: UNABLE TO RETRIEVE DATA");
  293. });
  294. },
  295. /*
  296. GET - Creates 5000 transactions for logged in merchant for testing
  297. */
  298. populate: function(req, res){
  299. if(!req.session.user){
  300. res.session.error = "Must be logged in to do that";
  301. return res.redirect("/");
  302. }
  303. function randomDate() {
  304. let now = new Date();
  305. let start = new Date();
  306. start.setFullYear(now.getFullYear() - 1);
  307. return new Date(start.getTime() + Math.random() * (now.getTime() - start.getTime()));
  308. }
  309. Merchant.findOne({_id: req.session.user})
  310. .then((merchant)=>{
  311. let newTransactions = [];
  312. for(let i = 0; i < 5000; i++){
  313. let newTransaction = new Transaction({
  314. merchant: merchant._id,
  315. date: randomDate(),
  316. recipes: []
  317. });
  318. let numberOfRecipes = Math.floor((Math.random() * 5) + 1);
  319. for(let j = 0; j < numberOfRecipes; j++){
  320. let recipeNumber = Math.floor(Math.random() * merchant.recipes.length);
  321. let randQuantity = Math.floor((Math.random() * 3) + 1);
  322. newTransaction.recipes.push({
  323. recipe: merchant.recipes[recipeNumber],
  324. quantity: randQuantity
  325. });
  326. }
  327. newTransactions.push(newTransaction);
  328. }
  329. Transaction.create(newTransactions)
  330. .then((transactions)=>{
  331. return res.redirect("/dashboard");
  332. })
  333. .catch((err)=>{
  334. return;
  335. });
  336. })
  337. .catch((err)=>{
  338. return;
  339. });
  340. }
  341. }