index.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. const express = require('express');
  2. const path = require('path');
  3. const CrudModule = require('../../base/CrudModule');
  4. const RepositorySystem = require('../../systems/RepositorySystem');
  5. const RoutingSystem = require('../../systems/RoutingSystem');
  6. const Actions = require('../../systems/ActionSystem');
  7. const UserMiddleware = require('./UserFilter.js');
  8. let OrderScheme = {
  9. fields: [
  10. {
  11. key: "amount",
  12. type: "decimal"
  13. },
  14. {
  15. key: "products",
  16. type: "text"
  17. },
  18. {
  19. key: "user_id",
  20. type: "integer",
  21. fk: {
  22. "table": "users",
  23. "key": "id"
  24. }
  25. }
  26. ]
  27. };
  28. class OrderModule extends CrudModule {
  29. constructor(){
  30. super('/orders', [1,1,1,1,1], 'Orders', '', [UserMiddleware]);
  31. this.repository = RepositorySystem.create('Orders', OrderScheme);
  32. this.productsRepo = RepositorySystem.create('Products');
  33. this.paymentRepo = RepositorySystem.create('Payment');
  34. this.setRepo(this.repository);
  35. // this.users = RepositorySystem.create('Users'); // You can get any repo you want!!
  36. this.router = express.Router();
  37. this.init();
  38. }
  39. init() {
  40. let routes = [
  41. {
  42. type: 'custom',
  43. method: 'post',
  44. endpoint: '/submit',
  45. customFn: this.verifyOrder.bind(this)
  46. },
  47. {
  48. type:'custom',
  49. method:'post',
  50. endpoint:'/some/',
  51. customFn: (req,res) => {
  52. this._checkProds(req.body.products)
  53. .then((result) => {
  54. console.log(result)
  55. res.sendStatus(200)
  56. })
  57. .catch((e) => {
  58. res.send("Something went wrong")
  59. })
  60. }
  61. }
  62. ]
  63. RoutingSystem.loadRoutes(routes, this.router, '/orders', [UserMiddleware]);
  64. }
  65. //1 check user --> Authentication Ok (200)
  66. //2 check products availability
  67. //3 Check shipping method and payment method
  68. //4 save Order as a row in Order Table
  69. //5 Update products Table with correct quantities
  70. //check Products Availability
  71. _checkPayment(payment_id){
  72. return new Promise((resolve,reject) =>{
  73. this.paymentRepo.get('id',payment_id)
  74. .then((res) => {
  75. console.log(res)
  76. resolve(res)
  77. })
  78. }).catch((e)=> {
  79. reject(e)
  80. })
  81. }
  82. _checkShipping(shipping_id){
  83. }
  84. submitOrder(order) {
  85. let tOrder = {...order};
  86. tOrder.products = JSON.stringify(tOrder.products);
  87. return this.clearObject(tOrder).then((temp) => this.repository.insert(temp));
  88. }
  89. verifyOrder(req, res) {
  90. let order = req.body;
  91. // check order fields are filled!
  92. // get products and check quantity!
  93. console.log("Verifying order");
  94. //get products if we have enough quantity
  95. let proms = order.products.map((item) => {
  96. let id = item.id;
  97. let quantity = item.quantity;
  98. let price = item.price;
  99. return this.productsRepo.get('id', id)
  100. .then((prod) => {
  101. if(prod[0].quantity < quantity) {
  102. throw Error(`Product with id: ${id} is low on quantity`);
  103. } else if ( prod[0].price !== price ) {
  104. throw Error(`Product with id: ${id} has different price than reported | price : ${prod[0].price} | reported : ${price}`);
  105. }
  106. return prod[0];
  107. });
  108. });
  109. //update products table
  110. Actions.emit('verifyOrder', order) // run other verifications
  111. .then((order) =>
  112. Promise.all(proms) // check quantities
  113. .then((array) => { // check total
  114. let total = parseFloat((order.products.reduce((total, item) => total + (item.price * item.quantity), 0) + order.shipping_cost).toFixed(2));
  115. if (order.amount !== total) {
  116. throw Error(`Order Amount different from calculated ${order.amount} -> ${total}`);
  117. }
  118. if(!req.user.id) {
  119. throw Error(`No user ?!`);
  120. }
  121. order["user_id"] = req.user.id;
  122. return order;
  123. })
  124. )
  125. .then((order) => this.submitOrder(order)) // submit
  126. .then(() => { // update Warehouse
  127. let promises = order.products.map((item) => {
  128. return this.productsRepo.get('id', item.id)
  129. .then((data) => {
  130. data[0].quantity = data[0].quantity - item.quantity;
  131. return this.productsRepo.update(item.id, data[0]);
  132. });
  133. });
  134. return Promise.all(promises);
  135. })
  136. .then((data) => console.log(data))
  137. .then((data) => {
  138. res.status(200).send({
  139. success: true
  140. })
  141. })
  142. .catch((e) => {
  143. console.log(e);
  144. res.sendStatus(400)
  145. });
  146. }
  147. }
  148. module.exports = OrderModule;