CartPage.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _react = _interopRequireDefault(require("react"));
  7. var _modularityFront = _interopRequireDefault(require("modularity-front"));
  8. var _reactMaterialize = require("react-materialize");
  9. require("./CartPage.css");
  10. var _API = _interopRequireDefault(require("../../Services/API"));
  11. var _Repository = _interopRequireDefault(require("../../Services/Repository"));
  12. var _UserService = _interopRequireDefault(require("../../Services/UserService"));
  13. var _Step = _interopRequireDefault(require("@material-ui/core/Step"));
  14. var _StepLabel = _interopRequireDefault(require("@material-ui/core/StepLabel"));
  15. var _Button = _interopRequireDefault(require("@material-ui/core/Button"));
  16. var _Typography = _interopRequireDefault(require("@material-ui/core/Typography"));
  17. var _CustomTable = _interopRequireDefault(require("../../Modules/CustomTable"));
  18. var _Form = _interopRequireDefault(require("../../Modules/Form"));
  19. var _Table = _interopRequireDefault(require("../../Modules/Table"));
  20. var _ArraySelector = _interopRequireDefault(require("../../Modules/ArraySelector"));
  21. var _AddressBox = _interopRequireDefault(require("../../Modules/AddressBox"));
  22. var _AddressesDisplay = _interopRequireDefault(require("../../HigherModules/AddressesDisplay"));
  23. var _Toast = _interopRequireDefault(require("../../helpers/Toast"));
  24. var _DictionaryService = _interopRequireDefault(require("../../Services/DictionaryService"));
  25. var _ClientInput = _interopRequireDefault(require("../../Inputs/ClientInput"));
  26. var _AddressInput = _interopRequireDefault(require("../../Inputs/AddressInput"));
  27. var _Stepper = _interopRequireDefault(require("../../Modules/Stepper"));
  28. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  29. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  30. function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
  31. function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
  32. function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
  33. function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
  34. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
  35. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  36. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  37. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  38. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  39. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  40. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  41. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  42. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  43. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  44. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  45. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  46. // import braintree from 'braintree-web';
  47. var braintree = window.braintree;
  48. var CLIENT_TOKEN, INSTANCE;
  49. var Module = _modularityFront.default.Module;
  50. var CartPage =
  51. /*#__PURE__*/
  52. function (_Modularity$Module) {
  53. _inherits(CartPage, _Modularity$Module);
  54. function CartPage(props) {
  55. var _this;
  56. _classCallCheck(this, CartPage);
  57. _this = _possibleConstructorReturn(this, _getPrototypeOf(CartPage).call(this, props));
  58. _this.state = {
  59. activeStep: 0,
  60. products: [],
  61. productHeaders: {
  62. '#': '-index-',
  63. image: "image",
  64. Name: "name",
  65. "Item Price": {
  66. field: "price",
  67. suffix: " €"
  68. },
  69. Quantity: "quantity",
  70. Total: {
  71. field: "amount",
  72. suffix: " €"
  73. }
  74. },
  75. selectedAddress: {},
  76. selectedBillingAddress: {},
  77. selectedShipping: {},
  78. user: {},
  79. clientInputs: {}
  80. };
  81. _this.formRef = _react.default.createRef();
  82. _this.api = new _API.default('/orders', _this.Token.value);
  83. _this.addressRepo = new _Repository.default('addresses', _this.Token.value);
  84. _this.accountRepo = new _Repository.default('accounts', _this.Token.value);
  85. _this.userRepo = new _UserService.default({
  86. Token: function Token(t) {}
  87. });
  88. _this.state = _objectSpread({}, _this.state, _this._load());
  89. _this.Products.onUpdate(function (data) {
  90. _this.setState(_this._load());
  91. });
  92. _this.Token.onUpdate(function (token) {
  93. return _this.handleToken(token);
  94. });
  95. _this.handleToken();
  96. return _this;
  97. }
  98. _createClass(CartPage, [{
  99. key: "_product_to_table",
  100. value: function _product_to_table(prods) {
  101. return Object.keys(prods).map(function (key, index) {
  102. var _prods$key = prods[key],
  103. name = _prods$key.name,
  104. price = _prods$key.price,
  105. quantity = _prods$key.quantity,
  106. image = _prods$key.image;
  107. return {
  108. id: key,
  109. image: image,
  110. name: name,
  111. price: parseFloat(price.toFixed(2)),
  112. quantity: quantity,
  113. amount: parseFloat((price * quantity).toFixed(2))
  114. };
  115. });
  116. }
  117. }, {
  118. key: "_load",
  119. value: function _load() {
  120. var _this2 = this;
  121. var withShipping = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  122. var products = this._product_to_table(this.Products.value || {});
  123. var total = Object.keys(this.Products.value || {}).reduce(function (tot, item) {
  124. return tot + _this2.Products.value[item].price * _this2.Products.value[item].quantity;
  125. }, withShipping ? this.state.selectedShipping.price || 0 : 0); //start with shipping
  126. var fpa = 0.24 * total;
  127. return {
  128. products: products,
  129. total: total,
  130. fpa: fpa
  131. };
  132. }
  133. }, {
  134. key: "routeMatch",
  135. value: function routeMatch() {
  136. return this.RoutingSystem.getRoute().url.startsWith(this.baseURL.value);
  137. }
  138. }, {
  139. key: "requestClientToken",
  140. value: function requestClientToken(token) {
  141. var _this3 = this;
  142. this.baseAPI = new _API.default("", token);
  143. this.baseAPI.get("/client_token").then(function (res) {
  144. var ctoken = res.clientToken;
  145. _this3.CLIENT_TOKEN = ctoken;
  146. _this3.showPayment();
  147. });
  148. }
  149. }, {
  150. key: "handleToken",
  151. value: function handleToken() {
  152. if (this.Token.value === "missing" && this.RoutingSystem.getRoute().url !== "/login" && this.routeMatch()) {
  153. this.CoreSystem.go('/login', {
  154. ref: this.RoutingSystem.getRoute().url
  155. }, true);
  156. }
  157. if (this.Token.value) {
  158. this.requestClientToken(this.Token.value);
  159. }
  160. this.api.setToken(this.Token.value);
  161. this.accountRepo.setToken(this.Token.value);
  162. this.addressRepo.setToken(this.Token.value);
  163. this.getUserData();
  164. }
  165. }, {
  166. key: "showPayment",
  167. value: function showPayment() {
  168. braintree.dropin.create({
  169. authorization: this.CLIENT_TOKEN,
  170. container: '#dropin-container',
  171. paypal: {
  172. flow: 'vault'
  173. }
  174. }, function (createErr, instance) {
  175. INSTANCE = instance;
  176. });
  177. }
  178. }, {
  179. key: "makePayment",
  180. value: function makePayment() {
  181. return new Promise(function (resolve, reject) {
  182. INSTANCE.requestPaymentMethod(function (err, payload) {
  183. // Submit payload.nonce to your server
  184. if (err) {
  185. return reject(err);
  186. }
  187. resolve(payload);
  188. });
  189. });
  190. }
  191. }, {
  192. key: "makeOrder",
  193. value: function makeOrder() {
  194. var _this4 = this;
  195. // FIX PRICE only 2 decimal places
  196. return this.makePayment().then(function (payload) {
  197. var products = _this4.state.products;
  198. var amount = parseFloat(_this4.state.total.toFixed(2));
  199. var nonce = payload.nonce;
  200. var customer = _this4.state.customer;
  201. var shipping = _this4.state.shipping;
  202. var ShippingID = _this4.state.selectedShipping.id;
  203. var AddressID = _this4.state.selectedAddress.id;
  204. _this4.api.post('/submit', {
  205. products: products,
  206. amount: amount,
  207. nonce: nonce,
  208. customer: customer,
  209. Shipping_id: ShippingID,
  210. Addresses_id: AddressID
  211. }).then(function (res) {
  212. console.log(res);
  213. alert("Success");
  214. _this4.CoreSystem.go('/user/orders');
  215. }).catch(function (err) {
  216. alert(err);
  217. });
  218. });
  219. }
  220. }, {
  221. key: "makeInputs",
  222. value: function makeInputs(struct) {
  223. var res = _objectSpread({}, struct);
  224. var user = this.state.user;
  225. if (!user.Account) return res;
  226. var acc = user.Account;
  227. for (var i in res) {
  228. res[i].value = acc[i] || '';
  229. }
  230. return res;
  231. }
  232. }, {
  233. key: "makeAddresses",
  234. value: function makeAddresses() {
  235. var user = this.state.user;
  236. if (!user.Addresses) return [];
  237. return user.Addresses || [];
  238. }
  239. }, {
  240. key: "makeAddress",
  241. value: function makeAddress(struct, address) {
  242. if (!address) return struct;
  243. for (var i in struct) {
  244. struct[i].value = address[i] || '';
  245. }
  246. return struct;
  247. }
  248. }, {
  249. key: "updateAccount",
  250. value: function updateAccount(acc) {
  251. this.setState({
  252. formAccount: acc
  253. });
  254. }
  255. }, {
  256. key: "getUserData",
  257. value: function getUserData() {
  258. var _this5 = this;
  259. return this.userRepo.getUser(this.Token.value).then(function (user) {
  260. return _this5.setState({
  261. user: user
  262. });
  263. }).then(function () {
  264. return _this5.makeInputs(_ClientInput.default);
  265. }).then(function (clientInputs) {
  266. return _this5.setState({
  267. clientInputs: clientInputs
  268. });
  269. });
  270. }
  271. }, {
  272. key: "verifyOrderDetails",
  273. value: function verifyOrderDetails() {
  274. var _this6 = this;
  275. _Toast.default.clear();
  276. var accid = this.state.user.Account && this.state.user.Account.id;
  277. return Promise.resolve(true).then(function () {
  278. return _this6.state.formAccount && accid && _this6.accountRepo.update(accid, _this6.state.formAccount);
  279. }).then(function () {
  280. return _this6.getUserData();
  281. }).then(function () {
  282. if (!_this6.state.selectedAddress || !_this6.state.selectedAddress.id) {
  283. // this.CoreSystem.go('/orders/verify');
  284. _Toast.default.warning(_DictionaryService.default.get("Select address!"));
  285. throw 'no selected Address';
  286. }
  287. if (!_this6.state.selectedBillingAddress || !_this6.state.selectedBillingAddress.id) {
  288. // this.CoreSystem.go('/orders/verify');
  289. _Toast.default.warning(_DictionaryService.default.get("Select billing address!"));
  290. throw 'no selected Address';
  291. }
  292. if (!_this6.state.selectedShipping || !_this6.state.selectedShipping.id) {
  293. // this.CoreSystem.go('/orders/verify');
  294. _Toast.default.warning(_DictionaryService.default.get("Select shipping method!"));
  295. throw 'no selected Shipping';
  296. }
  297. });
  298. }
  299. }, {
  300. key: "onNext",
  301. value: function onNext(step) {
  302. console.log(step);
  303. }
  304. }, {
  305. key: "getSteps",
  306. value: function getSteps() {
  307. var _this7 = this;
  308. return [{
  309. title: _DictionaryService.default.get("Cart"),
  310. url: '/orders',
  311. content: this.getStepContent(0),
  312. button: _DictionaryService.default.get("Checkout"),
  313. resolve: function resolve() {
  314. _this7.setState(_this7._load(false));
  315. }
  316. }, {
  317. title: _DictionaryService.default.get("Order Info"),
  318. url: '/orders/verify',
  319. content: this.getStepContent(1),
  320. button: _DictionaryService.default.get("Payment"),
  321. resolve: function resolve() {
  322. return _this7.getUserData();
  323. }
  324. }, {
  325. title: _DictionaryService.default.get("Payment"),
  326. url: '/orders/payment',
  327. content: this.getStepContent(2),
  328. button: _DictionaryService.default.get("Finish"),
  329. resolve: function resolve() {
  330. _this7.setState(_this7._load(true));
  331. return _this7.verifyOrderDetails();
  332. },
  333. postResolve: function postResolve() {
  334. return _this7.showPayment();
  335. }
  336. }];
  337. }
  338. }, {
  339. key: "getStepContent",
  340. value: function getStepContent(stepIndex) {
  341. var _this8 = this;
  342. switch (stepIndex) {
  343. case 0:
  344. return _react.default.createElement("div", null, _react.default.createElement("div", {
  345. className: "headers"
  346. }), _react.default.createElement(_Table.default, {
  347. TableData: [].concat(_toConsumableArray(this.state.products), [{
  348. quantity: "ΦΠΑ",
  349. amount: (this.state.fpa || 0).toFixed(2)
  350. }, {
  351. quantity: _react.default.createElement("b", null, _DictionaryService.default.get("Total")),
  352. amount: _react.default.createElement("b", null, this.state.total.toFixed(2) + ' €')
  353. }]),
  354. TableHeaders: this.state.productHeaders,
  355. TableClass: "products_table"
  356. }));
  357. case 1:
  358. // let addresses = this.makeAddresses();
  359. return _react.default.createElement("div", null, _react.default.createElement("div", {
  360. className: "headers"
  361. }, _DictionaryService.default.get("Please fill your Information")), _react.default.createElement(_reactMaterialize.Card, null, _react.default.createElement(_Form.default, {
  362. FormInputs: this.state.clientInputs,
  363. activeButton: false,
  364. formData: function formData(data) {
  365. return _this8.updateAccount(data);
  366. },
  367. ref: this.formRef
  368. })), _react.default.createElement("div", {
  369. className: "headers"
  370. }, _DictionaryService.default.get("Select delivery address")), _react.default.createElement(_AddressesDisplay.default, {
  371. service: this.addressRepo,
  372. update: function update(v) {
  373. return _this8.setState({
  374. __V: v
  375. });
  376. },
  377. onSelect: function onSelect(selectedAddress) {
  378. _this8.setState({
  379. selectedAddress: selectedAddress
  380. });
  381. }
  382. }), _react.default.createElement("div", {
  383. className: "headers"
  384. }, _DictionaryService.default.get("Select billing address")), _react.default.createElement(_AddressesDisplay.default, {
  385. service: this.addressRepo,
  386. update: function update(v) {
  387. return _this8.setState({
  388. __V: v
  389. });
  390. },
  391. onSelect: function onSelect(selectedBillingAddress) {
  392. _this8.setState({
  393. selectedBillingAddress: selectedBillingAddress
  394. });
  395. }
  396. }), _react.default.createElement(Shippings, {
  397. onSelect: function onSelect(selectedShipping) {
  398. _this8.setState({
  399. selectedShipping: selectedShipping
  400. });
  401. }
  402. }));
  403. case 2:
  404. return _react.default.createElement("div", null, _react.default.createElement("div", null, _react.default.createElement("div", {
  405. className: "headers"
  406. }), _react.default.createElement(_Table.default, {
  407. TableData: [].concat(_toConsumableArray(this.state.products), [{
  408. quantity: _DictionaryService.default.get("Shipping Cost"),
  409. amount: (this.state.selectedShipping.price || 0).toFixed(2)
  410. }, {
  411. quantity: "ΦΠΑ",
  412. amount: this.state.fpa.toFixed(2)
  413. }, {
  414. quantity: _react.default.createElement("b", null, _DictionaryService.default.get("Total")),
  415. amount: _react.default.createElement("b", null, this.state.total.toFixed(2) + ' €')
  416. }]),
  417. TableHeaders: this.state.productHeaders,
  418. TableClass: "products_table"
  419. })), _react.default.createElement("span", null, _DictionaryService.default.get("Payment")), _react.default.createElement("div", {
  420. id: "dropin-container"
  421. }), _react.default.createElement(_Button.default, {
  422. onClick: function onClick() {
  423. return _this8.makeOrder();
  424. }
  425. }, _DictionaryService.default.get("Submit order")));
  426. }
  427. }
  428. }, {
  429. key: "render",
  430. value: function render() {
  431. var _this9 = this;
  432. return _react.default.createElement("div", {
  433. className: "stepper_container"
  434. }, _react.default.createElement(_Stepper.default, {
  435. className: "row stepper",
  436. steps: this.getSteps(),
  437. baseURL: this.baseURL.value,
  438. onNext: function onNext(step) {
  439. return _this9.onNext(step);
  440. },
  441. lock: this.state.lock
  442. }), _get(_getPrototypeOf(CartPage.prototype), "render", this).call(this));
  443. }
  444. }]);
  445. return CartPage;
  446. }(_modularityFront.default.Module);
  447. var Shippings =
  448. /*#__PURE__*/
  449. function (_React$Component) {
  450. _inherits(Shippings, _React$Component);
  451. function Shippings(props) {
  452. var _this10;
  453. _classCallCheck(this, Shippings);
  454. _this10 = _possibleConstructorReturn(this, _getPrototypeOf(Shippings).call(this, props));
  455. _this10.state = {
  456. shippings: [],
  457. selected: {}
  458. };
  459. _this10.repo = new _Repository.default('shipping');
  460. _this10.repo.getPage(1, 1000).then(function (shippings) {
  461. return _this10.setState({
  462. shippings: shippings
  463. });
  464. });
  465. return _this10;
  466. }
  467. _createClass(Shippings, [{
  468. key: "select",
  469. value: function select(selected) {
  470. this.setState({
  471. selected: selected
  472. });
  473. this.props.onSelect && this.props.onSelect(selected);
  474. }
  475. }, {
  476. key: "render",
  477. value: function render() {
  478. var _this11 = this;
  479. var selected = this.state.selected;
  480. var shippings = this.state.shippings;
  481. return _react.default.createElement("div", {
  482. className: "shipping-items"
  483. }, _react.default.createElement("div", {
  484. className: "headers"
  485. }, _DictionaryService.default.get("Select shipping method")), shippings.map(function (ship) {
  486. return _react.default.createElement("div", {
  487. key: ship.id,
  488. className: "card cursor shipping-item " + (ship.id === selected.id ? 'selected' : ''),
  489. onClick: function onClick() {
  490. return _this11.select(ship);
  491. }
  492. }, _react.default.createElement("div", {
  493. className: "name"
  494. }, ship.name), _react.default.createElement("div", {
  495. className: "price"
  496. }, "+ ", ship.price.toFixed(2), " \u20AC"));
  497. }));
  498. }
  499. }]);
  500. return Shippings;
  501. }(_react.default.Component);
  502. CartPage.EditPosition = "center";
  503. CartPage.Inputs = {
  504. Products: {
  505. type: Module.Types.Object
  506. },
  507. Token: {
  508. type: Module.Types.Text
  509. },
  510. baseURL: {
  511. type: Module.Types.Text,
  512. defaultValue: "/orders"
  513. }
  514. };
  515. CartPage.Outputs = {
  516. selectedProduct: {}
  517. };
  518. CartPage.Category = "Sxoinas Packages";
  519. var _default = CartPage;
  520. exports.default = _default;