MDL-69166 core_payment: Show cost on the modal when no gateway is chosen
[moodle.git] / payment / classes / helper.php
CommitLineData
4865d2a0
SR
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * Contains helper class for the payment subsystem.
19 *
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
25namespace core_payment;
26
27defined('MOODLE_INTERNAL') || die();
28
29/**
30 * Helper class for the payment subsystem.
31 *
32 * @copyright 2019 Shamim Rezaie <shamim@moodle.com>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 */
35class helper {
36
37 /**
38 * Returns an accumulated list of supported currencies by all payment gateways.
39 *
40 * @return string[] An array of the currency codes in the three-character ISO-4217 format
41 */
42 public static function get_supported_currencies(): array {
43 $currencies = [];
44
45 $plugins = \core_plugin_manager::instance()->get_enabled_plugins('pg');
46 foreach ($plugins as $plugin) {
895f38cc 47 /** @var \pg_paypal\gateway $classname */
4865d2a0
SR
48 $classname = '\pg_' . $plugin . '\gateway';
49
15a4e4c8 50 $currencies += component_class_callback($classname, 'get_supported_currencies', [], []);
4865d2a0
SR
51 }
52
53 $currencies = array_unique($currencies);
54
55 return $currencies;
56 }
f3d75264
SR
57
58 /**
59 * Returns the list of gateways that can process payments in the given currency.
60 *
15a4e4c8
MG
61 * @param string $component
62 * @param int $componentid
f3d75264
SR
63 * @return string[]
64 */
15a4e4c8 65 public static function get_gateways_for_currency(string $component, int $componentid): array {
f3d75264
SR
66 $gateways = [];
67
15a4e4c8
MG
68 [
69 'amount' => $amount,
70 'currency' => $currency,
71 'accountid' => $accountid,
72 ] = self::get_cost($component, $componentid);
895f38cc
MG
73 $account = new account($accountid);
74 if (!$account->get('id') || !$account->get('enabled')) {
75 return $gateways;
76 }
77
78 foreach ($account->get_gateways() as $plugin => $gateway) {
79 if (!$gateway->get('enabled')) {
80 continue;
81 }
82 /** @var gateway $classname */
f3d75264
SR
83 $classname = '\pg_' . $plugin . '\gateway';
84
15a4e4c8 85 $currencies = component_class_callback($classname, 'get_supported_currencies', [], []);
f3d75264
SR
86 if (in_array($currency, $currencies)) {
87 $gateways[] = $plugin;
88 }
89 }
90
91 return $gateways;
92 }
c2321a26 93
15a4e4c8
MG
94 /**
95 * Calculates the cost with the surcharge
96 *
97 * @param float $amount amount in the currency units
98 * @param float $surcharge surcharge in percents
99 * @param string $currency currency, used for calculating the number of fractional digits
100 * @return float
101 */
102 public static function get_cost_with_surcharge(float $amount, float $surcharge, string $currency): float {
103 return round($amount + $amount * $surcharge / 100, 2); // TODO number of digits depends on currency.
104 }
105
106 /**
107 * Returns human-readable amount with fixed number of fractional digits and currency indicator
108 *
109 * @param float $amount
110 * @param string $currency
111 * @return string
112 * @throws \coding_exception
113 */
114 public static function get_cost_as_string(float $amount, string $currency): string {
115 if (class_exists('NumberFormatter') && function_exists('numfmt_format_currency')) {
116 $locale = get_string('localecldr', 'langconfig');
117 $fmt = \NumberFormatter::create($locale, \NumberFormatter::CURRENCY);
118 $localisedcost = numfmt_format_currency($fmt, $amount, $currency);
119 } else {
120 $localisedcost = sprintf("%.2f %s", $amount, $currency); // TODO number of digits depends on currency.
121 }
122
123 return $localisedcost;
124 }
125
1882bb47
SR
126 /**
127 * Returns the percentage of surcharge that is applied when using a gateway
128 *
129 * @param string $gateway Name of the gateway
15a4e4c8 130 * @return float
1882bb47 131 */
15a4e4c8
MG
132 public static function get_gateway_surcharge(string $gateway): float {
133 return (float)get_config('pg_' . $gateway, 'surcharge');
1882bb47
SR
134 }
135
c2321a26
SR
136 /**
137 * Returns the attributes to place on a pay button.
138 *
ab6ca275
SR
139 * @param string $component Name of the component that the componentid belongs to
140 * @param int $componentid An internal identifier that is used by the component
141 * @param string $description Description of the payment
c2321a26
SR
142 * @return array
143 */
15a4e4c8 144 public static function gateways_modal_link_params(string $component, int $componentid, string $description): array {
7e112616
SR
145 [
146 'amount' => $amount,
147 'currency' => $currency
148 ] = self::get_cost($component, $componentid);
149
c2321a26
SR
150 return [
151 'id' => 'gateways-modal-trigger',
152 'role' => 'button',
ed04c382
SR
153 'data-component' => $component,
154 'data-componentid' => $componentid,
7e112616 155 'data-cost' => self::get_cost_as_string($amount, $currency),
ab6ca275 156 'data-description' => $description,
c2321a26
SR
157 ];
158 }
5337ca48
SR
159
160 /**
161 * Asks the cost from the related component.
162 *
163 * @param string $component Name of the component that the componentid belongs to
164 * @param int $componentid An internal identifier that is used by the component
895f38cc 165 * @return array['amount' => float, 'currency' => string, 'accountid' => int]
5337ca48
SR
166 * @throws \moodle_exception
167 */
168 public static function get_cost(string $component, int $componentid): array {
169 $cost = component_class_callback("$component\\payment\\provider", 'get_cost', [$componentid]);
170
895f38cc
MG
171 if ($cost === null || !is_array($cost) || !array_key_exists('amount', $cost)
172 || !array_key_exists('currency', $cost) || !array_key_exists('accountid', $cost) ) {
5337ca48
SR
173 throw new \moodle_exception('callbacknotimplemented', 'core_payment', '', $component);
174 }
175
176 return $cost;
177 }
178
895f38cc
MG
179 /**
180 * Returns the gateway configuration for given component and gateway
181 *
182 * @param string $component
183 * @param int $componentid
184 * @param string $gatewayname
185 * @return array
186 * @throws \moodle_exception
187 */
188 public static function get_gateway_configuration(string $component, int $componentid, string $gatewayname): array {
189 $x = self::get_cost($component, $componentid);
190 $gateway = null;
191 $account = new account($x['accountid']);
192 if ($account && $account->get('enabled')) {
193 $gateway = $account->get_gateways()[$gatewayname] ?? null;
194 }
195 if (!$gateway) {
196 throw new \moodle_exception('gatewaynotfound', 'payment');
197 }
198 return $gateway->get_configuration();
199 }
200
5337ca48
SR
201 /**
202 * Delivers what the user paid for.
203 *
15a4e4c8
MG
204 * @uses \core_payment\local\callback\provider::deliver_order()
205 *
5337ca48
SR
206 * @param string $component Name of the component that the componentid belongs to
207 * @param int $componentid An internal identifier that is used by the component
15a4e4c8 208 * @param int $paymentid payment id as inserted into the 'payments' table, if needed for reference
5337ca48 209 * @return bool Whether successful or not
5337ca48 210 */
15a4e4c8
MG
211 public static function deliver_order(string $component, int $componentid, int $paymentid): bool {
212 $result = component_class_callback("$component\\payment\\provider", 'deliver_order', [$componentid, $paymentid]);
5337ca48
SR
213
214 if ($result === null) {
215 throw new \moodle_exception('callbacknotimplemented', 'core_payment', '', $component);
216 }
217
218 return $result;
219 }
3c3b43a5
SR
220
221 /**
222 * Stores essential information about the payment and returns the "id" field of the payment record in DB.
223 * Each payment gateway may then store the additional information their way.
224 *
15a4e4c8 225 * @param int $accountid Account id
3c3b43a5
SR
226 * @param string $component Name of the component that the componentid belongs to
227 * @param int $componentid An internal identifier that is used by the component
228 * @param int $userid Id of the user who is paying
229 * @param float $amount Amount of payment
230 * @param string $currency Currency of payment
231 * @param string $gateway The gateway that is used for the payment
232 * @return int
233 */
15a4e4c8 234 public static function save_payment(int $accountid, string $component, int $componentid, int $userid, float $amount, string $currency,
3c3b43a5
SR
235 string $gateway): int {
236 global $DB;
237
238 $record = new \stdClass();
239 $record->component = $component;
240 $record->componentid = $componentid;
241 $record->userid = $userid;
242 $record->amount = $amount;
243 $record->currency = $currency;
244 $record->gateway = $gateway;
15a4e4c8 245 $record->accountid = $accountid;
3c3b43a5
SR
246 $record->timecreated = $record->timemodified = time();
247
248 $id = $DB->insert_record('payments', $record);
249
250 return $id;
251 }
1882bb47
SR
252
253 /**
254 * This functions adds the settings that are common for all payment gateways.
255 *
256 * @param \admin_settingpage $settings The settings object
257 * @param string $gateway The gateway name prefic with pg_
258 */
259 public static function add_common_gateway_settings(\admin_settingpage $settings, string $gateway): void {
260 $settings->add(new \admin_setting_configtext($gateway . '/surcharge', get_string('surcharge', 'core_payment'),
261 get_string('surcharge_desc', 'core_payment'), 0, PARAM_INT));
262
263 }
895f38cc
MG
264
265 /**
266 * Save a new or edited payment account (used in management interface)
267 *
268 * @param \stdClass $data
269 */
270 public static function save_payment_account(\stdClass $data) {
271
272 if (empty($data->id)) {
273 $account = new account(0, $data);
274 } else {
275 $account = new account($data->id);
276 $account->from_record($data);
277 }
278
279 $account->save();
280 // TODO trigger event.
281 }
282
283 /**
284 * Delete a payment account (used in management interface)
285 *
286 * @param account $account
287 */
288 public static function delete_payment_account(account $account) {
289 foreach ($account->get_gateways(false) as $gateway) {
290 if ($gateway->get('id')) {
291 $gateway->delete();
292 }
293 }
294 $account->delete();
295 // TODO trigger event.
296 }
297
298 /**
299 * Save a payment gateway linked to an existing account (used in management interface)
300 *
301 * @param \stdClass $data
302 */
303 public static function save_payment_gateway(\stdClass $data) {
304 if (empty($data->id)) {
305 $gateway = new account_gateway(0, $data);
306 } else {
307 $gateway = new account_gateway($data->id);
308 unset($data->accountid, $data->gateway, $data->id);
309 $gateway->from_record($data);
310 }
311
312 $gateway->save();
313 // TODO trigger event.
314 }
315
316 /**
317 * Returns the list of payment accounts in the given context (used in management interface)
318 *
319 * @param \context $context
320 * @return account[]
321 */
322 public static function get_payment_accounts_to_manage(\context $context): array {
323 return account::get_records(['contextid' => $context->id]);
324 }
325
326 /**
327 * Get list of accounts available in the given context
328 *
329 * @param \context $context
330 * @return array
331 */
332 public static function get_payment_accounts_menu(\context $context): array {
333 global $DB;
334 [$sql, $params] = $DB->get_in_or_equal($context->get_parent_context_ids(true));
335 $accounts = array_filter(account::get_records_select('contextid '.$sql, $params), function($account) {
336 return $account->is_available();
337 });
338 return array_map(function($account) {
339 return $account->get_formatted_name();
340 }, $accounts);
341 }
4865d2a0 342}