orderData.js 10 KB

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