1 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
17 * Contain the logic for the gateways modal.
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
25 import ModalFactory from 'core/modal_factory';
26 import Templates from 'core/templates';
27 import {get_string as getString} from 'core/str';
28 import {getGatewaysSupportingCurrency} from './repository';
29 import Selectors from './selectors';
30 import ModalEvents from 'core/modal_events';
31 import PaymentEvents from 'core_payment/events';
32 import {add as addToast, addToastRegion} from 'core/toast';
33 import Notification from 'core/notification';
34 import ModalGateways from './modal_gateways';
37 * Register event listeners for the module.
39 * @param {string} nodeSelector The root to listen to.
41 export const registerEventListenersBySelector = (nodeSelector) => {
42 document.querySelectorAll(nodeSelector).forEach((element) => {
43 registerEventListeners(element);
48 * Register event listeners for the module.
50 * @param {HTMLElement} rootNode The root to listen to.
52 export const registerEventListeners = (rootNode) => {
53 rootNode.addEventListener('click', (e) => {
55 show(rootNode, {focusOnClose: e.target});
60 * Shows the gateway selector modal.
62 * @param {HTMLElement} rootNode
63 * @param {Object} options - Additional options
64 * @param {HTMLElement} options.focusOnClose The element to focus on when the modal is closed.
66 const show = async(rootNode, {
69 const modal = await ModalFactory.create({
70 type: ModalGateways.TYPE,
71 title: await getString('selectpaymenttype', 'core_payment'),
72 body: await Templates.render('core_payment/gateways_modal', {}),
75 const rootElement = modal.getRoot()[0];
76 addToastRegion(rootElement);
80 modal.getRoot().on(ModalEvents.hidden, () => {
81 // Destroy when hidden.
86 // eslint-disable-line
90 modal.getRoot().on(PaymentEvents.proceed, (e) => {
91 const gateway = (rootElement.querySelector(Selectors.values.gateway) || {value: ''}).value;
97 value: parseFloat(rootNode.dataset.amount),
98 currency: rootNode.dataset.currency,
99 surcharge: parseInt((rootElement.querySelector(Selectors.values.gateway) || {dataset: {surcharge: 0}})
102 rootNode.dataset.component,
103 rootNode.dataset.componentid,
104 rootNode.dataset.description,
105 ({success, message = ''}) => {
108 Notification.addNotification({
114 Notification.alert('', message);
119 // We cannot use await in the following line.
120 // The reason is that we are preventing the default action of the save event being triggered,
121 // therefore we cannot define the event handler function asynchronous.
122 getString('nogatewayselected', 'core_payment').then(message => addToast(message));
128 // Re-calculate the cost when gateway is changed.
129 rootElement.addEventListener('change', e => {
130 if (e.target.matches(Selectors.elements.gateways)) {
131 updateCostRegion(rootElement, parseFloat(rootNode.dataset.amount), rootNode.dataset.currency);
135 const currency = rootNode.dataset.currency;
136 const accountid = rootNode.dataset.accountid;
137 const gateways = await getGatewaysSupportingCurrency(currency, accountid);
142 const {html, js} = await Templates.renderForPromise('core_payment/gateways', context);
143 Templates.replaceNodeContents(rootElement.querySelector(Selectors.regions.gatewaysContainer), html, js);
144 selectSingleGateway(rootElement);
145 await updateCostRegion(rootElement, parseFloat(rootNode.dataset.amount), rootNode.dataset.currency);
149 * Auto-select the gateway if there is only one gateway.
151 * @param {HTMLElement} root An HTMLElement that contains the cost region
153 const selectSingleGateway = root => {
154 const gateways = root.querySelectorAll(Selectors.elements.gateways);
156 if (gateways.length == 1) {
157 gateways[0].checked = true;
162 * Shows the cost of the item the user is purchasing in the cost region.
164 * @param {HTMLElement} root An HTMLElement that contains the cost region
165 * @param {number} amount The amount part of cost
166 * @param {string} currency The currency part of cost in the 3-letter ISO-4217 format
167 * @returns {Promise<void>}
169 const updateCostRegion = async(root, amount, currency) => {
170 const locale = await updateCostRegion.locale; // This only takes a bit the first time.
171 const surcharge = parseInt((root.querySelector(Selectors.values.gateway) || {dataset: {surcharge: 0}}).dataset.surcharge);
172 amount += amount * surcharge / 100;
173 const localisedCost = amount.toLocaleString(locale, {style: "currency", currency: currency});
175 const {html, js} = await Templates.renderForPromise('core_payment/fee_breakdown', {fee: localisedCost, surcharge});
176 Templates.replaceNodeContents(root.querySelector(Selectors.regions.costContainer), html, js);
178 updateCostRegion.locale = getString("localecldr", "langconfig");
181 * Process payment using the selected gateway.
183 * @param {string} gateway The gateway to be used for payment
184 * @param {Object} amount - Amount of payment
185 * @param {number} amount.value The numerical part of the amount
186 * @param {string} amount.currency The currency part of the amount in the three-character ISO-4217 format
187 * @param {number} amount.surcharge The surcharge percentage that should be added to the amount
188 * @param {string} component Name of the component that the componentid belongs to
189 * @param {number} componentid An internal identifier that is used by the component
190 * @param {string} description Description of the payment
191 * @param {processPaymentCallback} callback The callback function to call when processing is finished
192 * @returns {Promise<void>}
194 const processPayment = async(gateway, {value, currency, surcharge = 0}, component, componentid, description, callback) => {
195 const paymentMethod = await import(`pg_${gateway}/gateways_modal`);
197 value += value * surcharge / 100;
198 paymentMethod.process(value, currency, component, componentid, description, callback);
202 * The callback definition for processPayment.
204 * @callback processPaymentCallback
205 * @param {bool} success
206 * @param {string} message