transactionData.js 13 KB

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