transactionData.js 14 KB

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