MDL-69166 core_payment: Use promises instead of callbacks
[moodle.git] / payment / amd / src / gateways_modal.js
CommitLineData
c2321a26
SR
1// This file is part of Moodle - http://moodle.org/
2//
3// Moodle is free software: you can redistribute it and/or modify
4// it under the terms of the GNU General Public License as published by
5// the Free Software Foundation, either version 3 of the License, or
6// (at your option) any later version.
7//
8// Moodle is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
15
16/**
17 * Contain the logic for the gateways modal.
18 *
19 * @module core_payment/gateways_modal
20 * @package core_payment
21 * @copyright 2019 Shamim Rezaie <shamim@moodle.com>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25import ModalFactory from 'core/modal_factory';
26import Templates from 'core/templates';
27import {get_string as getString} from 'core/str';
90fbc58d 28import {getAvailableGateways} from './repository';
c2321a26 29import Selectors from './selectors';
34770016 30import ModalEvents from 'core/modal_events';
e2faf672 31import PaymentEvents from 'core_payment/events';
ed04c382 32import {add as addToast, addToastRegion} from 'core/toast';
d00c00dd 33import Notification from 'core/notification';
e2faf672 34import ModalGateways from './modal_gateways';
c2321a26
SR
35
36/**
37 * Register event listeners for the module.
c2321a26 38 */
b63f17b5
SR
39const registerEventListeners = () => {
40 document.addEventListener('click', e => {
41 const gatewayTrigger = e.target.closest('[data-action="core_payment/triggerPayment"]');
42 if (gatewayTrigger) {
43 e.preventDefault();
c2321a26 44
b63f17b5
SR
45 show(gatewayTrigger, {focusOnClose: e.target});
46 }
c2321a26
SR
47 });
48};
49
50/**
51 * Shows the gateway selector modal.
52 *
53 * @param {HTMLElement} rootNode
54 * @param {Object} options - Additional options
55 * @param {HTMLElement} options.focusOnClose The element to focus on when the modal is closed.
56 */
34770016 57const show = async(rootNode, {
c2321a26
SR
58 focusOnClose = null,
59} = {}) => {
34770016 60 const modal = await ModalFactory.create({
e2faf672 61 type: ModalGateways.TYPE,
34770016
SR
62 title: await getString('selectpaymenttype', 'core_payment'),
63 body: await Templates.render('core_payment/gateways_modal', {}),
64 });
c2321a26 65
1882bb47
SR
66 const rootElement = modal.getRoot()[0];
67 addToastRegion(rootElement);
ed04c382 68
34770016 69 modal.show();
c2321a26 70
34770016
SR
71 modal.getRoot().on(ModalEvents.hidden, () => {
72 // Destroy when hidden.
73 modal.destroy();
74 try {
75 focusOnClose.focus();
76 } catch (e) {
77 // eslint-disable-line
78 }
79 });
c2321a26 80
e2faf672 81 modal.getRoot().on(PaymentEvents.proceed, (e) => {
1882bb47 82 const gateway = (rootElement.querySelector(Selectors.values.gateway) || {value: ''}).value;
ed04c382 83
34770016
SR
84 if (gateway) {
85 processPayment(
86 gateway,
34770016 87 rootNode.dataset.component,
7d10f352 88 rootNode.dataset.paymentarea,
52305c9a 89 rootNode.dataset.itemid,
0fb7847e
SR
90 rootNode.dataset.description
91 )
92 .then(message => {
93 modal.hide();
94 Notification.addNotification({
95 message: message,
96 type: 'success',
97 });
98 location.reload();
99
100 // The following return statement is never reached. It is put here just to make eslint happy.
101 return message;
102 })
103 .catch(message => Notification.alert('', message));
34770016
SR
104 } else {
105 // We cannot use await in the following line.
106 // The reason is that we are preventing the default action of the save event being triggered,
107 // therefore we cannot define the event handler function asynchronous.
0fb7847e 108 getString('nogatewayselected', 'core_payment').then(message => addToast(message)).catch();
34770016 109 }
ed04c382 110
34770016 111 e.preventDefault();
ed04c382 112 });
34770016 113
1882bb47
SR
114 // Re-calculate the cost when gateway is changed.
115 rootElement.addEventListener('change', e => {
116 if (e.target.matches(Selectors.elements.gateways)) {
7e112616 117 updateCostRegion(rootElement, rootNode.dataset.cost);
1882bb47
SR
118 }
119 });
120
52305c9a 121 const gateways = await getAvailableGateways(rootNode.dataset.component, rootNode.dataset.paymentarea, rootNode.dataset.itemid);
34770016
SR
122 const context = {
123 gateways
124 };
125
126 const {html, js} = await Templates.renderForPromise('core_payment/gateways', context);
1882bb47 127 Templates.replaceNodeContents(rootElement.querySelector(Selectors.regions.gatewaysContainer), html, js);
58a89a46 128 selectSingleGateway(rootElement);
7e112616 129 await updateCostRegion(rootElement, rootNode.dataset.cost);
ed04c382 130};
bb7d6793 131
58a89a46
SR
132/**
133 * Auto-select the gateway if there is only one gateway.
134 *
135 * @param {HTMLElement} root An HTMLElement that contains the cost region
136 */
137const selectSingleGateway = root => {
138 const gateways = root.querySelectorAll(Selectors.elements.gateways);
139
140 if (gateways.length == 1) {
141 gateways[0].checked = true;
142 }
143};
144
bb7d6793
SR
145/**
146 * Shows the cost of the item the user is purchasing in the cost region.
147 *
148 * @param {HTMLElement} root An HTMLElement that contains the cost region
7e112616 149 * @param {string} defaultCost The default cost that is going to be displayed if no gateway is selected
bb7d6793
SR
150 * @returns {Promise<void>}
151 */
7e112616
SR
152const updateCostRegion = async(root, defaultCost = '') => {
153 const gatewayElement = root.querySelector(Selectors.values.gateway);
154 const surcharge = parseInt((gatewayElement || {dataset: {surcharge: 0}}).dataset.surcharge);
155 const cost = (gatewayElement || {dataset: {cost: defaultCost}}).dataset.cost;
bb7d6793 156
15a4e4c8 157 const {html, js} = await Templates.renderForPromise('core_payment/fee_breakdown', {fee: cost, surcharge});
bb7d6793
SR
158 Templates.replaceNodeContents(root.querySelector(Selectors.regions.costContainer), html, js);
159};
ed04c382
SR
160
161/**
162 * Process payment using the selected gateway.
163 *
ed04c382 164 * @param {string} gateway The gateway to be used for payment
52305c9a
SR
165 * @param {string} component Name of the component that the itemId belongs to
166 * @param {string} paymentArea Name of the area in the component that the itemId belongs to
167 * @param {number} itemId An internal identifier that is used by the component
ab6ca275 168 * @param {string} description Description of the payment
0fb7847e 169 * @returns {Promise<string>}
ed04c382 170 */
0fb7847e 171const processPayment = async(gateway, component, paymentArea, itemId, description) => {
6b3d163a 172 const paymentMethod = await import(`paygw_${gateway}/gateways_modal`);
0fb7847e 173 return paymentMethod.process(component, paymentArea, itemId, description);
c2321a26 174};
d00c00dd 175
b63f17b5
SR
176/**
177 * Set up the payment actions.
178 */
179export const init = () => {
180 if (!init.initialised) {
181 // Event listeners should only be registered once.
182 init.initialised = true;
183 registerEventListeners();
184 }
185};
186
187/**
188 * Whether the init function was called before.
189 *
190 * @static
191 * @type {boolean}
192 */
193init.initialised = false;