transactionData.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. Transaction.findOne({_id: req.params.id})
  232. .populate("recipes.recipe")
  233. .then((transaction)=>{
  234. for(let i = 0; i < transaction.recipes.length; i++){
  235. const recipe = transaction.recipes[i].recipe;
  236. for(let j = 0; j < recipe.ingredients.length; j++){
  237. const ingredient = recipe.ingredients[j].ingredient;
  238. for(let k = 0; k < res.locals.merchant.inventory.length; k++){
  239. if(ingredient.toString() === res.locals.merchant.inventory[k].ingredient.toString()){
  240. res.locals.merchant.inventory[k].quantity += recipe.ingredients[j].quantity * transaction.recipes[i].quantity;
  241. break;
  242. }
  243. }
  244. }
  245. }
  246. return Promise.all([Transaction.deleteOne({_id: req.params.id}), res.locals.merchant.save()]);
  247. })
  248. .then((response)=>{
  249. res.json({});
  250. })
  251. .catch((err)=>{
  252. if(typeof(err) === "string"){
  253. return res.json(err);
  254. }
  255. if(err.name === "ValidationError"){
  256. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  257. }
  258. return res.json("ERROR: UNABLE TO DELETE THE TRANSACTION");
  259. });
  260. },
  261. /*
  262. GET - get transactions between two dates, sorted and group by date
  263. params:
  264. from: Date string
  265. to: Date string
  266. return:
  267. [{
  268. date: Date
  269. transactions:[[Recipe]]
  270. }]
  271. */
  272. getTransactionsByDate: function(req, res){
  273. if(!req.session.user){
  274. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  275. return res.redirect("/");
  276. }
  277. const from = new Date(req.params.from);
  278. const to = new Date(req.params.to);
  279. Transaction.aggregate([
  280. {$match: {
  281. merchant: ObjectId(req.session.user),
  282. date: {
  283. $gte: from,
  284. $lt: to
  285. }
  286. }},
  287. {$sort: {
  288. date: 1
  289. }}
  290. ])
  291. .then((transactions)=>{
  292. return res.json(transactions);
  293. })
  294. .catch((err)=>{
  295. return res.json("ERROR: UNABLE TO RETRIEVE DATA");
  296. });
  297. },
  298. /*
  299. GET - Creates 5000 transactions for logged in merchant for testing
  300. */
  301. populate: function(req, res){
  302. if(!req.session.user){
  303. res.session.error = "Must be logged in to do that";
  304. return res.redirect("/");
  305. }
  306. function randomDate() {
  307. let now = new Date();
  308. let start = new Date();
  309. start.setFullYear(now.getFullYear() - 1);
  310. return new Date(start.getTime() + Math.random() * (now.getTime() - start.getTime()));
  311. }
  312. Merchant.findOne({_id: req.session.user})
  313. .then((merchant)=>{
  314. let newTransactions = [];
  315. for(let i = 0; i < 5000; i++){
  316. let newTransaction = new Transaction({
  317. merchant: merchant._id,
  318. date: randomDate(),
  319. recipes: []
  320. });
  321. let numberOfRecipes = Math.floor((Math.random() * 5) + 1);
  322. for(let j = 0; j < numberOfRecipes; j++){
  323. let recipeNumber = Math.floor(Math.random() * merchant.recipes.length);
  324. let randQuantity = Math.floor((Math.random() * 3) + 1);
  325. newTransaction.recipes.push({
  326. recipe: merchant.recipes[recipeNumber],
  327. quantity: randQuantity
  328. });
  329. }
  330. newTransactions.push(newTransaction);
  331. }
  332. Transaction.create(newTransactions)
  333. .then((transactions)=>{
  334. return res.redirect("/dashboard");
  335. })
  336. .catch((err)=>{
  337. return;
  338. });
  339. })
  340. .catch((err)=>{
  341. return;
  342. });
  343. }
  344. }