transactionData.js 14 KB

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