transactionData.js 14 KB

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