MDL-69166 core_payment: improvements to api, small fixes
[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 {
c2321a26
SR
145 return [
146 'id' => 'gateways-modal-trigger',
147 'role' => 'button',
ed04c382
SR
148 'data-component' => $component,
149 'data-componentid' => $componentid,
ab6ca275 150 'data-description' => $description,
c2321a26
SR
151 ];
152 }
5337ca48
SR
153
154 /**
155 * Asks the cost from the related component.
156 *
157 * @param string $component Name of the component that the componentid belongs to
158 * @param int $componentid An internal identifier that is used by the component
895f38cc 159 * @return array['amount' => float, 'currency' => string, 'accountid' => int]
5337ca48
SR
160 * @throws \moodle_exception
161 */
162 public static function get_cost(string $component, int $componentid): array {
163 $cost = component_class_callback("$component\\payment\\provider", 'get_cost', [$componentid]);
164
895f38cc
MG
165 if ($cost === null || !is_array($cost) || !array_key_exists('amount', $cost)
166 || !array_key_exists('currency', $cost) || !array_key_exists('accountid', $cost) ) {
5337ca48
SR
167 throw new \moodle_exception('callbacknotimplemented', 'core_payment', '', $component);
168 }
169
170 return $cost;
171 }
172
895f38cc
MG
173 /**
174 * Returns the gateway configuration for given component and gateway
175 *
176 * @param string $component
177 * @param int $componentid
178 * @param string $gatewayname
179 * @return array
180 * @throws \moodle_exception
181 */
182 public static function get_gateway_configuration(string $component, int $componentid, string $gatewayname): array {
183 $x = self::get_cost($component, $componentid);
184 $gateway = null;
185 $account = new account($x['accountid']);
186 if ($account && $account->get('enabled')) {
187 $gateway = $account->get_gateways()[$gatewayname] ?? null;
188 }
189 if (!$gateway) {
190 throw new \moodle_exception('gatewaynotfound', 'payment');
191 }
192 return $gateway->get_configuration();
193 }
194
5337ca48
SR
195 /**
196 * Delivers what the user paid for.
197 *
15a4e4c8
MG
198 * @uses \core_payment\local\callback\provider::deliver_order()
199 *
5337ca48
SR
200 * @param string $component Name of the component that the componentid belongs to
201 * @param int $componentid An internal identifier that is used by the component
15a4e4c8 202 * @param int $paymentid payment id as inserted into the 'payments' table, if needed for reference
5337ca48 203 * @return bool Whether successful or not
5337ca48 204 */
15a4e4c8
MG
205 public static function deliver_order(string $component, int $componentid, int $paymentid): bool {
206 $result = component_class_callback("$component\\payment\\provider", 'deliver_order', [$componentid, $paymentid]);
5337ca48
SR
207
208 if ($result === null) {
209 throw new \moodle_exception('callbacknotimplemented', 'core_payment', '', $component);
210 }
211
212 return $result;
213 }
3c3b43a5
SR
214
215 /**
216 * Stores essential information about the payment and returns the "id" field of the payment record in DB.
217 * Each payment gateway may then store the additional information their way.
218 *
15a4e4c8 219 * @param int $accountid Account id
3c3b43a5
SR
220 * @param string $component Name of the component that the componentid belongs to
221 * @param int $componentid An internal identifier that is used by the component
222 * @param int $userid Id of the user who is paying
223 * @param float $amount Amount of payment
224 * @param string $currency Currency of payment
225 * @param string $gateway The gateway that is used for the payment
226 * @return int
227 */
15a4e4c8 228 public static function save_payment(int $accountid, string $component, int $componentid, int $userid, float $amount, string $currency,
3c3b43a5
SR
229 string $gateway): int {
230 global $DB;
231
232 $record = new \stdClass();
233 $record->component = $component;
234 $record->componentid = $componentid;
235 $record->userid = $userid;
236 $record->amount = $amount;
237 $record->currency = $currency;
238 $record->gateway = $gateway;
15a4e4c8 239 $record->accountid = $accountid;
3c3b43a5
SR
240 $record->timecreated = $record->timemodified = time();
241
242 $id = $DB->insert_record('payments', $record);
243
244 return $id;
245 }
1882bb47
SR
246
247 /**
248 * This functions adds the settings that are common for all payment gateways.
249 *
250 * @param \admin_settingpage $settings The settings object
251 * @param string $gateway The gateway name prefic with pg_
252 */
253 public static function add_common_gateway_settings(\admin_settingpage $settings, string $gateway): void {
254 $settings->add(new \admin_setting_configtext($gateway . '/surcharge', get_string('surcharge', 'core_payment'),
255 get_string('surcharge_desc', 'core_payment'), 0, PARAM_INT));
256
257 }
895f38cc
MG
258
259 /**
260 * Save a new or edited payment account (used in management interface)
261 *
262 * @param \stdClass $data
263 */
264 public static function save_payment_account(\stdClass $data) {
265
266 if (empty($data->id)) {
267 $account = new account(0, $data);
268 } else {
269 $account = new account($data->id);
270 $account->from_record($data);
271 }
272
273 $account->save();
274 // TODO trigger event.
275 }
276
277 /**
278 * Delete a payment account (used in management interface)
279 *
280 * @param account $account
281 */
282 public static function delete_payment_account(account $account) {
283 foreach ($account->get_gateways(false) as $gateway) {
284 if ($gateway->get('id')) {
285 $gateway->delete();
286 }
287 }
288 $account->delete();
289 // TODO trigger event.
290 }
291
292 /**
293 * Save a payment gateway linked to an existing account (used in management interface)
294 *
295 * @param \stdClass $data
296 */
297 public static function save_payment_gateway(\stdClass $data) {
298 if (empty($data->id)) {
299 $gateway = new account_gateway(0, $data);
300 } else {
301 $gateway = new account_gateway($data->id);
302 unset($data->accountid, $data->gateway, $data->id);
303 $gateway->from_record($data);
304 }
305
306 $gateway->save();
307 // TODO trigger event.
308 }
309
310 /**
311 * Returns the list of payment accounts in the given context (used in management interface)
312 *
313 * @param \context $context
314 * @return account[]
315 */
316 public static function get_payment_accounts_to_manage(\context $context): array {
317 return account::get_records(['contextid' => $context->id]);
318 }
319
320 /**
321 * Get list of accounts available in the given context
322 *
323 * @param \context $context
324 * @return array
325 */
326 public static function get_payment_accounts_menu(\context $context): array {
327 global $DB;
328 [$sql, $params] = $DB->get_in_or_equal($context->get_parent_context_ids(true));
329 $accounts = array_filter(account::get_records_select('contextid '.$sql, $params), function($account) {
330 return $account->is_available();
331 });
332 return array_map(function($account) {
333 return $account->get_formatted_name();
334 }, $accounts);
335 }
4865d2a0 336}