transactionData.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. res.locals.merchant
  207. .populate("recipes")
  208. .execPopulate()
  209. .then((merchant)=>{
  210. let workbook = xlsx.utils.book_new();
  211. workbook.SheetNames.push("Transaction");
  212. let workbookData = [];
  213. let now = new Date().toISOString();
  214. workbookData.push(["Date", "Recipes", "Quantity"]);
  215. workbookData.push([now.slice(0, 10), merchant.recipes[0].name, 0]);
  216. for(let i = 1; i < merchant.recipes.length; i++){
  217. workbookData.push(["", merchant.recipes[i].name, 0]);
  218. }
  219. workbook.Sheets.Transaction = xlsx.utils.aoa_to_sheet(workbookData);
  220. xlsx.writeFile(workbook, "SublineTransaction.xlsx");
  221. return res.download("SublineTransaction.xlsx", (err)=>{
  222. fs.unlink("SublineTransaction.xlsx", ()=>{});
  223. });
  224. })
  225. .catch((err)=>{});
  226. },
  227. /*
  228. DELETE - Remove a transaction from the database
  229. */
  230. remove: function(req, res){
  231. if(!req.session.user){
  232. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  233. return res.redirect("/");
  234. }
  235. let merchant = {};
  236. let transaction = {};
  237. Merchant.findOne({_id: req.session.user})
  238. .then((response)=>{
  239. merchant = response;
  240. return Transaction.findOne({_id: req.params.id}).populate("recipes.recipe");
  241. })
  242. .then((response)=>{
  243. transaction = response;
  244. return Transaction.deleteOne({_id: req.params.id});
  245. })
  246. .then((response)=>{
  247. res.json();
  248. for(let i = 0; i < transaction.recipes.length; i++){
  249. const recipe = transaction.recipes[i].recipe;
  250. for(let j = 0; j < recipe.ingredients.length; j++){
  251. const ingredient = recipe.ingredients[j].ingredient;
  252. for(let k = 0; k < merchant.inventory.length; k++){
  253. if(ingredient.toString() === merchant.inventory[k].ingredient.toString()){
  254. merchant.inventory[k].quantity += recipe.ingredients[j].quantity * transaction.recipes[i].quantity;
  255. break;
  256. }
  257. }
  258. }
  259. }
  260. return merchant.save();
  261. })
  262. .catch((err)=>{
  263. if(typeof(err) === "string"){
  264. return res.json(err);
  265. }
  266. if(err.name === "ValidationError"){
  267. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  268. }
  269. return res.json("ERROR: UNABLE TO DELETE THE TRANSACTION");
  270. });
  271. },
  272. /*
  273. GET - get transactions between two dates, sorted and group by date
  274. params:
  275. from: Date string
  276. to: Date string
  277. return:
  278. [{
  279. date: Date
  280. transactions:[[Recipe]]
  281. }]
  282. */
  283. getTransactionsByDate: function(req, res){
  284. if(!req.session.user){
  285. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  286. return res.redirect("/");
  287. }
  288. const from = new Date(req.params.from);
  289. const to = new Date(req.params.to);
  290. Transaction.aggregate([
  291. {$match: {
  292. merchant: ObjectId(req.session.user),
  293. date: {
  294. $gte: from,
  295. $lt: to
  296. }
  297. }},
  298. {$sort: {
  299. date: 1
  300. }}
  301. ])
  302. .then((transactions)=>{
  303. return res.json(transactions);
  304. })
  305. .catch((err)=>{
  306. return res.json("ERROR: UNABLE TO RETRIEVE DATA");
  307. });
  308. },
  309. /*
  310. GET - Creates 5000 transactions for logged in merchant for testing
  311. */
  312. populate: function(req, res){
  313. if(!req.session.user){
  314. res.session.error = "Must be logged in to do that";
  315. return res.redirect("/");
  316. }
  317. function randomDate() {
  318. let now = new Date();
  319. let start = new Date();
  320. start.setFullYear(now.getFullYear() - 1);
  321. return new Date(start.getTime() + Math.random() * (now.getTime() - start.getTime()));
  322. }
  323. Merchant.findOne({_id: req.session.user})
  324. .then((merchant)=>{
  325. let newTransactions = [];
  326. for(let i = 0; i < 5000; i++){
  327. let newTransaction = new Transaction({
  328. merchant: merchant._id,
  329. date: randomDate(),
  330. recipes: []
  331. });
  332. let numberOfRecipes = Math.floor((Math.random() * 5) + 1);
  333. for(let j = 0; j < numberOfRecipes; j++){
  334. let recipeNumber = Math.floor(Math.random() * merchant.recipes.length);
  335. let randQuantity = Math.floor((Math.random() * 3) + 1);
  336. newTransaction.recipes.push({
  337. recipe: merchant.recipes[recipeNumber],
  338. quantity: randQuantity
  339. });
  340. }
  341. newTransactions.push(newTransaction);
  342. }
  343. Transaction.create(newTransactions)
  344. .then((transactions)=>{
  345. return res.redirect("/dashboard");
  346. })
  347. .catch((err)=>{
  348. return;
  349. });
  350. })
  351. .catch((err)=>{
  352. return;
  353. });
  354. }
  355. }