transactionData.js 14 KB

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