orderData.js 12 KB

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