orderData.js 12 KB

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