MDL-69166 core_payment: Add paymentarea to the payment subsystem
[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';
34770016 28import {getGatewaysSupportingCurrency} 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.
38 *
39 * @param {string} nodeSelector The root to listen to.
40 */
2427b921
SR
41export const registerEventListenersBySelector = (nodeSelector) => {
42 document.querySelectorAll(nodeSelector).forEach((element) => {
43 registerEventListeners(element);
44 });
45};
c2321a26 46
2427b921
SR
47/**
48 * Register event listeners for the module.
49 *
50 * @param {HTMLElement} rootNode The root to listen to.
51 */
52export const registerEventListeners = (rootNode) => {
c2321a26
SR
53 rootNode.addEventListener('click', (e) => {
54 e.preventDefault();
55 show(rootNode, {focusOnClose: e.target});
56 });
57};
58
59/**
60 * Shows the gateway selector modal.
61 *
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.
65 */
34770016 66const show = async(rootNode, {
c2321a26
SR
67 focusOnClose = null,
68} = {}) => {
34770016 69 const modal = await ModalFactory.create({
e2faf672 70 type: ModalGateways.TYPE,
34770016
SR
71 title: await getString('selectpaymenttype', 'core_payment'),
72 body: await Templates.render('core_payment/gateways_modal', {}),
73 });
c2321a26 74
1882bb47
SR
75 const rootElement = modal.getRoot()[0];
76 addToastRegion(rootElement);
ed04c382 77
34770016 78 modal.show();
c2321a26 79
34770016
SR
80 modal.getRoot().on(ModalEvents.hidden, () => {
81 // Destroy when hidden.
82 modal.destroy();
83 try {
84 focusOnClose.focus();
85 } catch (e) {
86 // eslint-disable-line
87 }
88 });
c2321a26 89
e2faf672 90 modal.getRoot().on(PaymentEvents.proceed, (e) => {
1882bb47 91 const gateway = (rootElement.querySelector(Selectors.values.gateway) || {value: ''}).value;
ed04c382 92
34770016
SR
93 if (gateway) {
94 processPayment(
95 gateway,
34770016 96 rootNode.dataset.component,
7d10f352 97 rootNode.dataset.paymentarea,
34770016
SR
98 rootNode.dataset.componentid,
99 rootNode.dataset.description,
100 ({success, message = ''}) => {
101 modal.hide();
102 if (success) {
103 Notification.addNotification({
104 message: message,
105 type: 'success',
106 });
107 location.reload();
108 } else {
109 Notification.alert('', message);
110 }
111 },
112 );
113 } else {
114 // We cannot use await in the following line.
115 // The reason is that we are preventing the default action of the save event being triggered,
116 // therefore we cannot define the event handler function asynchronous.
117 getString('nogatewayselected', 'core_payment').then(message => addToast(message));
118 }
ed04c382 119
34770016 120 e.preventDefault();
ed04c382 121 });
34770016 122
1882bb47
SR
123 // Re-calculate the cost when gateway is changed.
124 rootElement.addEventListener('change', e => {
125 if (e.target.matches(Selectors.elements.gateways)) {
7e112616 126 updateCostRegion(rootElement, rootNode.dataset.cost);
1882bb47
SR
127 }
128 });
129
7d10f352
SR
130 const gateways = await getGatewaysSupportingCurrency(rootNode.dataset.component, rootNode.dataset.paymentarea,
131 rootNode.dataset.componentid);
34770016
SR
132 const context = {
133 gateways
134 };
135
136 const {html, js} = await Templates.renderForPromise('core_payment/gateways', context);
1882bb47 137 Templates.replaceNodeContents(rootElement.querySelector(Selectors.regions.gatewaysContainer), html, js);
58a89a46 138 selectSingleGateway(rootElement);
7e112616 139 await updateCostRegion(rootElement, rootNode.dataset.cost);
ed04c382 140};
bb7d6793 141
58a89a46
SR
142/**
143 * Auto-select the gateway if there is only one gateway.
144 *
145 * @param {HTMLElement} root An HTMLElement that contains the cost region
146 */
147const selectSingleGateway = root => {
148 const gateways = root.querySelectorAll(Selectors.elements.gateways);
149
150 if (gateways.length == 1) {
151 gateways[0].checked = true;
152 }
153};
154
bb7d6793
SR
155/**
156 * Shows the cost of the item the user is purchasing in the cost region.
157 *
158 * @param {HTMLElement} root An HTMLElement that contains the cost region
7e112616 159 * @param {string} defaultCost The default cost that is going to be displayed if no gateway is selected
bb7d6793
SR
160 * @returns {Promise<void>}
161 */
7e112616
SR
162const updateCostRegion = async(root, defaultCost = '') => {
163 const gatewayElement = root.querySelector(Selectors.values.gateway);
164 const surcharge = parseInt((gatewayElement || {dataset: {surcharge: 0}}).dataset.surcharge);
165 const cost = (gatewayElement || {dataset: {cost: defaultCost}}).dataset.cost;
bb7d6793 166
15a4e4c8 167 const {html, js} = await Templates.renderForPromise('core_payment/fee_breakdown', {fee: cost, surcharge});
bb7d6793
SR
168 Templates.replaceNodeContents(root.querySelector(Selectors.regions.costContainer), html, js);
169};
ed04c382
SR
170
171/**
172 * Process payment using the selected gateway.
173 *
ed04c382 174 * @param {string} gateway The gateway to be used for payment
7d10f352
SR
175 * @param {string} component Name of the component that the componentId belongs to
176 * @param {string} paymentArea Name of the area in the component that the componentId belongs to
177 * @param {number} componentId An internal identifier that is used by the component
ab6ca275 178 * @param {string} description Description of the payment
d00c00dd 179 * @param {processPaymentCallback} callback The callback function to call when processing is finished
ed04c382
SR
180 * @returns {Promise<void>}
181 */
7d10f352 182const processPayment = async(gateway, component, paymentArea, componentId, description, callback) => {
ed04c382 183 const paymentMethod = await import(`pg_${gateway}/gateways_modal`);
7d10f352 184 paymentMethod.process(component, paymentArea, componentId, description, callback);
c2321a26 185};
d00c00dd
SR
186
187/**
188 * The callback definition for processPayment.
189 *
190 * @callback processPaymentCallback
191 * @param {bool} success
192 * @param {string} message
193 */