[REF] final cleanup - call bulkCreate from migrate_utils
[civicrm-core.git] / api / v3 / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * This api exposes CiviCRM Contribution records.
30 *
31 * @package CiviCRM_APIv3
32 */
33
34 /**
35 * Add or update a Contribution.
36 *
37 * @param array $params
38 * Input parameters.
39 *
40 * @throws API_Exception
41 * @return array
42 * Api result array
43 */
44 function civicrm_api3_contribution_create($params) {
45 $values = [];
46 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
47 $params = array_merge($params, $values);
48 // The BAO should not clean money - it should be done in the form layer & api wrapper
49 // (although arguably the api should expect pre-cleaned it seems to do some cleaning.)
50 if (empty($params['skipCleanMoney'])) {
51 foreach (['total_amount', 'net_amount', 'fee_amount'] as $field) {
52 if (isset($params[$field])) {
53 $params[$field] = CRM_Utils_Rule::cleanMoney($params[$field]);
54 }
55 }
56 }
57 $params['skipCleanMoney'] = TRUE;
58
59 if (!empty($params['check_permissions']) && CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
60 if (empty($params['id'])) {
61 $op = CRM_Core_Action::ADD;
62 }
63 else {
64 if (empty($params['financial_type_id'])) {
65 $params['financial_type_id'] = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $params['id'], 'financial_type_id');
66 }
67 $op = CRM_Core_Action::UPDATE;
68 }
69 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($types, $op);
70 if (!in_array($params['financial_type_id'], array_keys($types))) {
71 throw new API_Exception('You do not have permission to create this contribution');
72 }
73 }
74 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
75 $error = [];
76 //throw error for invalid status change such as setting completed back to pending
77 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
78 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
79 CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
80 if (array_key_exists('contribution_status_id', $error)) {
81 throw new API_Exception($error['contribution_status_id']);
82 }
83 }
84 if (!empty($params['id']) && !empty($params['financial_type_id'])) {
85 $error = [];
86 CRM_Contribute_BAO_Contribution::checkFinancialTypeChange($params['financial_type_id'], $params['id'], $error);
87 if (array_key_exists('financial_type_id', $error)) {
88 throw new API_Exception($error['financial_type_id']);
89 }
90 }
91 _civicrm_api3_contribution_create_legacy_support_45($params);
92
93 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
94 }
95
96 /**
97 * Adjust Metadata for Create action.
98 *
99 * The metadata is used for setting defaults, documentation & validation.
100 *
101 * @param array $params
102 * Array of parameters determined by getfields.
103 */
104 function _civicrm_api3_contribution_create_spec(&$params) {
105 $params['contact_id']['api.required'] = 1;
106 $params['total_amount']['api.required'] = 1;
107 $params['payment_instrument_id']['api.aliases'] = ['payment_instrument'];
108 $params['receive_date']['api.default'] = 'now';
109 $params['receive_date']['api.required'] = TRUE;
110 $params['payment_processor'] = [
111 'name' => 'payment_processor',
112 'title' => 'Payment Processor ID',
113 'description' => 'ID of payment processor used for this contribution',
114 // field is called payment processor - not payment processor id but can only be one id so
115 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
116 'api.aliases' => ['payment_processor_id'],
117 'type' => CRM_Utils_Type::T_INT,
118 ];
119 $params['financial_type_id']['api.aliases'] = ['contribution_type_id', 'contribution_type'];
120 $params['financial_type_id']['api.required'] = 1;
121 $params['note'] = [
122 'name' => 'note',
123 'uniqueName' => 'contribution_note',
124 'title' => 'note',
125 'type' => 2,
126 'description' => 'Associated Note in the notes table',
127 ];
128 $params['soft_credit_to'] = [
129 'name' => 'soft_credit_to',
130 'title' => 'Soft Credit contact ID (legacy)',
131 'type' => CRM_Utils_Type::T_INT,
132 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
133 'FKClassName' => 'CRM_Contact_DAO_Contact',
134 ];
135 $params['honor_contact_id'] = [
136 'name' => 'honor_contact_id',
137 'title' => 'Honoree contact ID (legacy)',
138 'type' => CRM_Utils_Type::T_INT,
139 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
140 'FKClassName' => 'CRM_Contact_DAO_Contact',
141 ];
142 $params['honor_type_id'] = [
143 'name' => 'honor_type_id',
144 'title' => 'Honoree Type (legacy)',
145 'type' => CRM_Utils_Type::T_INT,
146 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
147 'pseudoconstant' => TRUE,
148 ];
149 // note this is a recommended option but not adding as a default to avoid
150 // creating unnecessary changes for the dev
151 $params['skipRecentView'] = [
152 'name' => 'skipRecentView',
153 'title' => 'Skip adding to recent view',
154 'type' => CRM_Utils_Type::T_BOOLEAN,
155 'description' => 'Do not add to recent view (setting this improves performance)',
156 ];
157 $params['skipLineItem'] = [
158 'name' => 'skipLineItem',
159 'title' => 'Skip adding line items',
160 'type' => CRM_Utils_Type::T_BOOLEAN,
161 'api.default' => 0,
162 'description' => 'Do not add line items by default (if you wish to add your own)',
163 ];
164 $params['batch_id'] = [
165 'title' => 'Batch',
166 'type' => CRM_Utils_Type::T_INT,
167 'description' => 'Batch which relevant transactions should be added to',
168 ];
169 $params['refund_trxn_id'] = [
170 'title' => 'Refund Transaction ID',
171 'type' => CRM_Utils_Type::T_STRING,
172 'description' => 'Transaction ID specific to the refund taking place',
173 ];
174 $params['card_type_id'] = [
175 'title' => 'Card Type ID',
176 'description' => 'Providing Credit Card Type ID',
177 'type' => CRM_Utils_Type::T_INT,
178 'pseudoconstant' => [
179 'optionGroupName' => 'accept_creditcard',
180 ],
181 ];
182 }
183
184 /**
185 * Support for schema changes made in 4.5.
186 *
187 * The main purpose of the API is to provide integrators a level of stability not provided by
188 * the core code or schema - this means we have to provide support for api calls (where possible)
189 * across schema changes.
190 *
191 * @param array $params
192 */
193 function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
194 //legacy soft credit handling - recommended approach is chaining
195 if (!empty($params['soft_credit_to'])) {
196 $params['soft_credit'][] = [
197 'contact_id' => $params['soft_credit_to'],
198 'amount' => $params['total_amount'],
199 'soft_credit_type_id' => CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"),
200 ];
201 }
202 if (!empty($params['honor_contact_id'])) {
203 $params['soft_credit'][] = [
204 'contact_id' => $params['honor_contact_id'],
205 'amount' => $params['total_amount'],
206 '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')),
207 ];
208 }
209 }
210
211 /**
212 * Delete a Contribution.
213 *
214 * @param array $params
215 * Input parameters.
216 *
217 * @return array
218 * @throws \API_Exception
219 */
220 function civicrm_api3_contribution_delete($params) {
221
222 $contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
223 // First check contribution financial type
224 $financialType = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_Contribution', $contributionID, 'financial_type_id');
225 // Now check permissioned lineitems & permissioned contribution
226 if (!empty($params['check_permissions']) && CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus() &&
227 (
228 !CRM_Core_Permission::check('delete contributions of type ' . CRM_Contribute_PseudoConstant::financialType($financialType))
229 || !CRM_Financial_BAO_FinancialType::checkPermissionedLineItems($contributionID, 'delete', FALSE)
230 )
231 ) {
232 throw new API_Exception('You do not have permission to delete this contribution');
233 }
234 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
235 return civicrm_api3_create_success([$contributionID => 1]);
236 }
237 else {
238 throw new API_Exception('Could not delete contribution');
239 }
240 }
241
242 /**
243 * Modify metadata for delete action.
244 *
245 * Legacy support for contribution_id.
246 *
247 * @param array $params
248 */
249 function _civicrm_api3_contribution_delete_spec(&$params) {
250 $params['id']['api.aliases'] = ['contribution_id'];
251 }
252
253 /**
254 * Retrieve a set of contributions.
255 *
256 * @param array $params
257 * Input parameters.
258 *
259 * @return array
260 * Array of contributions, if error an array with an error id and error message
261 */
262 function civicrm_api3_contribution_get($params) {
263
264 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
265 $additionalOptions = _civicrm_api3_contribution_get_support_nonunique_returns($params);
266 $returnProperties = CRM_Contribute_BAO_Query::defaultReturnProperties($mode);
267
268 $contributions = _civicrm_api3_get_using_query_object('Contribution', $params, $additionalOptions, NULL, $mode, $returnProperties);
269
270 foreach ($contributions as $id => $contribution) {
271 $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($id, TRUE);
272 $contributions[$id] = array_merge($contribution, $softContribution);
273 // format soft credit for backward compatibility
274 _civicrm_api3_format_soft_credit($contributions[$id]);
275 _civicrm_api3_contribution_add_supported_fields($contributions[$id]);
276
277 }
278 return civicrm_api3_create_success($contributions, $params, 'Contribution', 'get');
279 }
280
281 /**
282 * Fix the return values to reflect cases where the schema has been changed.
283 *
284 * At the query object level using uniquenames dismbiguates between tables.
285 *
286 * However, adding uniquename can change inputs accepted by the api, so we need
287 * to ensure we are asking for the unique name return fields.
288 *
289 * @param array $params
290 *
291 * @return array
292 * @throws \API_Exception
293 */
294 function _civicrm_api3_contribution_get_support_nonunique_returns($params) {
295 $additionalOptions = [];
296 $options = _civicrm_api3_get_options_from_params($params, TRUE);
297 foreach (['check_number', 'address_id', 'cancel_date'] as $changedVariable) {
298 if (isset($options['return']) && !empty($options['return'][$changedVariable])) {
299 $additionalOptions['return']['contribution_' . $changedVariable] = 1;
300 }
301 }
302 return $additionalOptions;
303 }
304
305 /**
306 * Support for supported output variables.
307 *
308 * @param $contribution
309 */
310 function _civicrm_api3_contribution_add_supported_fields(&$contribution) {
311 // These are output fields that are supported in our test contract.
312 // Arguably we should also do the same with 'campaign_id' &
313 // 'source' - which are also fields being rendered with unique names.
314 // That seems more consistent with other api where we output the actual field names.
315 $outputAliases = [
316 'contribution_check_number' => 'check_number',
317 'contribution_address_id' => 'address_id',
318 'payment_instrument_id' => 'instrument_id',
319 'contribution_cancel_date' => 'cancel_date',
320 ];
321 foreach ($outputAliases as $returnName => $copyTo) {
322 if (array_key_exists($returnName, $contribution)) {
323 $contribution[$copyTo] = $contribution[$returnName];
324 }
325 }
326
327 }
328
329 /**
330 * Get number of contacts matching the supplied criteria.
331 *
332 * @param array $params
333 *
334 * @return int
335 */
336 function civicrm_api3_contribution_getcount($params) {
337 $count = _civicrm_api3_get_using_query_object('Contribution', $params, [], TRUE, CRM_Contact_BAO_Query::MODE_CONTRIBUTE);
338 return (int) $count;
339 }
340
341 /**
342 * This function is used to format the soft credit for backward compatibility.
343 *
344 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
345 * but we still return first soft credit as a part of contribution array
346 *
347 * @param $contribution
348 */
349 function _civicrm_api3_format_soft_credit(&$contribution) {
350 if (!empty($contribution['soft_credit'])) {
351 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
352 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
353 }
354 }
355
356 /**
357 * Adjust Metadata for Get action.
358 *
359 * The metadata is used for setting defaults, documentation & validation.
360 *
361 * @param array $params
362 * Array of parameters determined by getfields.
363 */
364 function _civicrm_api3_contribution_get_spec(&$params) {
365 $params['contribution_test'] = [
366 'api.default' => 0,
367 'type' => CRM_Utils_Type::T_BOOLEAN,
368 'title' => 'Get Test Contributions?',
369 'api.aliases' => ['is_test'],
370 ];
371
372 $params['financial_type_id']['api.aliases'] = ['contribution_type_id'];
373 $params['payment_instrument_id']['api.aliases'] = ['contribution_payment_instrument', 'payment_instrument'];
374 $params['contact_id'] = CRM_Utils_Array::value('contribution_contact_id', $params);
375 $params['contact_id']['api.aliases'] = ['contribution_contact_id'];
376 unset($params['contribution_contact_id']);
377 }
378
379 /**
380 * Legacy handling for contribution parameters.
381 *
382 * Take the input parameter list as specified in the data model and
383 * convert it into the same format that we use in QF and BAO object.
384 *
385 * @param array $params
386 * property name/value pairs to insert in new contact.
387 * @param array $values
388 * The reformatted properties that we can use internally.
389 *
390 * @return array
391 */
392 function _civicrm_api3_contribute_format_params($params, &$values) {
393 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
394 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
395 return [];
396 }
397
398 /**
399 * Adjust Metadata for Transact action.
400 *
401 * The metadata is used for setting defaults, documentation & validation.
402 *
403 * @param array $params
404 * Array of parameters determined by getfields.
405 */
406 function _civicrm_api3_contribution_transact_spec(&$params) {
407 $fields = civicrm_api3('Contribution', 'getfields', ['action' => 'create']);
408 $params = array_merge($params, $fields['values']);
409 $params['receive_date']['api.default'] = 'now';
410 }
411
412 /**
413 * Process a transaction and record it against the contact.
414 *
415 * @param array $params
416 * Input parameters.
417 *
418 * @return array
419 * contribution of created or updated record (or a civicrm error)
420 */
421 function civicrm_api3_contribution_transact($params) {
422 // Set some params specific to payment processing
423 // @todo - fix this function - none of the results checked by civicrm_error would ever be an array with
424 // 'is_error' set
425 // also trxn_id is not saved.
426 // but since there is no test it's not desirable to jump in & make the obvious changes.
427 $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
428 $params['amount'] = $params['total_amount'];
429 if (!isset($params['net_amount'])) {
430 $params['net_amount'] = $params['amount'];
431 }
432 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
433 $params['invoiceID'] = $params['invoice_id'];
434 }
435
436 // Some payment processors expect a unique invoice_id - generate one if not supplied
437 $params['invoice_id'] = CRM_Utils_Array::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
438
439 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
440 $paymentProcessor['object']->doPayment($params);
441
442 $params['payment_instrument_id'] = $paymentProcessor['object']->getPaymentInstrumentID();
443
444 return civicrm_api('Contribution', 'create', $params);
445 }
446
447 /**
448 * Send a contribution confirmation (receipt or invoice).
449 *
450 * The appropriate online template will be used (the existence of related objects
451 * (e.g. memberships ) will affect this selection
452 *
453 * @param array $params
454 * Input parameters.
455 *
456 * @throws Exception
457 */
458 function civicrm_api3_contribution_sendconfirmation($params) {
459 $ids = $values = [];
460 $allowedParams = [
461 'receipt_from_email',
462 'receipt_from_name',
463 'receipt_update',
464 'cc_receipt',
465 'bcc_receipt',
466 'receipt_text',
467 'payment_processor_id',
468 ];
469 $input = array_intersect_key($params, array_flip($allowedParams));
470 $input['is_email_receipt'] = TRUE;
471 CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $params['id'], $values);
472 }
473
474 /**
475 * Adjust Metadata for sendconfirmation action.
476 *
477 * The metadata is used for setting defaults, documentation & validation.
478 *
479 * @param array $params
480 * Array of parameters determined by getfields.
481 */
482 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
483 $params['id'] = [
484 'api.required' => 1,
485 'title' => ts('Contribution ID'),
486 'type' => CRM_Utils_Type::T_INT,
487 ];
488 $params['receipt_from_email'] = [
489 'title' => ts('From Email address (string)'),
490 'type' => CRM_Utils_Type::T_STRING,
491 ];
492 $params['receipt_from_name'] = [
493 'title' => ts('From Name (string)'),
494 'type' => CRM_Utils_Type::T_STRING,
495 ];
496 $params['cc_receipt'] = [
497 'title' => ts('CC Email address (string)'),
498 'type' => CRM_Utils_Type::T_STRING,
499 ];
500 $params['bcc_receipt'] = [
501 'title' => ts('BCC Email address (string)'),
502 'type' => CRM_Utils_Type::T_STRING,
503 ];
504 $params['receipt_text'] = [
505 'title' => ts('Message (string)'),
506 'type' => CRM_Utils_Type::T_STRING,
507 ];
508 $params['receipt_update'] = [
509 'title' => ts('Update the Receipt Date'),
510 'type' => CRM_Utils_Type::T_BOOLEAN,
511 'api.default' => TRUE,
512 ];
513 $params['payment_processor_id'] = [
514 'title' => ts('Payment processor Id (avoids mis-guesses)'),
515 'type' => CRM_Utils_Type::T_INT,
516 ];
517 }
518
519 /**
520 * Complete an existing (pending) transaction.
521 *
522 * This will update related entities (participant, membership, pledge etc)
523 * and take any complete actions from the contribution page (e.g. send receipt).
524 *
525 * @todo - most of this should live in the BAO layer but as we want it to be an addition
526 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
527 *
528 * @param array $params
529 * Input parameters.
530 *
531 * @return array
532 * API result array
533 * @throws \API_Exception
534 * @throws \CRM_Core_Exception
535 * @throws \Exception
536 */
537 function civicrm_api3_contribution_completetransaction($params) {
538 $input = $ids = [];
539 if (isset($params['payment_processor_id'])) {
540 $input['payment_processor_id'] = $params['payment_processor_id'];
541 }
542 $contribution = new CRM_Contribute_BAO_Contribution();
543 $contribution->id = $params['id'];
544 if (!$contribution->find(TRUE)) {
545 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
546 }
547
548 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
549 throw new API_Exception('failed to load related objects');
550 }
551 elseif ($contribution->contribution_status_id == CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed')) {
552 throw new API_Exception(ts('Contribution already completed'), 'contribution_completed');
553 }
554 $input['trxn_id'] = !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
555 if (!empty($params['fee_amount'])) {
556 $input['fee_amount'] = $params['fee_amount'];
557 }
558 return _ipn_process_transaction($params, $contribution, $input, $ids);
559
560 }
561
562 /**
563 * Provide function metadata.
564 *
565 * @param array $params
566 */
567 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
568 $params['id'] = [
569 'title' => 'Contribution ID',
570 'type' => CRM_Utils_Type::T_INT,
571 'api.required' => TRUE,
572 ];
573 $params['trxn_id'] = [
574 'title' => 'Transaction ID',
575 'type' => CRM_Utils_Type::T_STRING,
576 ];
577 $params['is_email_receipt'] = [
578 'title' => 'Send email Receipt?',
579 'type' => CRM_Utils_Type::T_BOOLEAN,
580 ];
581 $params['receipt_from_email'] = [
582 'title' => 'Email to send receipt from.',
583 'description' => 'If not provided this will default to being based on domain mail or contribution page',
584 'type' => CRM_Utils_Type::T_EMAIL,
585 ];
586 $params['receipt_from_name'] = [
587 'title' => 'Name to send receipt from',
588 'description' => '. If not provided this will default to domain mail or contribution page',
589 'type' => CRM_Utils_Type::T_STRING,
590 ];
591 $params['payment_processor_id'] = [
592 'title' => 'Payment processor ID',
593 'description' => 'Providing this is strongly recommended, as not possible to calculate it accurately always',
594 'type' => CRM_Utils_Type::T_INT,
595 ];
596 $params['fee_amount'] = [
597 'title' => 'Fee charged on transaction',
598 'description' => 'If a fee has been charged then the amount',
599 'type' => CRM_Utils_Type::T_FLOAT,
600 ];
601 $params['trxn_date'] = [
602 'title' => 'Transaction Date',
603 'description' => 'Date this transaction occurred',
604 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
605 ];
606 $params['card_type_id'] = [
607 'title' => 'Card Type ID',
608 'description' => 'Providing Credit Card Type ID',
609 'type' => CRM_Utils_Type::T_INT,
610 'pseudoconstant' => [
611 'optionGroupName' => 'accept_creditcard',
612 ],
613 ];
614 }
615
616 /**
617 * Complete an existing (pending) transaction.
618 *
619 * This will update related entities (participant, membership, pledge etc)
620 * and take any complete actions from the contribution page (e.g. send receipt).
621 *
622 * @todo - most of this should live in the BAO layer but as we want it to be an addition
623 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
624 *
625 * @param array $params
626 * Input parameters.
627 *
628 * @return array
629 * Api result array.
630 * @throws API_Exception
631 */
632 function civicrm_api3_contribution_repeattransaction($params) {
633 $input = $ids = [];
634 civicrm_api3_verify_one_mandatory($params, NULL, ['contribution_recur_id', 'original_contribution_id']);
635 if (empty($params['original_contribution_id'])) {
636 // CRM-19873 call with test mode.
637 $params['original_contribution_id'] = civicrm_api3('contribution', 'getvalue', [
638 'return' => 'id',
639 'contribution_status_id' => ['IN' => ['Completed']],
640 'contribution_recur_id' => $params['contribution_recur_id'],
641 'contribution_test' => CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionRecur', $params['contribution_recur_id'], 'is_test'),
642 'options' => ['limit' => 1, 'sort' => 'id DESC'],
643 ]);
644 }
645 $contribution = new CRM_Contribute_BAO_Contribution();
646 $contribution->id = $params['original_contribution_id'];
647 if (!$contribution->find(TRUE)) {
648 throw new API_Exception(
649 'A valid original contribution ID is required', 'invalid_data');
650 }
651 $original_contribution = clone $contribution;
652 $input['payment_processor_id'] = civicrm_api3('contributionRecur', 'getvalue', [
653 'return' => 'payment_processor_id',
654 'id' => $contribution->contribution_recur_id,
655 ]);
656 try {
657 if (!$contribution->loadRelatedObjects($input, $ids, TRUE)) {
658 throw new API_Exception('failed to load related objects');
659 }
660
661 unset($contribution->id, $contribution->receive_date, $contribution->invoice_id);
662 $contribution->receive_date = $params['receive_date'];
663
664 $passThroughParams = [
665 'trxn_id',
666 'total_amount',
667 'campaign_id',
668 'fee_amount',
669 'financial_type_id',
670 'contribution_status_id',
671 ];
672 $input = array_intersect_key($params, array_fill_keys($passThroughParams, NULL));
673
674 return _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
675 }
676 catch (Exception $e) {
677 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
678 }
679 }
680
681 /**
682 * Calls IPN complete transaction for completing or repeating a transaction.
683 *
684 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
685 * when separating them in the api layer.
686 *
687 * @param array $params
688 * @param CRM_Contribute_BAO_Contribution $contribution
689 * @param array $input
690 *
691 * @param array $ids
692 *
693 * @param CRM_Contribute_BAO_Contribution $firstContribution
694 *
695 * @return mixed
696 */
697 function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
698 $objects = $contribution->_relatedObjects;
699 $objects['contribution'] = &$contribution;
700
701 if ($firstContribution) {
702 $objects['first_contribution'] = $firstContribution;
703 }
704 $input['component'] = $contribution->_component;
705 $input['is_test'] = $contribution->is_test;
706 $input['amount'] = empty($input['total_amount']) ? $contribution->total_amount : $input['total_amount'];
707
708 if (isset($params['is_email_receipt'])) {
709 $input['is_email_receipt'] = $params['is_email_receipt'];
710 }
711 if (!empty($params['trxn_date'])) {
712 $input['trxn_date'] = $params['trxn_date'];
713 }
714 if (!empty($params['receive_date'])) {
715 $input['receive_date'] = $params['receive_date'];
716 }
717 if (empty($contribution->contribution_page_id)) {
718 static $domainFromName;
719 static $domainFromEmail;
720 if (empty($domainFromEmail) && (empty($params['receipt_from_name']) || empty($params['receipt_from_email']))) {
721 list($domainFromName, $domainFromEmail) = CRM_Core_BAO_Domain::getNameAndEmail(TRUE);
722 }
723 $input['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', $params, $domainFromName);
724 $input['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', $params, $domainFromEmail);
725 }
726 $input['card_type_id'] = CRM_Utils_Array::value('card_type_id', $params);
727 $input['pan_truncation'] = CRM_Utils_Array::value('pan_truncation', $params);
728 $transaction = new CRM_Core_Transaction();
729 return CRM_Contribute_BAO_Contribution::completeOrder($input, $ids, $objects, $transaction,
730 !empty($contribution->contribution_recur_id), $contribution);
731 }
732
733 /**
734 * Provide function metadata.
735 *
736 * @param array $params
737 */
738 function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
739 $params['original_contribution_id'] = [
740 'title' => 'Original Contribution ID',
741 'description' => 'Contribution ID to copy (will be calculated from recurring contribution if not provided)',
742 'type' => CRM_Utils_Type::T_INT,
743 ];
744 $params['contribution_recur_id'] = [
745 'title' => 'Recurring contribution ID',
746 'type' => CRM_Utils_Type::T_INT,
747 ];
748 $params['trxn_id'] = [
749 'title' => 'Transaction ID',
750 'type' => CRM_Utils_Type::T_STRING,
751 ];
752 $params['is_email_receipt'] = [
753 'title' => 'Send email Receipt?',
754 'type' => CRM_Utils_Type::T_BOOLEAN,
755 ];
756 $params['contribution_status_id'] = [
757 'title' => 'Contribution Status ID',
758 'name' => 'contribution_status_id',
759 'type' => CRM_Utils_Type::T_INT,
760 'pseudoconstant' => [
761 'optionGroupName' => 'contribution_status',
762 ],
763 'api.required' => TRUE,
764 ];
765 $params['receive_date'] = [
766 'title' => 'Contribution Receive Date',
767 'name' => 'receive_date',
768 'type' => CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME,
769 'api.default' => 'now',
770 ];
771 $params['trxn_id'] = [
772 'title' => 'Transaction ID',
773 'name' => 'trxn_id',
774 'type' => CRM_Utils_Type::T_STRING,
775 ];
776 $params['campaign_id'] = [
777 'title' => 'Campaign ID',
778 'name' => 'campaign_id',
779 'type' => CRM_Utils_Type::T_INT,
780 'pseudoconstant' => [
781 'table' => 'civicrm_campaign',
782 'keyColumn' => 'id',
783 'labelColumn' => 'title',
784 ],
785 ];
786 $params['financial_type_id'] = [
787 'title' => 'Financial ID (ignored if more than one line item)',
788 'name' => 'financial_type_id',
789 'type' => CRM_Utils_Type::T_INT,
790 'pseudoconstant' => [
791 'table' => 'civicrm_financial_type',
792 'keyColumn' => 'id',
793 'labelColumn' => 'name',
794 ],
795 ];
796 $params['payment_processor_id'] = [
797 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
798 'title' => 'Payment processor ID',
799 'name' => 'payment_processor_id',
800 'type' => CRM_Utils_Type::T_INT,
801 ];
802 }