orderData.js 14 KB

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