transactionData.js 12 KB

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