transactionData.js 15 KB

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