transactionData.js 15 KB

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