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