transactionData.js 12 KB

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