transactionData.js 14 KB

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