Merge branch 'MDL-64723-310' of git://github.com/paulholden/moodle into MOODLE_310_STABLE
[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
9476b489
MG
27use core_payment\event\account_created;
28use core_payment\event\account_deleted;
29use core_payment\event\account_updated;
30
4865d2a0
SR
31/**
32 * Helper class for the payment subsystem.
33 *
34 * @copyright 2019 Shamim Rezaie <shamim@moodle.com>
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36 */
37class helper {
38
39 /**
40 * Returns an accumulated list of supported currencies by all payment gateways.
41 *
42 * @return string[] An array of the currency codes in the three-character ISO-4217 format
43 */
44 public static function get_supported_currencies(): array {
45 $currencies = [];
46
6b3d163a 47 $plugins = \core_plugin_manager::instance()->get_enabled_plugins('paygw');
4865d2a0 48 foreach ($plugins as $plugin) {
6b3d163a
SR
49 /** @var \paygw_paypal\gateway $classname */
50 $classname = '\paygw_' . $plugin . '\gateway';
4865d2a0 51
15a4e4c8 52 $currencies += component_class_callback($classname, 'get_supported_currencies', [], []);
4865d2a0
SR
53 }
54
55 $currencies = array_unique($currencies);
56
57 return $currencies;
58 }
f3d75264
SR
59
60 /**
61 * Returns the list of gateways that can process payments in the given currency.
62 *
15a4e4c8 63 * @param string $component
7d10f352 64 * @param string $paymentarea
52305c9a 65 * @param int $itemid
f3d75264
SR
66 * @return string[]
67 */
52305c9a 68 public static function get_available_gateways(string $component, string $paymentarea, int $itemid): array {
f3d75264
SR
69 $gateways = [];
70
b63f17b5
SR
71 $payable = static::get_payable($component, $paymentarea, $itemid);
72 $account = new account($payable->get_account_id());
73
895f38cc
MG
74 if (!$account->get('id') || !$account->get('enabled')) {
75 return $gateways;
76 }
77
b63f17b5 78 $currency = $payable->get_currency();
895f38cc
MG
79 foreach ($account->get_gateways() as $plugin => $gateway) {
80 if (!$gateway->get('enabled')) {
81 continue;
82 }
83 /** @var gateway $classname */
6b3d163a 84 $classname = '\paygw_' . $plugin . '\gateway';
f3d75264 85
15a4e4c8 86 $currencies = component_class_callback($classname, 'get_supported_currencies', [], []);
f3d75264
SR
87 if (in_array($currency, $currencies)) {
88 $gateways[] = $plugin;
89 }
90 }
91
92 return $gateways;
93 }
c2321a26 94
15a4e4c8 95 /**
90fbc58d 96 * Rounds the cost based on the currency fractional digits, can also apply surcharge
15a4e4c8
MG
97 *
98 * @param float $amount amount in the currency units
15a4e4c8 99 * @param string $currency currency, used for calculating the number of fractional digits
90fbc58d 100 * @param float $surcharge surcharge in percents
15a4e4c8
MG
101 * @return float
102 */
90fbc58d
MG
103 public static function get_rounded_cost(float $amount, string $currency, float $surcharge = 0): float {
104 $amount = $amount * (100 + $surcharge) / 100;
105
106 $locale = get_string('localecldr', 'langconfig');
107 $fmt = \NumberFormatter::create($locale, \NumberFormatter::CURRENCY);
108 $localisedcost = numfmt_format_currency($fmt, $amount, $currency);
109
110 return numfmt_parse_currency($fmt, $localisedcost, $currency);
15a4e4c8
MG
111 }
112
113 /**
90fbc58d 114 * Returns human-readable amount with correct number of fractional digits and currency indicator, can also apply surcharge
15a4e4c8 115 *
90fbc58d
MG
116 * @param float $amount amount in the currency units
117 * @param string $currency The currency
118 * @param float $surcharge surcharge in percents
15a4e4c8 119 * @return string
15a4e4c8 120 */
90fbc58d
MG
121 public static function get_cost_as_string(float $amount, string $currency, float $surcharge = 0): string {
122 $amount = $amount * (100 + $surcharge) / 100;
123
124 $locale = get_string('localecldr', 'langconfig');
125 $fmt = \NumberFormatter::create($locale, \NumberFormatter::CURRENCY);
126 $localisedcost = numfmt_format_currency($fmt, $amount, $currency);
15a4e4c8
MG
127
128 return $localisedcost;
129 }
130
1882bb47
SR
131 /**
132 * Returns the percentage of surcharge that is applied when using a gateway
133 *
134 * @param string $gateway Name of the gateway
15a4e4c8 135 * @return float
1882bb47 136 */
15a4e4c8 137 public static function get_gateway_surcharge(string $gateway): float {
6b3d163a 138 return (float)get_config('paygw_' . $gateway, 'surcharge');
1882bb47
SR
139 }
140
c2321a26
SR
141 /**
142 * Returns the attributes to place on a pay button.
143 *
52305c9a 144 * @param string $component Name of the component that the itemid belongs to
7d10f352 145 * @param string $paymentarea
52305c9a 146 * @param int $itemid An internal identifier that is used by the component
ab6ca275 147 * @param string $description Description of the payment
c2321a26
SR
148 * @return array
149 */
b63f17b5
SR
150 public static function gateways_modal_link_params(string $component, string $paymentarea, int $itemid,
151 string $description): array {
152
153 $payable = static::get_payable($component, $paymentarea, $itemid);
7e112616 154
c2321a26
SR
155 return [
156 'id' => 'gateways-modal-trigger',
157 'role' => 'button',
b63f17b5 158 'data-action' => 'core_payment/triggerPayment',
ed04c382 159 'data-component' => $component,
7d10f352 160 'data-paymentarea' => $paymentarea,
52305c9a 161 'data-itemid' => $itemid,
b63f17b5 162 'data-cost' => static::get_cost_as_string($payable->get_amount(), $payable->get_currency()),
ab6ca275 163 'data-description' => $description,
c2321a26
SR
164 ];
165 }
5337ca48
SR
166
167 /**
b63f17b5
SR
168 * @param string $component
169 * @return string
170 * @throws \coding_exception
171 */
172 private static function get_service_provider_classname(string $component) {
173 $providerclass = "$component\\payment\\service_provider";
174
175 if (class_exists($providerclass)) {
176 $rc = new \ReflectionClass($providerclass);
177 if ($rc->implementsInterface(local\callback\service_provider::class)) {
178 return $providerclass;
179 }
180 }
181
182 throw new \coding_exception("$component does not have an eligible implementation of payment service_provider.");
183 }
184
185 /**
186 * Asks the payable from the related component.
5337ca48 187 *
52305c9a 188 * @param string $component Name of the component that the itemid belongs to
7d10f352 189 * @param string $paymentarea
52305c9a 190 * @param int $itemid An internal identifier that is used by the component
b63f17b5 191 * @return local\entities\payable
5337ca48 192 */
b63f17b5
SR
193 public static function get_payable(string $component, string $paymentarea, int $itemid): local\entities\payable {
194 $providerclass = static::get_service_provider_classname($component);
5337ca48 195
b63f17b5 196 return component_class_callback($providerclass, 'get_payable', [$paymentarea, $itemid]);
5337ca48
SR
197 }
198
895f38cc
MG
199 /**
200 * Returns the gateway configuration for given component and gateway
201 *
202 * @param string $component
7d10f352 203 * @param string $paymentarea
52305c9a 204 * @param int $itemid
895f38cc
MG
205 * @param string $gatewayname
206 * @return array
207 * @throws \moodle_exception
208 */
52305c9a 209 public static function get_gateway_configuration(string $component, string $paymentarea, int $itemid,
7d10f352 210 string $gatewayname): array {
b63f17b5 211 $payable = self::get_payable($component, $paymentarea, $itemid);
895f38cc 212 $gateway = null;
b63f17b5 213 $account = new account($payable->get_account_id());
895f38cc
MG
214 if ($account && $account->get('enabled')) {
215 $gateway = $account->get_gateways()[$gatewayname] ?? null;
216 }
217 if (!$gateway) {
218 throw new \moodle_exception('gatewaynotfound', 'payment');
219 }
220 return $gateway->get_configuration();
221 }
222
5337ca48
SR
223 /**
224 * Delivers what the user paid for.
225 *
b63f17b5 226 * @uses \core_payment\local\callback\service_provider::deliver_order()
15a4e4c8 227 *
52305c9a 228 * @param string $component Name of the component that the itemid belongs to
7d10f352 229 * @param string $paymentarea
52305c9a 230 * @param int $itemid An internal identifier that is used by the component
15a4e4c8 231 * @param int $paymentid payment id as inserted into the 'payments' table, if needed for reference
b63f17b5 232 * @param int $userid The userid the order is going to deliver to
5337ca48 233 * @return bool Whether successful or not
5337ca48 234 */
b63f17b5
SR
235 public static function deliver_order(string $component, string $paymentarea, int $itemid, int $paymentid, int $userid): bool {
236 $providerclass = static::get_service_provider_classname($component);
237 $result = component_class_callback($providerclass, 'deliver_order', [$paymentarea, $itemid, $paymentid, $userid]);
5337ca48
SR
238
239 return $result;
240 }
3c3b43a5
SR
241
242 /**
243 * Stores essential information about the payment and returns the "id" field of the payment record in DB.
244 * Each payment gateway may then store the additional information their way.
245 *
15a4e4c8 246 * @param int $accountid Account id
52305c9a 247 * @param string $component Name of the component that the itemid belongs to
7d10f352 248 * @param string $paymentarea
52305c9a 249 * @param int $itemid An internal identifier that is used by the component
3c3b43a5
SR
250 * @param int $userid Id of the user who is paying
251 * @param float $amount Amount of payment
252 * @param string $currency Currency of payment
253 * @param string $gateway The gateway that is used for the payment
254 * @return int
255 */
52305c9a 256 public static function save_payment(int $accountid, string $component, string $paymentarea, int $itemid, int $userid,
7d10f352 257 float $amount, string $currency, string $gateway): int {
3c3b43a5
SR
258 global $DB;
259
260 $record = new \stdClass();
261 $record->component = $component;
7d10f352 262 $record->paymentarea = $paymentarea;
52305c9a 263 $record->itemid = $itemid;
3c3b43a5
SR
264 $record->userid = $userid;
265 $record->amount = $amount;
266 $record->currency = $currency;
267 $record->gateway = $gateway;
15a4e4c8 268 $record->accountid = $accountid;
3c3b43a5
SR
269 $record->timecreated = $record->timemodified = time();
270
271 $id = $DB->insert_record('payments', $record);
272
273 return $id;
274 }
1882bb47
SR
275
276 /**
277 * This functions adds the settings that are common for all payment gateways.
278 *
279 * @param \admin_settingpage $settings The settings object
6b3d163a 280 * @param string $gateway The gateway name prefixed with paygw_
1882bb47
SR
281 */
282 public static function add_common_gateway_settings(\admin_settingpage $settings, string $gateway): void {
283 $settings->add(new \admin_setting_configtext($gateway . '/surcharge', get_string('surcharge', 'core_payment'),
284 get_string('surcharge_desc', 'core_payment'), 0, PARAM_INT));
285
286 }
895f38cc
MG
287
288 /**
289 * Save a new or edited payment account (used in management interface)
290 *
291 * @param \stdClass $data
9476b489 292 * @return account
895f38cc 293 */
9476b489 294 public static function save_payment_account(\stdClass $data): account {
895f38cc
MG
295
296 if (empty($data->id)) {
297 $account = new account(0, $data);
9476b489
MG
298 $account->save();
299 account_created::create_from_account($account)->trigger();
895f38cc
MG
300 } else {
301 $account = new account($data->id);
302 $account->from_record($data);
9476b489
MG
303 $account->save();
304 account_updated::create_from_account($account)->trigger();
895f38cc
MG
305 }
306
9476b489 307 return $account;
895f38cc
MG
308 }
309
310 /**
311 * Delete a payment account (used in management interface)
312 *
313 * @param account $account
314 */
9476b489
MG
315 public static function delete_payment_account(account $account): void {
316 global $DB;
317 if ($DB->record_exists('payments', ['accountid' => $account->get('id')])) {
318 $account->set('archived', 1);
319 $account->save();
320 account_updated::create_from_account($account, ['archived' => 1])->trigger();
321 return;
322 }
323
895f38cc
MG
324 foreach ($account->get_gateways(false) as $gateway) {
325 if ($gateway->get('id')) {
326 $gateway->delete();
327 }
328 }
9476b489 329 $event = account_deleted::create_from_account($account);
895f38cc 330 $account->delete();
9476b489
MG
331 $event->trigger();
332 }
333
334 /**
335 * Restore archived payment account (used in management interface)
336 *
337 * @param account $account
338 */
339 public static function restore_payment_account(account $account): void {
340 $account->set('archived', 0);
341 $account->save();
342 account_updated::create_from_account($account, ['restored' => 1])->trigger();
895f38cc
MG
343 }
344
345 /**
346 * Save a payment gateway linked to an existing account (used in management interface)
347 *
348 * @param \stdClass $data
9476b489 349 * @return account_gateway
895f38cc 350 */
9476b489 351 public static function save_payment_gateway(\stdClass $data): account_gateway {
895f38cc 352 if (empty($data->id)) {
9476b489
MG
353 $records = account_gateway::get_records(['accountid' => $data->accountid, 'gateway' => $data->gateway]);
354 if ($records) {
355 $gateway = reset($records);
356 } else {
357 $gateway = new account_gateway(0, $data);
358 }
895f38cc
MG
359 } else {
360 $gateway = new account_gateway($data->id);
895f38cc 361 }
9476b489
MG
362 unset($data->accountid, $data->gateway, $data->id);
363 $gateway->from_record($data);
895f38cc 364
9476b489 365 $account = $gateway->get_account();
895f38cc 366 $gateway->save();
9476b489
MG
367 account_updated::create_from_account($account)->trigger();
368 return $gateway;
895f38cc
MG
369 }
370
371 /**
372 * Returns the list of payment accounts in the given context (used in management interface)
373 *
374 * @param \context $context
375 * @return account[]
376 */
9476b489
MG
377 public static function get_payment_accounts_to_manage(\context $context, bool $showarchived = false): array {
378 $records = account::get_records(['contextid' => $context->id] + ($showarchived ? [] : ['archived' => 0]));
379 \core_collator::asort_objects_by_method($records, 'get_formatted_name');
380 return $records;
895f38cc
MG
381 }
382
383 /**
384 * Get list of accounts available in the given context
385 *
386 * @param \context $context
387 * @return array
388 */
389 public static function get_payment_accounts_menu(\context $context): array {
390 global $DB;
391 [$sql, $params] = $DB->get_in_or_equal($context->get_parent_context_ids(true));
392 $accounts = array_filter(account::get_records_select('contextid '.$sql, $params), function($account) {
9476b489 393 return $account->is_available() && !$account->get('archived');
895f38cc
MG
394 });
395 return array_map(function($account) {
396 return $account->get_formatted_name();
397 }, $accounts);
398 }
4865d2a0 399}