Initial go at cleaning up repeattransaction
[civicrm-core.git] / api / v3 / Contribution.php
CommitLineData
6a488035 1<?php
6a488035
TO
2/*
3 +--------------------------------------------------------------------+
a30c801b 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
a30c801b
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
b081365f 13 * This api exposes CiviCRM Contribution records.
6a488035
TO
14 *
15 * @package CiviCRM_APIv3
6a488035
TO
16 */
17
0552d667
EM
18use Civi\Api4\Contribution;
19
6a488035 20/**
244bbdd8 21 * Add or update a Contribution.
6a488035 22 *
cf470720 23 * @param array $params
9d32e6f7 24 * Input parameters.
6a488035 25 *
69dbd1ba 26 * @throws API_Exception
a6c01b45 27 * @return array
72b3a70c 28 * Api result array
6a488035 29 */
1c31aa41 30function civicrm_api3_contribution_create($params) {
cf8f0fff 31 $values = [];
6a488035 32 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
504a78f6 33 $params = array_merge($params, $values);
83644f47 34 // The BAO should not clean money - it should be done in the form layer & api wrapper
35 // (although arguably the api should expect pre-cleaned it seems to do some cleaning.)
4750ab01 36 if (empty($params['skipCleanMoney'])) {
bb35c5f3 37 foreach (['total_amount', 'net_amount', 'fee_amount', 'non_deductible_amount'] as $field) {
4750ab01 38 if (isset($params[$field])) {
39 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
40 }
41 }
42 }
83644f47 43 $params['skipCleanMoney'] = TRUE;
504a78f6 44
0552d667
EM
45 if (!empty($params['check_permissions'])) {
46 // Check acls on this entity. Note that we pass in financial type id, if we have it
47 // since we know this is checked by acls. In v4 we do something more generic.
48 if (!Contribution::checkAccess()
49 ->setAction(empty($params['id']) ? 'create' : 'update')
50 ->addValue('id', $params['id'] ?? NULL)
51 ->addValue('financial_type_id', $params['financial_type_id'] ?? NULL)
52 ->execute()->first()['access']) {
ae2ade98 53 throw new API_Exception('You do not have permission to create this contribution');
3300bf67 54 }
816cac04 55 }
8cc574cf 56 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
cf8f0fff 57 $error = [];
504a78f6 58 //throw error for invalid status change such as setting completed back to pending
59 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
60 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
61 CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
62 if (array_key_exists('contribution_status_id', $error)) {
63 throw new API_Exception($error['contribution_status_id']);
64 }
6a488035 65 }
4d47ad17 66 if (!empty($params['id']) && !empty($params['financial_type_id'])) {
cf8f0fff 67 $error = [];
4d47ad17
PN
68 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange($params['financial_type_id'], $params['id'], $error);
69 if (array_key_exists('financial_type_id', $error)) {
70 throw new API_Exception($error['financial_type_id']);
71 }
72 }
8da4799e
EM
73 if (!isset($params['tax_amount']) && empty($params['line_item'])
74 && empty($params['skipLineItem'])
75 && empty($params['id'])
76 ) {
77 $taxRates = CRM_Core_PseudoConstant::getTaxRates();
78 $taxRate = $taxRates[$params['financial_type_id']] ?? 0;
79 if ($taxRate) {
80 // Be afraid - historically if a contribution was tax then the passed in amount is EXCLUSIVE
81 $params['tax_amount'] = $params['total_amount'] * ($taxRate / 100);
82 $params['total_amount'] += $params['tax_amount'];
83 }
84 }
6a516bd6
DG
85 _civicrm_api3_contribution_create_legacy_support_45($params);
86
504a78f6 87 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
6a488035 88}
11e09c59
TO
89
90/**
0aa0303c
EM
91 * Adjust Metadata for Create action.
92 *
93 * The metadata is used for setting defaults, documentation & validation.
6a488035 94 *
cf470720 95 * @param array $params
b081365f 96 * Array of parameters determined by getfields.
6a488035
TO
97 */
98function _civicrm_api3_contribution_create_spec(&$params) {
99 $params['contact_id']['api.required'] = 1;
100 $params['total_amount']['api.required'] = 1;
cf8f0fff 101 $params['payment_instrument_id']['api.aliases'] = ['payment_instrument'];
8757a378 102 $params['receive_date']['api.default'] = 'now';
2b0fe7ac 103 $params['receive_date']['api.required'] = TRUE;
cf8f0fff 104 $params['payment_processor'] = [
6a488035
TO
105 'name' => 'payment_processor',
106 'title' => 'Payment Processor ID',
107 'description' => 'ID of payment processor used for this contribution',
108 // field is called payment processor - not payment processor id but can only be one id so
109 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
cf8f0fff 110 'api.aliases' => ['payment_processor_id'],
d142432b 111 'type' => CRM_Utils_Type::T_INT,
cf8f0fff
CW
112 ];
113 $params['financial_type_id']['api.aliases'] = ['contribution_type_id', 'contribution_type'];
6a488035 114 $params['financial_type_id']['api.required'] = 1;
cf8f0fff 115 $params['note'] = [
6a488035
TO
116 'name' => 'note',
117 'uniqueName' => 'contribution_note',
118 'title' => 'note',
119 'type' => 2,
120 'description' => 'Associated Note in the notes table',
cf8f0fff
CW
121 ];
122 $params['soft_credit_to'] = [
6a488035 123 'name' => 'soft_credit_to',
33a429d4 124 'title' => 'Soft Credit contact ID (legacy)',
797d4c52 125 'type' => CRM_Utils_Type::T_INT,
33a429d4 126 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
6a488035 127 'FKClassName' => 'CRM_Contact_DAO_Contact',
cf8f0fff
CW
128 ];
129 $params['honor_contact_id'] = [
6a516bd6 130 'name' => 'honor_contact_id',
33a429d4 131 'title' => 'Honoree contact ID (legacy)',
797d4c52 132 'type' => CRM_Utils_Type::T_INT,
33a429d4 133 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
6a516bd6 134 'FKClassName' => 'CRM_Contact_DAO_Contact',
cf8f0fff
CW
135 ];
136 $params['honor_type_id'] = [
33a429d4
CW
137 'name' => 'honor_type_id',
138 'title' => 'Honoree Type (legacy)',
797d4c52 139 'type' => CRM_Utils_Type::T_INT,
33a429d4
CW
140 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
141 'pseudoconstant' => TRUE,
cf8f0fff 142 ];
6a488035 143 // note this is a recommended option but not adding as a default to avoid
c206647d 144 // creating unnecessary changes for the dev
cf8f0fff 145 $params['skipRecentView'] = [
6a488035
TO
146 'name' => 'skipRecentView',
147 'title' => 'Skip adding to recent view',
0900b21e 148 'type' => CRM_Utils_Type::T_BOOLEAN,
6a488035 149 'description' => 'Do not add to recent view (setting this improves performance)',
cf8f0fff
CW
150 ];
151 $params['skipLineItem'] = [
6a488035
TO
152 'name' => 'skipLineItem',
153 'title' => 'Skip adding line items',
b3b7f4c5 154 'type' => CRM_Utils_Type::T_BOOLEAN,
6a488035
TO
155 'api.default' => 0,
156 'description' => 'Do not add line items by default (if you wish to add your own)',
cf8f0fff
CW
157 ];
158 $params['batch_id'] = [
599c61ac 159 'title' => 'Batch',
797d4c52 160 'type' => CRM_Utils_Type::T_INT,
599c61ac 161 'description' => 'Batch which relevant transactions should be added to',
cf8f0fff
CW
162 ];
163 $params['refund_trxn_id'] = [
797d4c52 164 'title' => 'Refund Transaction ID',
165 'type' => CRM_Utils_Type::T_STRING,
166 'description' => 'Transaction ID specific to the refund taking place',
cf8f0fff
CW
167 ];
168 $params['card_type_id'] = [
a55e39e9 169 'title' => 'Card Type ID',
170 'description' => 'Providing Credit Card Type ID',
171 'type' => CRM_Utils_Type::T_INT,
cf8f0fff 172 'pseudoconstant' => [
a55e39e9 173 'optionGroupName' => 'accept_creditcard',
cf8f0fff
CW
174 ],
175 ];
6a488035
TO
176}
177
6a516bd6 178/**
9d32e6f7
EM
179 * Support for schema changes made in 4.5.
180 *
35671d00
TO
181 * The main purpose of the API is to provide integrators a level of stability not provided by
182 * the core code or schema - this means we have to provide support for api calls (where possible)
183 * across schema changes.
dc64d047 184 *
d0997921 185 * @param array $params
35671d00 186 */
9b873358 187function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
6a516bd6 188 //legacy soft credit handling - recommended approach is chaining
9b873358 189 if (!empty($params['soft_credit_to'])) {
cf8f0fff 190 $params['soft_credit'][] = [
6a516bd6
DG
191 'contact_id' => $params['soft_credit_to'],
192 'amount' => $params['total_amount'],
21dfd5f5 193 'soft_credit_type_id' => CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"),
cf8f0fff 194 ];
6a516bd6 195 }
9b873358 196 if (!empty($params['honor_contact_id'])) {
cf8f0fff 197 $params['soft_credit'][] = [
6a516bd6
DG
198 'contact_id' => $params['honor_contact_id'],
199 'amount' => $params['total_amount'],
a28ce73f 200 'soft_credit_type_id' => CRM_Utils_Array::value('honor_type_id', $params, CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'in_honor_of')),
cf8f0fff 201 ];
6a516bd6
DG
202 }
203}
204
6a488035 205/**
244bbdd8 206 * Delete a Contribution.
6a488035 207 *
cf470720 208 * @param array $params
9d32e6f7 209 * Input parameters.
6a488035 210 *
9d32e6f7 211 * @return array
ae2ade98 212 * @throws \API_Exception
6a488035
TO
213 */
214function civicrm_api3_contribution_delete($params) {
215
0d8afee2 216 $contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
70da3927 217 if (!empty($params['check_permissions']) && !\Civi\Api4\Utils\CoreUtil::checkAccessDelegated('Contribution', 'delete', ['id' => $contributionID], CRM_Core_Session::getLoggedInContactID() ?: 0)) {
ae2ade98 218 throw new API_Exception('You do not have permission to delete this contribution');
c93fecd1 219 }
6a488035 220 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
cf8f0fff 221 return civicrm_api3_create_success([$contributionID => 1]);
6a488035 222 }
9cef6066 223 throw new API_Exception('Could not delete contribution');
6a488035 224}
11e09c59
TO
225
226/**
9d32e6f7
EM
227 * Modify metadata for delete action.
228 *
229 * Legacy support for contribution_id.
230 *
d0997921 231 * @param array $params
6a488035
TO
232 */
233function _civicrm_api3_contribution_delete_spec(&$params) {
cf8f0fff 234 $params['id']['api.aliases'] = ['contribution_id'];
6a488035
TO
235}
236
237/**
35823763 238 * Retrieve a set of contributions.
6a488035 239 *
cf470720 240 * @param array $params
35823763 241 * Input parameters.
69dbd1ba 242 *
a6c01b45 243 * @return array
16b10e64 244 * Array of contributions, if error an array with an error id and error message
6a488035
TO
245 */
246function civicrm_api3_contribution_get($params) {
247
82f7d8b2 248 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
3123273f 249 $additionalOptions = _civicrm_api3_contribution_get_support_nonunique_returns($params);
be81f101 250 $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties($mode);
6a488035 251
5062a7b3 252 // Get the contributions based on parameters passed in
3123273f 253 $contributions = _civicrm_api3_get_using_query_object('Contribution', $params, $additionalOptions, NULL, $mode, $returnProperties);
5062a7b3
MWMC
254 if (!empty($contributions)) {
255 $softContributions = CRM_Contribute_BAO_ContributionSoft::getSoftCreditContributionFields(array_keys($contributions), TRUE);
256 foreach ($contributions as $id => $contribution) {
257 $contributions[$id] = isset($softContributions[$id]) ? array_merge($contribution, $softContributions[$id]) : $contribution;
258 // format soft credit for backward compatibility
259 _civicrm_api3_format_soft_credit($contributions[$id]);
260 _civicrm_api3_contribution_add_supported_fields($contributions[$id]);
261 }
6a488035 262 }
be81f101 263 return civicrm_api3_create_success($contributions, $params, 'Contribution', 'get');
9ae25b56 264}
265
3123273f 266/**
267 * Fix the return values to reflect cases where the schema has been changed.
268 *
269 * At the query object level using uniquenames dismbiguates between tables.
270 *
271 * However, adding uniquename can change inputs accepted by the api, so we need
272 * to ensure we are asking for the unique name return fields.
273 *
274 * @param array $params
275 *
276 * @return array
277 * @throws \API_Exception
278 */
279function _civicrm_api3_contribution_get_support_nonunique_returns($params) {
cf8f0fff 280 $additionalOptions = [];
3123273f 281 $options = _civicrm_api3_get_options_from_params($params, TRUE);
6e7cc0f5 282 foreach (['check_number', 'address_id', 'cancel_date'] as $changedVariable) {
3123273f 283 if (isset($options['return']) && !empty($options['return'][$changedVariable])) {
284 $additionalOptions['return']['contribution_' . $changedVariable] = 1;
285 }
286 }
287 return $additionalOptions;
288}
289
290/**
291 * Support for supported output variables.
292 *
2884d956 293 * @param array $contribution
3123273f 294 */
295function _civicrm_api3_contribution_add_supported_fields(&$contribution) {
296 // These are output fields that are supported in our test contract.
297 // Arguably we should also do the same with 'campaign_id' &
298 // 'source' - which are also fields being rendered with unique names.
299 // That seems more consistent with other api where we output the actual field names.
cf8f0fff 300 $outputAliases = [
3123273f 301 'contribution_check_number' => 'check_number',
302 'contribution_address_id' => 'address_id',
303 'payment_instrument_id' => 'instrument_id',
6e7cc0f5 304 'contribution_cancel_date' => 'cancel_date',
cf8f0fff 305 ];
3123273f 306 foreach ($outputAliases as $returnName => $copyTo) {
307 if (array_key_exists($returnName, $contribution)) {
308 $contribution[$copyTo] = $contribution[$returnName];
309 }
310 }
311
312}
313
9ae25b56 314/**
315 * Get number of contacts matching the supplied criteria.
316 *
317 * @param array $params
318 *
319 * @return int
320 */
321function civicrm_api3_contribution_getcount($params) {
cf8f0fff 322 $count = _civicrm_api3_get_using_query_object('Contribution', $params, [], TRUE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE);
9ae25b56 323 return (int) $count;
6a488035 324}
11e09c59 325
76ca3345 326/**
1747ab99
EM
327 * This function is used to format the soft credit for backward compatibility.
328 *
329 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
76ca3345 330 * but we still return first soft credit as a part of contribution array
dc64d047 331 *
2884d956 332 * @param array $contribution
76ca3345
KJ
333 */
334function _civicrm_api3_format_soft_credit(&$contribution) {
335 if (!empty($contribution['soft_credit'])) {
336 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
337 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
338 }
339}
340
11e09c59 341/**
1747ab99 342 * Adjust Metadata for Get action.
6a488035 343 *
0aa0303c
EM
344 * The metadata is used for setting defaults, documentation & validation.
345 *
cf470720 346 * @param array $params
b081365f 347 * Array of parameters determined by getfields.
6a488035
TO
348 */
349function _civicrm_api3_contribution_get_spec(&$params) {
cf8f0fff 350 $params['contribution_test'] = [
d142432b
EM
351 'api.default' => 0,
352 'type' => CRM_Utils_Type::T_BOOLEAN,
353 'title' => 'Get Test Contributions?',
cf8f0fff
CW
354 'api.aliases' => ['is_test'],
355 ];
739a8336 356
cf8f0fff
CW
357 $params['financial_type_id']['api.aliases'] = ['contribution_type_id'];
358 $params['payment_instrument_id']['api.aliases'] = ['contribution_payment_instrument', 'payment_instrument'];
f748c073 359 $params['contact_id'] = $params['contribution_contact_id'] ?? NULL;
cf8f0fff 360 $params['contact_id']['api.aliases'] = ['contribution_contact_id'];
f614a080 361 $params['is_template']['api.default'] = 0;
6a488035
TO
362 unset($params['contribution_contact_id']);
363}
364
365/**
1747ab99
EM
366 * Legacy handling for contribution parameters.
367 *
368 * Take the input parameter list as specified in the data model and
369 * convert it into the same format that we use in QF and BAO object.
6a488035 370 *
cf470720 371 * @param array $params
c23f45d3 372 * property name/value pairs to insert in new contact.
cf470720
TO
373 * @param array $values
374 * The reformatted properties that we can use internally.
6a488035 375 *
c23f45d3 376 * @return array
6a488035 377 */
c23f45d3 378function _civicrm_api3_contribute_format_params($params, &$values) {
35671d00 379 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
6a488035 380 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
cf8f0fff 381 return [];
6a488035
TO
382}
383
6a488035 384/**
1747ab99
EM
385 * Send a contribution confirmation (receipt or invoice).
386 *
6a488035
TO
387 * The appropriate online template will be used (the existence of related objects
388 * (e.g. memberships ) will affect this selection
69dbd1ba 389 *
cf470720
TO
390 * @param array $params
391 * Input parameters.
69dbd1ba
EM
392 *
393 * @throws Exception
6a488035
TO
394 */
395function civicrm_api3_contribution_sendconfirmation($params) {
0d07fe4e 396 $ids = [];
cf8f0fff 397 $allowedParams = [
ec7e3954
E
398 'receipt_from_email',
399 'receipt_from_name',
400 'receipt_update',
401 'cc_receipt',
402 'bcc_receipt',
403 'receipt_text',
f57ccf3c 404 'pay_later_receipt',
ec7e3954 405 'payment_processor_id',
cf8f0fff 406 ];
71687b3d 407 $input = array_intersect_key($params, array_flip($allowedParams));
0d07fe4e 408 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $params['id']);
9faf45a5 409 return [];
6a488035
TO
410}
411
11e09c59 412/**
1747ab99 413 * Adjust Metadata for sendconfirmation action.
6a488035 414 *
0aa0303c
EM
415 * The metadata is used for setting defaults, documentation & validation.
416 *
cf470720 417 * @param array $params
b081365f 418 * Array of parameters determined by getfields.
6a488035
TO
419 */
420function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
cf8f0fff 421 $params['id'] = [
6a488035 422 'api.required' => 1,
ec7e3954 423 'title' => ts('Contribution ID'),
d142432b 424 'type' => CRM_Utils_Type::T_INT,
cf8f0fff
CW
425 ];
426 $params['receipt_from_email'] = [
ec7e3954 427 'title' => ts('From Email address (string)'),
d142432b 428 'type' => CRM_Utils_Type::T_STRING,
cf8f0fff
CW
429 ];
430 $params['receipt_from_name'] = [
ec7e3954 431 'title' => ts('From Name (string)'),
d142432b 432 'type' => CRM_Utils_Type::T_STRING,
cf8f0fff
CW
433 ];
434 $params['cc_receipt'] = [
ec7e3954 435 'title' => ts('CC Email address (string)'),
d142432b 436 'type' => CRM_Utils_Type::T_STRING,
cf8f0fff
CW
437 ];
438 $params['bcc_receipt'] = [
ec7e3954 439 'title' => ts('BCC Email address (string)'),
d142432b 440 'type' => CRM_Utils_Type::T_STRING,
cf8f0fff
CW
441 ];
442 $params['receipt_text'] = [
ec7e3954 443 'title' => ts('Message (string)'),
d142432b 444 'type' => CRM_Utils_Type::T_STRING,
cf8f0fff 445 ];
f57ccf3c
JP
446 $params['pay_later_receipt'] = [
447 'title' => ts('Pay Later Message (string)'),
448 'type' => CRM_Utils_Type::T_STRING,
449 ];
cf8f0fff 450 $params['receipt_update'] = [
ec7e3954
E
451 'title' => ts('Update the Receipt Date'),
452 'type' => CRM_Utils_Type::T_BOOLEAN,
453 'api.default' => TRUE,
cf8f0fff
CW
454 ];
455 $params['payment_processor_id'] = [
ec7e3954
E
456 'title' => ts('Payment processor Id (avoids mis-guesses)'),
457 'type' => CRM_Utils_Type::T_INT,
cf8f0fff 458 ];
6a488035 459}
0efa8efe 460
461/**
1747ab99
EM
462 * Complete an existing (pending) transaction.
463 *
464 * This will update related entities (participant, membership, pledge etc)
465 * and take any complete actions from the contribution page (e.g. send receipt).
0efa8efe 466 *
467 * @todo - most of this should live in the BAO layer but as we want it to be an addition
468 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
469 *
cf470720
TO
470 * @param array $params
471 * Input parameters.
69dbd1ba 472 *
734d2daa 473 * @return array
474 * API result array
475 * @throws \API_Exception
476 * @throws \CRM_Core_Exception
477 * @throws \Exception
0efa8efe 478 */
1c31aa41 479function civicrm_api3_contribution_completetransaction($params) {
0efa8efe 480 $contribution = new CRM_Contribute_BAO_Contribution();
481 $contribution->id = $params['id'];
4e379895 482 if (!$contribution->find(TRUE)) {
0efa8efe 483 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
484 }
8c1ed7f8 485 if ($contribution->contribution_status_id == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
5ddd6889 486 throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
0efa8efe 487 }
8c1ed7f8 488
97887960 489 $params['trxn_id'] = $params['trxn_id'] ?? $contribution->trxn_id;
39052b78 490
97887960
MW
491 $passThroughParams = [
492 'fee_amount',
493 'payment_processor_id',
494 'trxn_id',
495 ];
496 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
5ddd6889 497
8c1ed7f8
MW
498 $ids = [];
499 if (!$contribution->loadRelatedObjects(['payment_processor_id' => $input['payment_processor_id'] ?? NULL], $ids, TRUE)) {
500 throw new API_Exception('failed to load related objects');
501 }
502
0c9ae247
MW
503 // @todo Copied from _ipn_process_transaction - needs cleanup/refactor
504 $objects = $contribution->_relatedObjects;
505 $objects['contribution'] = &$contribution;
506 $input['component'] = $contribution->_component;
507 $input['is_test'] = $contribution->is_test;
508 $input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
509
510 if (isset($params['is_email_receipt'])) {
511 $input['is_email_receipt'] = $params['is_email_receipt'];
512 }
513 if (!empty($params['trxn_date'])) {
514 $input['trxn_date'] = $params['trxn_date'];
515 }
516 if (!empty($params['receive_date'])) {
517 $input['receive_date'] = $params['receive_date'];
518 }
519 if (empty($contribution->contribution_page_id)) {
520 static $domainFromName;
521 static $domainFromEmail;
522 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
523 [$domainFromName, $domainFromEmail] = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
524 }
525 $input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
526 $input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
527 }
528 $input['card_type_id'] = $params['card_type_id'] ?? NULL;
529 $input['pan_truncation'] = $params['pan_truncation'] ?? NULL;
530 if (!empty($params['payment_instrument_id'])) {
531 $input['payment_instrument_id'] = $params['payment_instrument_id'];
532 }
533 return CRM_Contribute_BAO_Contribution::completeOrder($input,
534 !empty($objects['contributionRecur']) ? $objects['contributionRecur']->id : NULL,
535 $objects['contribution']->id ?? NULL,
536 $params['is_post_payment_create'] ?? NULL);
0efa8efe 537}
538
aa1b1481 539/**
9d32e6f7
EM
540 * Provide function metadata.
541 *
c490a46a 542 * @param array $params
aa1b1481 543 */
3dfbdece 544function _civicrm_api3_contribution_completetransaction_spec(&$params) {
cf8f0fff 545 $params['id'] = [
eac25df2
EM
546 'title' => 'Contribution ID',
547 'type' => CRM_Utils_Type::T_INT,
548 'api.required' => TRUE,
cf8f0fff
CW
549 ];
550 $params['trxn_id'] = [
eac25df2
EM
551 'title' => 'Transaction ID',
552 'type' => CRM_Utils_Type::T_STRING,
cf8f0fff
CW
553 ];
554 $params['is_email_receipt'] = [
eac25df2
EM
555 'title' => 'Send email Receipt?',
556 'type' => CRM_Utils_Type::T_BOOLEAN,
cf8f0fff
CW
557 ];
558 $params['receipt_from_email'] = [
0930231a
EM
559 'title' => 'Email to send receipt from.',
560 'description' => 'If not provided this will default to being based on domain mail or contribution page',
561 'type' => CRM_Utils_Type::T_EMAIL,
cf8f0fff
CW
562 ];
563 $params['receipt_from_name'] = [
0930231a
EM
564 'title' => 'Name to send receipt from',
565 'description' => '. If not provided this will default to domain mail or contribution page',
566 'type' => CRM_Utils_Type::T_STRING,
cf8f0fff
CW
567 ];
568 $params['payment_processor_id'] = [
07b46478 569 'title' => 'Payment processor ID',
080a561b 570 'description' => 'Providing this is strongly recommended, as not possible to calculate it accurately always',
07b46478 571 'type' => CRM_Utils_Type::T_INT,
cf8f0fff
CW
572 ];
573 $params['fee_amount'] = [
080a561b 574 'title' => 'Fee charged on transaction',
575 'description' => 'If a fee has been charged then the amount',
576 'type' => CRM_Utils_Type::T_FLOAT,
cf8f0fff
CW
577 ];
578 $params['trxn_date'] = [
7104593e 579 'title' => 'Transaction Date',
580 'description' => 'Date this transaction occurred',
970aa2fe 581 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
cf8f0fff
CW
582 ];
583 $params['card_type_id'] = [
a55e39e9 584 'title' => 'Card Type ID',
585 'description' => 'Providing Credit Card Type ID',
586 'type' => CRM_Utils_Type::T_INT,
cf8f0fff 587 'pseudoconstant' => [
a55e39e9 588 'optionGroupName' => 'accept_creditcard',
cf8f0fff
CW
589 ],
590 ];
362f37fc 591 // At some point we will deprecate this api in favour of calling payment create which will in turn call this
592 // api if appropriate to transition related entities and send receipts - ie. financial responsibility should
593 // not exist in completetransaction. For now we just need to allow payment.create to force a bypass on the
594 // things it does itself.
595 $params['is_post_payment_create'] = [
596 'title' => 'Is this being called from payment create?',
597 'type' => CRM_Utils_Type::T_BOOLEAN,
598 'description' => 'The \'correct\' flow is to call payment.create for the financial side & for that to call completecontribution for the entity & receipt management. However, we need to still support completetransaction directly for legacy reasons',
599 ];
0efa8efe 600}
5fa7c328
EM
601
602/**
603 * Complete an existing (pending) transaction.
604 *
605 * This will update related entities (participant, membership, pledge etc)
606 * and take any complete actions from the contribution page (e.g. send receipt).
607 *
608 * @todo - most of this should live in the BAO layer but as we want it to be an addition
609 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
610 *
611 * @param array $params
612 * Input parameters.
613 *
e4384ce8 614 * @return array
5fa7c328 615 * Api result array.
e4384ce8 616 * @throws API_Exception
5fa7c328 617 */
1c31aa41 618function civicrm_api3_contribution_repeattransaction($params) {
6a0b0616 619
cf8f0fff 620 civicrm_api3_verify_one_mandatory($params, NULL, ['contribution_recur_id', 'original_contribution_id']);
6a0b0616
RLAR
621
622 // We need a contribution to copy.
1eade77d 623 if (empty($params['original_contribution_id'])) {
6a0b0616 624 // Find one from the given recur. A template contribution is preferred, otherwise use the latest one added.
9c15bfdb
MW
625 $templateContribution = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution($params['contribution_recur_id']);
626 if (empty($templateContribution)) {
627 throw new CiviCRM_API3_Exception('Contribution.repeattransaction failed to get original_contribution_id for recur with ID: ' . $params['contribution_recur_id']);
628 }
5fa7c328 629 }
6a0b0616
RLAR
630 else {
631 // A template/original contribution was specified by the params. Load it.
632 $templateContribution = Contribution::get(FALSE)
633 ->addWhere('id', '=', $params['original_contribution_id'])
634 ->addWhere('is_test', 'IN', [0, 1])
635 ->addWhere('contribution_recur_id', 'IS NOT EMPTY')
636 ->execute()->first();
637 if (empty($templateContribution)) {
638 throw new CiviCRM_API3_Exception("Contribution.repeattransaction failed to load the given original_contribution_id ($params[original_contribution_id]) because it does not exist, or because it does not belong to a recurring contribution");
639 }
7b3cf420
MW
640 }
641
6a0b0616
RLAR
642 // Collect inputs for CRM_Contribute_BAO_Contribution::completeOrder in $input.
643 $paramsToCopy = [
ed3bf903 644 'trxn_id',
ed3bf903
MW
645 'campaign_id',
646 'fee_amount',
647 'financial_type_id',
648 'contribution_status_id',
ed3bf903 649 'payment_processor_id',
6a0b0616
RLAR
650 'is_email_receipt',
651 'trxn_date',
652 'receive_date',
653 'card_type_id',
654 'pan_truncation',
655 'payment_instrument_id',
656 // Q. not contribution_page_id ?
657 ];
658 $input = array_intersect_key($params, array_fill_keys($paramsToCopy, NULL));
659 // Ensure certain keys exist with NULL values if they don't already (not sure if this is ACTUALLY necessary?)
660 $input += array_fill_keys(['card_type_id', 'pan_truncation'], NULL);
661
662 // Set amount, use templateContribution if not in params.
663 $input['total_amount'] = $params['total_amount'] ?? $templateContribution['total_amount'];
664 // Why do we need this extra 'amount' key? It's used in CRM_Contribute_BAO_Contribution::completeOrder to pass on to CRM_Contribute_BAO_ContributionRecur::updateRecurLinkedPledge
665 // but it could possibly be removed if that code was adjusted unless anything else uses 'amount'
666 $input['amount'] = $input['total_amount'];
667
668 $input['payment_processor_id'] = civicrm_api3('contributionRecur', 'getvalue', [
669 'return' => 'payment_processor_id',
670 'id' => $templateContribution['contribution_recur_id'],
671 ]);
ed3bf903 672
6a0b0616 673 $input['is_test'] = $templateContribution['is_test'];
8c1ed7f8 674
6a0b0616
RLAR
675 if (empty($templateContribution['contribution_page_id'])) {
676 // Q. why do we need statics here?
0c9ae247
MW
677 static $domainFromName;
678 static $domainFromEmail;
679 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
680 [$domainFromName, $domainFromEmail] = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
681 }
6a0b0616
RLAR
682 $input['receipt_from_name'] = ($params['receipt_from_name'] ?? NULL) ?: $domainFromName;
683 $input['receipt_from_email'] = ($params['receipt_from_email'] ?? NULL) ?: $domainFromEmail;
0c9ae247 684 }
6a0b0616 685
0c9ae247 686 return CRM_Contribute_BAO_Contribution::completeOrder($input,
6a0b0616
RLAR
687 $templateContribution['contribution_recur_id'],
688 NULL,
0c9ae247 689 $params['is_post_payment_create'] ?? NULL);
5fa7c328
EM
690}
691
692/**
693 * Calls IPN complete transaction for completing or repeating a transaction.
694 *
695 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
696 * when separating them in the api layer.
697 *
0c9ae247
MW
698 * @deprecated
699 *
5fa7c328
EM
700 * @param array $params
701 * @param CRM_Contribute_BAO_Contribution $contribution
702 * @param array $input
703 *
704 * @param array $ids
705 *
706 * @return mixed
27d10f99 707 * @throws \CRM_Core_Exception
708 * @throws \CiviCRM_API3_Exception
5fa7c328 709 */
f19d0e35 710function _ipn_process_transaction($params, $contribution, $input, $ids) {
0c9ae247 711 CRM_Core_Error::deprecatedFunctionWarning('API3 contribution.completetransaction or contribution.repeattransaction');
5fa7c328
EM
712 $objects = $contribution->_relatedObjects;
713 $objects['contribution'] = &$contribution;
714 $input['component'] = $contribution->_component;
715 $input['is_test'] = $contribution->is_test;
96f0fe0d
EM
716 $input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
717
5fa7c328
EM
718 if (isset($params['is_email_receipt'])) {
719 $input['is_email_receipt'] = $params['is_email_receipt'];
720 }
7104593e 721 if (!empty($params['trxn_date'])) {
722 $input['trxn_date'] = $params['trxn_date'];
723 }
dccd9f4f
ERL
724 if (!empty($params['receive_date'])) {
725 $input['receive_date'] = $params['receive_date'];
726 }
0930231a
EM
727 if (empty($contribution->contribution_page_id)) {
728 static $domainFromName;
729 static $domainFromEmail;
730 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
9cef6066 731 [$domainFromName, $domainFromEmail] = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
0930231a
EM
732 }
733 $input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
734 $input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
735 }
f748c073 736 $input['card_type_id'] = $params['card_type_id'] ?? NULL;
737 $input['pan_truncation'] = $params['pan_truncation'] ?? NULL;
d0b559aa
SP
738 if (!empty($params['payment_instrument_id'])) {
739 $input['payment_instrument_id'] = $params['payment_instrument_id'];
740 }
5f31e5f4
YN
741 return CRM_Contribute_BAO_Contribution::completeOrder($input,
742 !empty($objects['contributionRecur']) ? $objects['contributionRecur']->id : NULL,
743 $objects['contribution']->id ?? NULL,
2e426931 744 $params['is_post_payment_create'] ?? NULL);
5fa7c328
EM
745}
746
747/**
748 * Provide function metadata.
749 *
750 * @param array $params
751 */
752function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
cf8f0fff 753 $params['original_contribution_id'] = [
5fa7c328 754 'title' => 'Original Contribution ID',
1eade77d 755 'description' => 'Contribution ID to copy (will be calculated from recurring contribution if not provided)',
756 'type' => CRM_Utils_Type::T_INT,
cf8f0fff
CW
757 ];
758 $params['contribution_recur_id'] = [
1eade77d 759 'title' => 'Recurring contribution ID',
5fa7c328 760 'type' => CRM_Utils_Type::T_INT,
cf8f0fff
CW
761 ];
762 $params['trxn_id'] = [
5fa7c328
EM
763 'title' => 'Transaction ID',
764 'type' => CRM_Utils_Type::T_STRING,
cf8f0fff
CW
765 ];
766 $params['is_email_receipt'] = [
5fa7c328
EM
767 'title' => 'Send email Receipt?',
768 'type' => CRM_Utils_Type::T_BOOLEAN,
cf8f0fff
CW
769 ];
770 $params['contribution_status_id'] = [
5fa7c328 771 'title' => 'Contribution Status ID',
d97c96dc 772 'name' => 'contribution_status_id',
5fa7c328 773 'type' => CRM_Utils_Type::T_INT,
cf8f0fff 774 'pseudoconstant' => [
5fa7c328 775 'optionGroupName' => 'contribution_status',
cf8f0fff 776 ],
5fa7c328 777 'api.required' => TRUE,
d6de72c6 778 'api.default' => 'Pending',
cf8f0fff
CW
779 ];
780 $params['receive_date'] = [
5fa7c328 781 'title' => 'Contribution Receive Date',
d97c96dc 782 'name' => 'receive_date',
970aa2fe 783 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
5fa7c328 784 'api.default' => 'now',
cf8f0fff
CW
785 ];
786 $params['trxn_id'] = [
d97c96dc
EM
787 'title' => 'Transaction ID',
788 'name' => 'trxn_id',
789 'type' => CRM_Utils_Type::T_STRING,
cf8f0fff
CW
790 ];
791 $params['campaign_id'] = [
c02c17df 792 'title' => 'Campaign ID',
793 'name' => 'campaign_id',
794 'type' => CRM_Utils_Type::T_INT,
cf8f0fff 795 'pseudoconstant' => [
c02c17df 796 'table' => 'civicrm_campaign',
797 'keyColumn' => 'id',
798 'labelColumn' => 'title',
cf8f0fff
CW
799 ],
800 ];
801 $params['financial_type_id'] = [
3c49d90c 802 'title' => 'Financial ID (ignored if more than one line item)',
803 'name' => 'financial_type_id',
804 'type' => CRM_Utils_Type::T_INT,
cf8f0fff 805 'pseudoconstant' => [
3c49d90c 806 'table' => 'civicrm_financial_type',
807 'keyColumn' => 'id',
808 'labelColumn' => 'name',
cf8f0fff
CW
809 ],
810 ];
811 $params['payment_processor_id'] = [
d97c96dc
EM
812 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
813 'title' => 'Payment processor ID',
814 'name' => 'payment_processor_id',
815 'type' => CRM_Utils_Type::T_INT,
cf8f0fff 816 ];
5fa7c328 817}
779cb42a 818
819/**
820 * Declare deprecated functions.
821 *
822 * @return array
823 * Array of deprecated actions
824 */
825function _civicrm_api3_contribution_deprecation() {
826 return ['transact' => 'Contribute.transact is ureliable & unsupported - see https://docs.civicrm.org/dev/en/latest/financial/OrderAPI/ for how to move on'];
827}