orderData.js 10.0 KB

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