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