Merge pull request #23656 from colemanw/afformOptions
[civicrm-core.git] / api / v3 / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * This api exposes CiviCRM Contribution records.
14 *
15 * @package CiviCRM_APIv3
16 */
17
18 use Civi\Api4\Contribution;
19
20 /**
21 * Add or update a Contribution.
22 *
23 * @param array $params
24 * Input parameters.
25 *
26 * @throws API_Exception
27 * @return array
28 * Api result array
29 */
30 function civicrm_api3_contribution_create($params) {
31 $values = [];
32 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
33 $params = array_merge($params, $values);
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.)
36 if (empty($params['skipCleanMoney'])) {
37 foreach (['total_amount', 'net_amount', 'fee_amount', 'non_deductible_amount'] as $field) {
38 if (isset($params[$field])) {
39 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
40 }
41 }
42 }
43 $params['skipCleanMoney'] = TRUE;
44
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']) {
53 throw new API_Exception('You do not have permission to create this contribution');
54 }
55 }
56 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
57 $error = [];
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 }
65 }
66 if (!empty($params['id']) && !empty($params['financial_type_id'])) {
67 $error = [];
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 }
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 }
85 _civicrm_api3_contribution_create_legacy_support_45($params);
86
87 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
88 }
89
90 /**
91 * Adjust Metadata for Create action.
92 *
93 * The metadata is used for setting defaults, documentation & validation.
94 *
95 * @param array $params
96 * Array of parameters determined by getfields.
97 */
98 function _civicrm_api3_contribution_create_spec(&$params) {
99 $params['contact_id']['api.required'] = 1;
100 $params['total_amount']['api.required'] = 1;
101 $params['payment_instrument_id']['api.aliases'] = ['payment_instrument'];
102 $params['receive_date']['api.default'] = 'now';
103 $params['receive_date']['api.required'] = TRUE;
104 $params['payment_processor'] = [
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
110 'api.aliases' => ['payment_processor_id'],
111 'type' => CRM_Utils_Type::T_INT,
112 ];
113 $params['financial_type_id']['api.aliases'] = ['contribution_type_id', 'contribution_type'];
114 $params['financial_type_id']['api.required'] = 1;
115 $params['note'] = [
116 'name' => 'note',
117 'uniqueName' => 'contribution_note',
118 'title' => 'note',
119 'type' => 2,
120 'description' => 'Associated Note in the notes table',
121 ];
122 $params['soft_credit_to'] = [
123 'name' => 'soft_credit_to',
124 'title' => 'Soft Credit contact ID (legacy)',
125 'type' => CRM_Utils_Type::T_INT,
126 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
127 'FKClassName' => 'CRM_Contact_DAO_Contact',
128 ];
129 $params['honor_contact_id'] = [
130 'name' => 'honor_contact_id',
131 'title' => 'Honoree contact ID (legacy)',
132 'type' => CRM_Utils_Type::T_INT,
133 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
134 'FKClassName' => 'CRM_Contact_DAO_Contact',
135 ];
136 $params['honor_type_id'] = [
137 'name' => 'honor_type_id',
138 'title' => 'Honoree Type (legacy)',
139 'type' => CRM_Utils_Type::T_INT,
140 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
141 'pseudoconstant' => TRUE,
142 ];
143 // note this is a recommended option but not adding as a default to avoid
144 // creating unnecessary changes for the dev
145 $params['skipRecentView'] = [
146 'name' => 'skipRecentView',
147 'title' => 'Skip adding to recent view',
148 'type' => CRM_Utils_Type::T_BOOLEAN,
149 'description' => 'Do not add to recent view (setting this improves performance)',
150 ];
151 $params['skipLineItem'] = [
152 'name' => 'skipLineItem',
153 'title' => 'Skip adding line items',
154 'type' => CRM_Utils_Type::T_BOOLEAN,
155 'api.default' => 0,
156 'description' => 'Do not add line items by default (if you wish to add your own)',
157 ];
158 $params['batch_id'] = [
159 'title' => 'Batch',
160 'type' => CRM_Utils_Type::T_INT,
161 'description' => 'Batch which relevant transactions should be added to',
162 ];
163 $params['refund_trxn_id'] = [
164 'title' => 'Refund Transaction ID',
165 'type' => CRM_Utils_Type::T_STRING,
166 'description' => 'Transaction ID specific to the refund taking place',
167 ];
168 $params['card_type_id'] = [
169 'title' => 'Card Type ID',
170 'description' => 'Providing Credit Card Type ID',
171 'type' => CRM_Utils_Type::T_INT,
172 'pseudoconstant' => [
173 'optionGroupName' => 'accept_creditcard',
174 ],
175 ];
176 }
177
178 /**
179 * Support for schema changes made in 4.5.
180 *
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.
184 *
185 * @param array $params
186 */
187 function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
188 //legacy soft credit handling - recommended approach is chaining
189 if (!empty($params['soft_credit_to'])) {
190 $params['soft_credit'][] = [
191 'contact_id' => $params['soft_credit_to'],
192 'amount' => $params['total_amount'],
193 'soft_credit_type_id' => CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"),
194 ];
195 }
196 if (!empty($params['honor_contact_id'])) {
197 $params['soft_credit'][] = [
198 'contact_id' => $params['honor_contact_id'],
199 'amount' => $params['total_amount'],
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')),
201 ];
202 }
203 }
204
205 /**
206 * Delete a Contribution.
207 *
208 * @param array $params
209 * Input parameters.
210 *
211 * @return array
212 * @throws \API_Exception
213 */
214 function civicrm_api3_contribution_delete($params) {
215
216 $contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
217 if (!empty($params['check_permissions']) && !\Civi\Api4\Utils\CoreUtil::checkAccessDelegated('Contribution', 'delete', ['id' => $contributionID], CRM_Core_Session::getLoggedInContactID() ?: 0)) {
218 throw new API_Exception('You do not have permission to delete this contribution');
219 }
220 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
221 return civicrm_api3_create_success([$contributionID => 1]);
222 }
223 throw new API_Exception('Could not delete contribution');
224 }
225
226 /**
227 * Modify metadata for delete action.
228 *
229 * Legacy support for contribution_id.
230 *
231 * @param array $params
232 */
233 function _civicrm_api3_contribution_delete_spec(&$params) {
234 $params['id']['api.aliases'] = ['contribution_id'];
235 }
236
237 /**
238 * Retrieve a set of contributions.
239 *
240 * @param array $params
241 * Input parameters.
242 *
243 * @return array
244 * Array of contributions, if error an array with an error id and error message
245 */
246 function civicrm_api3_contribution_get($params) {
247
248 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
249 $additionalOptions = _civicrm_api3_contribution_get_support_nonunique_returns($params);
250 $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties($mode);
251
252 // Get the contributions based on parameters passed in
253 $contributions = _civicrm_api3_get_using_query_object('Contribution', $params, $additionalOptions, NULL, $mode, $returnProperties);
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 }
262 }
263 return civicrm_api3_create_success($contributions, $params, 'Contribution', 'get');
264 }
265
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 */
279 function _civicrm_api3_contribution_get_support_nonunique_returns($params) {
280 $additionalOptions = [];
281 $options = _civicrm_api3_get_options_from_params($params, TRUE);
282 foreach (['check_number', 'address_id', 'cancel_date'] as $changedVariable) {
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 *
293 * @param array $contribution
294 */
295 function _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.
300 $outputAliases = [
301 'contribution_check_number' => 'check_number',
302 'contribution_address_id' => 'address_id',
303 'payment_instrument_id' => 'instrument_id',
304 'contribution_cancel_date' => 'cancel_date',
305 ];
306 foreach ($outputAliases as $returnName => $copyTo) {
307 if (array_key_exists($returnName, $contribution)) {
308 $contribution[$copyTo] = $contribution[$returnName];
309 }
310 }
311
312 }
313
314 /**
315 * Get number of contacts matching the supplied criteria.
316 *
317 * @param array $params
318 *
319 * @return int
320 */
321 function civicrm_api3_contribution_getcount($params) {
322 $count = _civicrm_api3_get_using_query_object('Contribution', $params, [], TRUE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE);
323 return (int) $count;
324 }
325
326 /**
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
330 * but we still return first soft credit as a part of contribution array
331 *
332 * @param array $contribution
333 */
334 function _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
341 /**
342 * Adjust Metadata for Get action.
343 *
344 * The metadata is used for setting defaults, documentation & validation.
345 *
346 * @param array $params
347 * Array of parameters determined by getfields.
348 */
349 function _civicrm_api3_contribution_get_spec(&$params) {
350 $params['contribution_test'] = [
351 'api.default' => 0,
352 'type' => CRM_Utils_Type::T_BOOLEAN,
353 'title' => 'Get Test Contributions?',
354 'api.aliases' => ['is_test'],
355 ];
356
357 $params['financial_type_id']['api.aliases'] = ['contribution_type_id'];
358 $params['payment_instrument_id']['api.aliases'] = ['contribution_payment_instrument', 'payment_instrument'];
359 $params['contact_id'] = $params['contribution_contact_id'] ?? NULL;
360 $params['contact_id']['api.aliases'] = ['contribution_contact_id'];
361 $params['is_template']['api.default'] = 0;
362 unset($params['contribution_contact_id']);
363 }
364
365 /**
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.
370 *
371 * @param array $params
372 * property name/value pairs to insert in new contact.
373 * @param array $values
374 * The reformatted properties that we can use internally.
375 *
376 * @return array
377 */
378 function _civicrm_api3_contribute_format_params($params, &$values) {
379 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
380 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
381 return [];
382 }
383
384 /**
385 * Send a contribution confirmation (receipt or invoice).
386 *
387 * The appropriate online template will be used (the existence of related objects
388 * (e.g. memberships ) will affect this selection
389 *
390 * @param array $params
391 * Input parameters.
392 *
393 * @throws Exception
394 */
395 function civicrm_api3_contribution_sendconfirmation($params) {
396 $ids = [];
397 $allowedParams = [
398 'receipt_from_email',
399 'receipt_from_name',
400 'receipt_update',
401 'cc_receipt',
402 'bcc_receipt',
403 'receipt_text',
404 'pay_later_receipt',
405 'payment_processor_id',
406 ];
407 $input = array_intersect_key($params, array_flip($allowedParams));
408 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $params['id']);
409 return [];
410 }
411
412 /**
413 * Adjust Metadata for sendconfirmation action.
414 *
415 * The metadata is used for setting defaults, documentation & validation.
416 *
417 * @param array $params
418 * Array of parameters determined by getfields.
419 */
420 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
421 $params['id'] = [
422 'api.required' => 1,
423 'title' => ts('Contribution ID'),
424 'type' => CRM_Utils_Type::T_INT,
425 ];
426 $params['receipt_from_email'] = [
427 'title' => ts('From Email address (string)'),
428 'type' => CRM_Utils_Type::T_STRING,
429 ];
430 $params['receipt_from_name'] = [
431 'title' => ts('From Name (string)'),
432 'type' => CRM_Utils_Type::T_STRING,
433 ];
434 $params['cc_receipt'] = [
435 'title' => ts('CC Email address (string)'),
436 'type' => CRM_Utils_Type::T_STRING,
437 ];
438 $params['bcc_receipt'] = [
439 'title' => ts('BCC Email address (string)'),
440 'type' => CRM_Utils_Type::T_STRING,
441 ];
442 $params['receipt_text'] = [
443 'title' => ts('Message (string)'),
444 'type' => CRM_Utils_Type::T_STRING,
445 ];
446 $params['pay_later_receipt'] = [
447 'title' => ts('Pay Later Message (string)'),
448 'type' => CRM_Utils_Type::T_STRING,
449 ];
450 $params['receipt_update'] = [
451 'title' => ts('Update the Receipt Date'),
452 'type' => CRM_Utils_Type::T_BOOLEAN,
453 'api.default' => TRUE,
454 ];
455 $params['payment_processor_id'] = [
456 'title' => ts('Payment processor Id (avoids mis-guesses)'),
457 'type' => CRM_Utils_Type::T_INT,
458 ];
459 }
460
461 /**
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).
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 *
470 * @param array $params
471 * Input parameters.
472 *
473 * @return array
474 * API result array
475 * @throws \API_Exception
476 * @throws \CRM_Core_Exception
477 * @throws \Exception
478 */
479 function civicrm_api3_contribution_completetransaction($params) {
480 $contribution = new CRM_Contribute_BAO_Contribution();
481 $contribution->id = $params['id'];
482 if (!$contribution->find(TRUE)) {
483 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
484 }
485 if ($contribution->contribution_status_id == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
486 throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
487 }
488
489 $params['trxn_id'] = $params['trxn_id'] ?? $contribution->trxn_id;
490
491 $passThroughParams = [
492 'fee_amount',
493 'payment_processor_id',
494 'trxn_id',
495 ];
496 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
497
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
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);
537 }
538
539 /**
540 * Provide function metadata.
541 *
542 * @param array $params
543 */
544 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
545 $params['id'] = [
546 'title' => 'Contribution ID',
547 'type' => CRM_Utils_Type::T_INT,
548 'api.required' => TRUE,
549 ];
550 $params['trxn_id'] = [
551 'title' => 'Transaction ID',
552 'type' => CRM_Utils_Type::T_STRING,
553 ];
554 $params['is_email_receipt'] = [
555 'title' => 'Send email Receipt?',
556 'type' => CRM_Utils_Type::T_BOOLEAN,
557 ];
558 $params['receipt_from_email'] = [
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,
562 ];
563 $params['receipt_from_name'] = [
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,
567 ];
568 $params['payment_processor_id'] = [
569 'title' => 'Payment processor ID',
570 'description' => 'Providing this is strongly recommended, as not possible to calculate it accurately always',
571 'type' => CRM_Utils_Type::T_INT,
572 ];
573 $params['fee_amount'] = [
574 'title' => 'Fee charged on transaction',
575 'description' => 'If a fee has been charged then the amount',
576 'type' => CRM_Utils_Type::T_FLOAT,
577 ];
578 $params['trxn_date'] = [
579 'title' => 'Transaction Date',
580 'description' => 'Date this transaction occurred',
581 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
582 ];
583 $params['card_type_id'] = [
584 'title' => 'Card Type ID',
585 'description' => 'Providing Credit Card Type ID',
586 'type' => CRM_Utils_Type::T_INT,
587 'pseudoconstant' => [
588 'optionGroupName' => 'accept_creditcard',
589 ],
590 ];
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 ];
600 }
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 *
614 * @return array
615 * Api result array.
616 * @throws API_Exception
617 */
618 function civicrm_api3_contribution_repeattransaction($params) {
619 civicrm_api3_verify_one_mandatory($params, NULL, ['contribution_recur_id', 'original_contribution_id']);
620 if (empty($params['original_contribution_id'])) {
621 $templateContribution = CRM_Contribute_BAO_ContributionRecur::getTemplateContribution($params['contribution_recur_id']);
622 if (empty($templateContribution)) {
623 throw new CiviCRM_API3_Exception('Contribution.repeattransaction failed to get original_contribution_id for recur with ID: ' . $params['contribution_recur_id']);
624 }
625 $params['original_contribution_id'] = $templateContribution['id'];
626 }
627 $contribution = new CRM_Contribute_BAO_Contribution();
628 $contribution->id = $params['original_contribution_id'];
629 if (!$contribution->find(TRUE)) {
630 throw new API_Exception(
631 'A valid original contribution ID is required', 'invalid_data');
632 }
633 // We don't support repeattransaction without a related recurring contribution.
634 if (empty($contribution->contribution_recur_id)) {
635 throw new API_Exception(
636 'Repeattransaction API can only be used in the context of contributions that have a contribution_recur_id.',
637 'invalid_data'
638 );
639 }
640
641 $params['payment_processor_id'] = civicrm_api3('contributionRecur', 'getvalue', [
642 'return' => 'payment_processor_id',
643 'id' => $contribution->contribution_recur_id,
644 ]);
645
646 $passThroughParams = [
647 'trxn_id',
648 'total_amount',
649 'campaign_id',
650 'fee_amount',
651 'financial_type_id',
652 'contribution_status_id',
653 'payment_processor_id',
654 ];
655 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
656
657 $ids = [];
658 if (!$contribution->loadRelatedObjects(['payment_processor_id' => $input['payment_processor_id']], $ids, TRUE)) {
659 throw new API_Exception('failed to load related objects');
660 }
661 unset($contribution->id, $contribution->receive_date, $contribution->invoice_id);
662 $contribution->receive_date = $params['receive_date'];
663
664 // @todo Copied from _ipn_process_transaction - needs cleanup/refactor
665 $objects = $contribution->_relatedObjects;
666 $objects['contribution'] = &$contribution;
667 $input['component'] = $contribution->_component;
668 $input['is_test'] = $contribution->is_test;
669 $input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
670
671 if (isset($params['is_email_receipt'])) {
672 $input['is_email_receipt'] = $params['is_email_receipt'];
673 }
674 if (!empty($params['trxn_date'])) {
675 $input['trxn_date'] = $params['trxn_date'];
676 }
677 if (!empty($params['receive_date'])) {
678 $input['receive_date'] = $params['receive_date'];
679 }
680 if (empty($contribution->contribution_page_id)) {
681 static $domainFromName;
682 static $domainFromEmail;
683 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
684 [$domainFromName, $domainFromEmail] = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
685 }
686 $input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
687 $input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
688 }
689 $input['card_type_id'] = $params['card_type_id'] ?? NULL;
690 $input['pan_truncation'] = $params['pan_truncation'] ?? NULL;
691 if (!empty($params['payment_instrument_id'])) {
692 $input['payment_instrument_id'] = $params['payment_instrument_id'];
693 }
694 return CRM_Contribute_BAO_Contribution::completeOrder($input,
695 !empty($objects['contributionRecur']) ? $objects['contributionRecur']->id : NULL,
696 $objects['contribution']->id ?? NULL,
697 $params['is_post_payment_create'] ?? NULL);
698 }
699
700 /**
701 * Calls IPN complete transaction for completing or repeating a transaction.
702 *
703 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
704 * when separating them in the api layer.
705 *
706 * @deprecated
707 *
708 * @param array $params
709 * @param CRM_Contribute_BAO_Contribution $contribution
710 * @param array $input
711 *
712 * @param array $ids
713 *
714 * @return mixed
715 * @throws \CRM_Core_Exception
716 * @throws \CiviCRM_API3_Exception
717 */
718 function _ipn_process_transaction($params, $contribution, $input, $ids) {
719 CRM_Core_Error::deprecatedFunctionWarning('API3 contribution.completetransaction or contribution.repeattransaction');
720 $objects = $contribution->_relatedObjects;
721 $objects['contribution'] = &$contribution;
722 $input['component'] = $contribution->_component;
723 $input['is_test'] = $contribution->is_test;
724 $input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
725
726 if (isset($params['is_email_receipt'])) {
727 $input['is_email_receipt'] = $params['is_email_receipt'];
728 }
729 if (!empty($params['trxn_date'])) {
730 $input['trxn_date'] = $params['trxn_date'];
731 }
732 if (!empty($params['receive_date'])) {
733 $input['receive_date'] = $params['receive_date'];
734 }
735 if (empty($contribution->contribution_page_id)) {
736 static $domainFromName;
737 static $domainFromEmail;
738 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
739 [$domainFromName, $domainFromEmail] = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
740 }
741 $input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
742 $input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
743 }
744 $input['card_type_id'] = $params['card_type_id'] ?? NULL;
745 $input['pan_truncation'] = $params['pan_truncation'] ?? NULL;
746 if (!empty($params['payment_instrument_id'])) {
747 $input['payment_instrument_id'] = $params['payment_instrument_id'];
748 }
749 return CRM_Contribute_BAO_Contribution::completeOrder($input,
750 !empty($objects['contributionRecur']) ? $objects['contributionRecur']->id : NULL,
751 $objects['contribution']->id ?? NULL,
752 $params['is_post_payment_create'] ?? NULL);
753 }
754
755 /**
756 * Provide function metadata.
757 *
758 * @param array $params
759 */
760 function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
761 $params['original_contribution_id'] = [
762 'title' => 'Original Contribution ID',
763 'description' => 'Contribution ID to copy (will be calculated from recurring contribution if not provided)',
764 'type' => CRM_Utils_Type::T_INT,
765 ];
766 $params['contribution_recur_id'] = [
767 'title' => 'Recurring contribution ID',
768 'type' => CRM_Utils_Type::T_INT,
769 ];
770 $params['trxn_id'] = [
771 'title' => 'Transaction ID',
772 'type' => CRM_Utils_Type::T_STRING,
773 ];
774 $params['is_email_receipt'] = [
775 'title' => 'Send email Receipt?',
776 'type' => CRM_Utils_Type::T_BOOLEAN,
777 ];
778 $params['contribution_status_id'] = [
779 'title' => 'Contribution Status ID',
780 'name' => 'contribution_status_id',
781 'type' => CRM_Utils_Type::T_INT,
782 'pseudoconstant' => [
783 'optionGroupName' => 'contribution_status',
784 ],
785 'api.required' => TRUE,
786 'api.default' => 'Pending',
787 ];
788 $params['receive_date'] = [
789 'title' => 'Contribution Receive Date',
790 'name' => 'receive_date',
791 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
792 'api.default' => 'now',
793 ];
794 $params['trxn_id'] = [
795 'title' => 'Transaction ID',
796 'name' => 'trxn_id',
797 'type' => CRM_Utils_Type::T_STRING,
798 ];
799 $params['campaign_id'] = [
800 'title' => 'Campaign ID',
801 'name' => 'campaign_id',
802 'type' => CRM_Utils_Type::T_INT,
803 'pseudoconstant' => [
804 'table' => 'civicrm_campaign',
805 'keyColumn' => 'id',
806 'labelColumn' => 'title',
807 ],
808 ];
809 $params['financial_type_id'] = [
810 'title' => 'Financial ID (ignored if more than one line item)',
811 'name' => 'financial_type_id',
812 'type' => CRM_Utils_Type::T_INT,
813 'pseudoconstant' => [
814 'table' => 'civicrm_financial_type',
815 'keyColumn' => 'id',
816 'labelColumn' => 'name',
817 ],
818 ];
819 $params['payment_processor_id'] = [
820 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
821 'title' => 'Payment processor ID',
822 'name' => 'payment_processor_id',
823 'type' => CRM_Utils_Type::T_INT,
824 ];
825 }
826
827 /**
828 * Declare deprecated functions.
829 *
830 * @return array
831 * Array of deprecated actions
832 */
833 function _civicrm_api3_contribution_deprecation() {
834 return ['transact' => 'Contribute.transact is ureliable & unsupported - see https://docs.civicrm.org/dev/en/latest/financial/OrderAPI/ for how to move on'];
835 }