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 * @copyright 2019 Shamim Rezaie <shamim@moodle.com>
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 import ModalFactory from 'core/modal_factory';
25 import Templates from 'core/templates';
26 import {get_string as getString} from 'core/str';
27 import {getAvailableGateways} from './repository';
28 import Selectors from './selectors';
29 import ModalEvents from 'core/modal_events';
30 import PaymentEvents from 'core_payment/events';
31 import {add as addToast, addToastRegion} from 'core/toast';
32 import Notification from 'core/notification';
33 import ModalGateways from './modal_gateways';
36 * Register event listeners for the module.
38 const registerEventListeners = () => {
39 document.addEventListener('click', e => {
40 const gatewayTrigger = e.target.closest('[data-action="core_payment/triggerPayment"]');
44 show(gatewayTrigger, {focusOnClose: e.target});
50 * Shows the gateway selector modal.
52 * @param {HTMLElement} rootNode
53 * @param {Object} options - Additional options
54 * @param {HTMLElement} options.focusOnClose The element to focus on when the modal is closed.
56 const show = async(rootNode, {
59 const modal = await ModalFactory.create({
60 type: ModalGateways.TYPE,
61 title: await getString('selectpaymenttype', 'core_payment'),
62 body: await Templates.render('core_payment/gateways_modal', {}),
65 const rootElement = modal.getRoot()[0];
66 addToastRegion(rootElement);
70 modal.getRoot().on(ModalEvents.hidden, () => {
71 // Destroy when hidden.
76 // eslint-disable-line
80 modal.getRoot().on(PaymentEvents.proceed, (e) => {
81 const gateway = (rootElement.querySelector(Selectors.values.gateway) || {value: ''}).value;
86 rootNode.dataset.component,
87 rootNode.dataset.paymentarea,
88 rootNode.dataset.itemid,
89 rootNode.dataset.description
93 Notification.addNotification({
97 location.href = rootNode.dataset.successurl;
99 // The following return statement is never reached. It is put here just to make eslint happy.
102 .catch(message => Notification.alert('', message));
104 // We cannot use await in the following line.
105 // The reason is that we are preventing the default action of the save event being triggered,
106 // therefore we cannot define the event handler function asynchronous.
107 getString('nogatewayselected', 'core_payment').then(message => addToast(message, {type: 'warning'})).catch();
113 // Re-calculate the cost when gateway is changed.
114 rootElement.addEventListener('change', e => {
115 if (e.target.matches(Selectors.elements.gateways)) {
116 updateCostRegion(rootElement, rootNode.dataset.cost);
120 const gateways = await getAvailableGateways(rootNode.dataset.component, rootNode.dataset.paymentarea, rootNode.dataset.itemid);
125 const {html, js} = await Templates.renderForPromise('core_payment/gateways', context);
126 Templates.replaceNodeContents(rootElement.querySelector(Selectors.regions.gatewaysContainer), html, js);
127 selectSingleGateway(rootElement);
128 await updateCostRegion(rootElement, rootNode.dataset.cost);
132 * Auto-select the gateway if there is only one gateway.
134 * @param {HTMLElement} root An HTMLElement that contains the cost region
136 const selectSingleGateway = root => {
137 const gateways = root.querySelectorAll(Selectors.elements.gateways);
139 if (gateways.length == 1) {
140 gateways[0].checked = true;
145 * Shows the cost of the item the user is purchasing in the cost region.
147 * @param {HTMLElement} root An HTMLElement that contains the cost region
148 * @param {string} defaultCost The default cost that is going to be displayed if no gateway is selected
149 * @returns {Promise<void>}
151 const updateCostRegion = async(root, defaultCost = '') => {
152 const gatewayElement = root.querySelector(Selectors.values.gateway);
153 const surcharge = parseInt((gatewayElement || {dataset: {surcharge: 0}}).dataset.surcharge);
154 const cost = (gatewayElement || {dataset: {cost: defaultCost}}).dataset.cost;
156 const {html, js} = await Templates.renderForPromise('core_payment/fee_breakdown', {fee: cost, surcharge});
157 Templates.replaceNodeContents(root.querySelector(Selectors.regions.costContainer), html, js);
161 * Process payment using the selected gateway.
163 * @param {string} gateway The gateway to be used for payment
164 * @param {string} component Name of the component that the itemId belongs to
165 * @param {string} paymentArea Name of the area in the component that the itemId belongs to
166 * @param {number} itemId An internal identifier that is used by the component
167 * @param {string} description Description of the payment
168 * @returns {Promise<string>}
170 const processPayment = async(gateway, component, paymentArea, itemId, description) => {
171 const paymentMethod = await import(`paygw_${gateway}/gateways_modal`);
172 return paymentMethod.process(component, paymentArea, itemId, description);
176 * Set up the payment actions.
178 export const init = () => {
179 if (!init.initialised) {
180 // Event listeners should only be registered once.
181 init.initialised = true;
182 registerEventListeners();
187 * Whether the init function was called before.
192 init.initialised = false;