orderData.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. const Order = require("../models/order.js");
  2. const Merchant = require("../models/merchant.js");
  3. const ObjectId = require("mongoose").Types.ObjectId;
  4. module.exports = {
  5. /*
  6. GET - get the 25 most recent orders
  7. return = [
  8. _id: id of order,
  9. name: user created id for order,
  10. date: date order was created,
  11. ingredients: [{
  12. _id: unused id of this object,
  13. ingredient: id of the ingredient,
  14. price: price per unit of the ingredient,
  15. quantity: quantity of ingredient in this order
  16. }]
  17. ]
  18. */
  19. getOrders: function(req, res){
  20. if(!req.session.user){
  21. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  22. return res.redirect("/");
  23. }
  24. Order.aggregate([
  25. {$match: {merchant: ObjectId(req.session.user)}},
  26. {$sort: {date: -1}},
  27. {$limit: 25},
  28. {$project: {
  29. name: 1,
  30. date: 1,
  31. taxes: 1,
  32. fees: 1,
  33. ingredients: 1
  34. }}
  35. ])
  36. .then((orders)=>{
  37. return res.json(orders);
  38. })
  39. .catch((err)=>{
  40. if(typeof(err) === "string"){
  41. return res.json(err);
  42. }
  43. if(err.name === "ValidationError"){
  44. return res.json(err.errors.name.properties.message);
  45. }
  46. return res.json("ERROR: UNABLE TO RETRIEVE YOUR ORDERS");
  47. });
  48. },
  49. /*
  50. POST - retrieves a list of transactions based on the filter
  51. req.body = {
  52. startDate: starting date to filter on,
  53. endDate: ending date to filter on,
  54. ingredients: list of recipes.to filter on
  55. }
  56. */
  57. orderFilter: function(req, res){
  58. if(!req.session.user){
  59. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  60. return res.redirect("/");
  61. }
  62. let objectifiedIngredients = [];
  63. for(let i = 0; i < req.body.ingredients.length; i++){
  64. objectifiedIngredients.push(new ObjectId(req.body.ingredients[i]));
  65. }
  66. let startDate = new Date(req.body.startDate);
  67. let endDate = new Date(req.body.endDate);
  68. endDate = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate() + 1);
  69. Order.aggregate([
  70. {$match: {
  71. merchant: new ObjectId(req.session.user),
  72. date: {
  73. $gte: startDate,
  74. $lt: endDate
  75. },
  76. ingredients: {
  77. $elemMatch: {
  78. ingredient: {
  79. $in: objectifiedIngredients
  80. }
  81. }
  82. }
  83. }},
  84. {$sort: {date: -1}}
  85. ])
  86. .then((orders)=>{
  87. return res.json(orders);
  88. })
  89. .catch((err)=>{
  90. if(typeof(err) === "string"){
  91. return res.json(err);
  92. }
  93. if(err.name === "ValidationError"){
  94. return res.json(err.errors.name.properties.message);
  95. }
  96. return res.json("ERROR: UNABLE TO RETRIEVE YOUR TRANSACTIONS");
  97. });
  98. },
  99. /*
  100. POST - Creates a new order from the site
  101. req.body = {
  102. name: user created order id
  103. date: creation date
  104. ingredients: [{
  105. ingredient: id of the ingredient
  106. quantity: amount of the ingredient purchased
  107. pricePerUnit: price per gram
  108. }]
  109. }
  110. */
  111. createOrder: function(req, res){
  112. if(!req.session.user){
  113. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  114. return res.redirect("/");
  115. }
  116. let newOrder = new Order(req.body);
  117. newOrder.merchant = req.session.user;
  118. newOrder.save()
  119. .then((response)=>{
  120. res.json(response);
  121. })
  122. .catch((err)=>{
  123. if(typeof(err) === "string"){
  124. return res.json(err);
  125. }
  126. if(err.name === "ValidationError"){
  127. return res.json(err.errors.name.properties.message);
  128. }
  129. return res.json("ERROR: UNABLE TO SAVE ORDER");
  130. });
  131. Merchant.findOne({_id: req.session.user})
  132. .then((merchant)=>{
  133. for(let i = 0; i < req.body.ingredients.length; i++){
  134. for(let j = 0; j < merchant.inventory.length; j++){
  135. if(req.body.ingredients[i].ingredient === merchant.inventory[j].ingredient.toString()){
  136. merchant.inventory[j].quantity += parseFloat(req.body.ingredients[i].quantity);
  137. }
  138. }
  139. }
  140. return merchant.save();
  141. })
  142. .then((merchant)=>{
  143. return;
  144. })
  145. .catch(()=>{});
  146. },
  147. createFromSpreadsheet: function(req, res){
  148. if(!req.session.user){
  149. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  150. return res.redirect("/");
  151. }
  152. //read file, get the correct sheet, create array from sheet
  153. let workbook = xlsx.readFile(req.file.path);
  154. fs.unlink(req.file.path, ()=>{});
  155. let sheets = Object.keys(workbook.Sheets);
  156. let sheet = {};
  157. for(let i = 0; i < sheets.length; i++){
  158. let str = sheets[i].toLowerCase();
  159. if(str === "order" || str === "orders"){
  160. sheet = workbook.Sheets[sheets[i]];
  161. }
  162. }
  163. const array = xlsx.utils.sheet_to_json(sheet, {
  164. header: 1
  165. });
  166. //get property locations
  167. let locations = {};
  168. for(let i = 0; i < array[0].length; i++){
  169. switch(array[0][i].toLowerCase()){
  170. case "name": locations.name = i; break;
  171. case "date": locations.date = i; break;
  172. case "taxes": locations.taxes = i; break;
  173. case "fees": locations.fees = i; break;
  174. case "ingredients": locations.ingredients = i; break;
  175. case "quantity": locations.quantity = i; break;
  176. case "price": locations.price = i; break;
  177. }
  178. }
  179. let merchant = {};
  180. Merchant.findOne({_id: req.session.user})
  181. .populate("inventory.ingredient")
  182. .then((response)=>{
  183. merchant = response;
  184. let orders = [];
  185. let currentOrder = {};
  186. for(let i = 1; i < array.length; i++){
  187. if(array[i].length === 0 || array[i][locations.ingredients] === undefined){
  188. continue;
  189. }
  190. if(array[i][locations.name] !== undefined){
  191. currentOrder = {
  192. merchant: req.session.user,
  193. name: array[i][locations.name],
  194. taxes: parseInt(array[i][locations.taxes] * 100),
  195. fees: parseInt(array[i][locations.fees] * 100),
  196. ingredients: []
  197. }
  198. if(array[i][locations.date] === undefined){
  199. currentOrder.date = new Date();
  200. }else{
  201. currentOrder.date = new Date(array[i][locations.date]);
  202. }
  203. orders.push(currentOrder);
  204. }
  205. let exists = false;
  206. for(let j = 0; j < merchant.inventory.length; j++){
  207. if(merchant.inventory[j].ingredient.name.toLowerCase() === array[i][locations.ingredients].toLowerCase()){
  208. const baseQuantity = helper.convertQuantityToBaseUnit(array[i][locations.quantity], merchant.inventory[j].defaultUnit);
  209. currentOrder.ingredients.push({
  210. ingredient: merchant.inventory[j].ingredient._id,
  211. quantity: baseQuantity,
  212. pricePerUnit: helper.convertPrice(array[i][locations.price] * 100, merchant.inventory[j].defaultUnit)
  213. });
  214. merchant.inventory[j].quantity += baseQuantity;
  215. exists = true;
  216. break;
  217. }
  218. }
  219. if(exists === false){
  220. throw `CANNOT FIND INGREDIENT ${array[i][locations.ingredients]} FROM ORDER ${array[i][locations.name]}`;
  221. }
  222. }
  223. return Promise.all([Order.create(orders), merchant.save()]);
  224. })
  225. .then((response)=>{
  226. return res.json(response[0]);
  227. })
  228. .catch((err)=>{
  229. if(typeof(err) === "string"){
  230. return res.json(err);
  231. }
  232. return res.json("ERROR: UNABLE TO CREATE YOUR ORDERS");
  233. });
  234. },
  235. /*
  236. GET - Creates and sends a template xlsx for uploading orders
  237. */
  238. spreadsheetTemplate: function(req, res){
  239. if(!req.session.user){
  240. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  241. return res.redirect("/");
  242. }
  243. Merchant.findOne({_id: req.session.user})
  244. .populate("inventory.ingredient")
  245. .then((merchant)=>{
  246. let workbook = xlsx.utils.book_new();
  247. workbook.SheetNames.push("Order");
  248. let workbookData = [];
  249. workbookData.push(["Name", "Date", "Taxes", "Fees", "Ingredients", "Quantity", "Price", "<- Price Per Unit", "Ingredient Reference"]);
  250. for(let i = 0; i < merchant.inventory.length; i++){
  251. let data = ["", "", "", "", "", "", "", "", merchant.inventory[i].ingredient.name];
  252. workbookData.push(data);
  253. }
  254. workbookData[1][0] = "My Order Name";
  255. workbookData[1][1] = "2020-02-29";
  256. workbookData[1][2] = 10.99;
  257. workbookData[1][3] = 5.98;
  258. workbookData[1][4] = "Example ingredient 1";
  259. workbookData[1][5] = 100;
  260. workbookData[1][6] = 1.99;
  261. workbookData[2][4] = "Example ingredient 2";
  262. workbookData[2][5] = 55;
  263. workbookData[2][6] = 0.95;
  264. workbook.Sheets.Order = xlsx.utils.aoa_to_sheet(workbookData);
  265. xlsx.writeFile(workbook, "SublineOrder.xlsx");
  266. return res.download("SublineOrder.xlsx", (err)=>{
  267. fs.unlink("SublineOrder.xlsx", ()=>{});
  268. });
  269. })
  270. .catch((err)=>{});
  271. },
  272. /*
  273. DELETE - Remove an order from the database
  274. */
  275. removeOrder: function(req, res){
  276. if(!req.session.user){
  277. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  278. return res.redirect("/");
  279. }
  280. let merchant = {};
  281. let order = {}
  282. Merchant.findOne({_id: req.session.user})
  283. .then((response)=>{
  284. merchant = response;
  285. return Order.findOne({_id: req.params.id});
  286. })
  287. .then((response)=>{
  288. order = response;
  289. return Order.deleteOne({_id: req.params.id})
  290. })
  291. .then((response)=>{
  292. res.json({});
  293. for(let i = 0; i < order.ingredients.length; i++){
  294. for(let j = 0; j < merchant.inventory.length; j++){
  295. if(order.ingredients[i].ingredient.toString() === merchant.inventory[j].ingredient.toString()){
  296. merchant.inventory[j].quantity -= order.ingredients[i].quantity;
  297. break;
  298. }
  299. }
  300. }
  301. return merchant.save();
  302. })
  303. .catch((err)=>{
  304. if(typeof(err) === "string"){
  305. return res.json(err);
  306. }
  307. if(err.name === "ValidationError"){
  308. return res.json(err.errors.name.properties.message);
  309. }
  310. return res.json("ERROR: UNABLE TO REMOVE ORDER");
  311. });
  312. }
  313. }