Merge pull request #5421 from monishdeb/CRM-15536
[civicrm-core.git] / api / v3 / Contribution.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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 = array();
46 _civicrm_api3_custom_format_params($params, $values, 'Contribution');
47 $params = array_merge($params, $values);
48
49 if (!empty($params['id']) && !empty($params['contribution_status_id'])) {
50 $error = array();
51 //throw error for invalid status change such as setting completed back to pending
52 //@todo this sort of validation belongs in the BAO not the API - if it is not an OK
53 // action it needs to be blocked there. If it is Ok through a form it needs to be OK through the api
54 CRM_Contribute_BAO_Contribution::checkStatusValidation(NULL, $params, $error);
55 if (array_key_exists('contribution_status_id', $error)) {
56 throw new API_Exception($error['contribution_status_id']);
57 }
58 }
59
60 _civicrm_api3_contribution_create_legacy_support_45($params);
61
62 // Make sure tax calculation is handled via api.
63 $params = CRM_Contribute_BAO_Contribution::checkTaxAmount($params);
64
65 return _civicrm_api3_basic_create(_civicrm_api3_get_BAO(__FUNCTION__), $params, 'Contribution');
66 }
67
68 /**
69 * Adjust Metadata for Create action.
70 *
71 * The metadata is used for setting defaults, documentation & validation.
72 *
73 * @param array $params
74 * Array of parameters determined by getfields.
75 */
76 function _civicrm_api3_contribution_create_spec(&$params) {
77 $params['contact_id']['api.required'] = 1;
78 $params['total_amount']['api.required'] = 1;
79 $params['payment_instrument_id']['api.aliases'] = array('payment_instrument');
80 $params['receive_date']['api.default'] = 'now';
81 $params['payment_processor'] = array(
82 'name' => 'payment_processor',
83 'title' => 'Payment Processor ID',
84 'description' => 'ID of payment processor used for this contribution',
85 // field is called payment processor - not payment processor id but can only be one id so
86 // it seems likely someone will fix it up one day to be more consistent - lets alias it from the start
87 'api.aliases' => array('payment_processor_id'),
88 'type' => CRM_Utils_Type::T_INT,
89 );
90 $params['financial_type_id']['api.aliases'] = array('contribution_type_id', 'contribution_type');
91 $params['financial_type_id']['api.required'] = 1;
92 $params['note'] = array(
93 'name' => 'note',
94 'uniqueName' => 'contribution_note',
95 'title' => 'note',
96 'type' => 2,
97 'description' => 'Associated Note in the notes table',
98 );
99 $params['soft_credit_to'] = array(
100 'name' => 'soft_credit_to',
101 'title' => 'Soft Credit contact ID (legacy)',
102 'type' => 1,
103 'description' => 'ID of Contact to be Soft credited to (deprecated - use contribution_soft api)',
104 'FKClassName' => 'CRM_Contact_DAO_Contact',
105 );
106 $params['honor_contact_id'] = array(
107 'name' => 'honor_contact_id',
108 'title' => 'Honoree contact ID (legacy)',
109 'type' => 1,
110 'description' => 'ID of honoree contact (deprecated - use contribution_soft api)',
111 'FKClassName' => 'CRM_Contact_DAO_Contact',
112 );
113 $params['honor_type_id'] = array(
114 'name' => 'honor_type_id',
115 'title' => 'Honoree Type (legacy)',
116 'type' => 1,
117 'description' => 'Type of honoree contact (deprecated - use contribution_soft api)',
118 'pseudoconstant' => TRUE,
119 );
120 // note this is a recommended option but not adding as a default to avoid
121 // creating unnecessary changes for the dev
122 $params['skipRecentView'] = array(
123 'name' => 'skipRecentView',
124 'title' => 'Skip adding to recent view',
125 'type' => CRM_Utils_Type::T_BOOLEAN,
126 'description' => 'Do not add to recent view (setting this improves performance)',
127 );
128 $params['skipLineItem'] = array(
129 'name' => 'skipLineItem',
130 'title' => 'Skip adding line items',
131 'type' => 1,
132 'api.default' => 0,
133 'description' => 'Do not add line items by default (if you wish to add your own)',
134 );
135 $params['batch_id'] = array(
136 'title' => 'Batch',
137 'type' => 1,
138 'description' => 'Batch which relevant transactions should be added to',
139 );
140 }
141
142 /**
143 * Support for schema changes made in 4.5.
144 *
145 * The main purpose of the API is to provide integrators a level of stability not provided by
146 * the core code or schema - this means we have to provide support for api calls (where possible)
147 * across schema changes.
148 *
149 * @param array $params
150 */
151 function _civicrm_api3_contribution_create_legacy_support_45(&$params) {
152 //legacy soft credit handling - recommended approach is chaining
153 if (!empty($params['soft_credit_to'])) {
154 $params['soft_credit'][] = array(
155 'contact_id' => $params['soft_credit_to'],
156 'amount' => $params['total_amount'],
157 'soft_credit_type_id' => CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"),
158 );
159 }
160 if (!empty($params['honor_contact_id'])) {
161 $params['soft_credit'][] = array(
162 'contact_id' => $params['honor_contact_id'],
163 'amount' => $params['total_amount'],
164 'soft_credit_type_id' => CRM_Utils_Array::value('honor_type_id', $params, CRM_Core_OptionGroup::getValue('soft_credit_type', 'in_honor_of', 'name')),
165 );
166 }
167 }
168
169 /**
170 * Delete a Contribution.
171 *
172 * @param array $params
173 * Input parameters.
174 *
175 * @return array
176 */
177 function civicrm_api3_contribution_delete($params) {
178
179 $contributionID = !empty($params['contribution_id']) ? $params['contribution_id'] : $params['id'];
180 if (CRM_Contribute_BAO_Contribution::deleteContribution($contributionID)) {
181 return civicrm_api3_create_success(array($contributionID => 1));
182 }
183 else {
184 return civicrm_api3_create_error('Could not delete contribution');
185 }
186 }
187
188 /**
189 * Modify metadata for delete action.
190 *
191 * Legacy support for contribution_id.
192 *
193 * @param array $params
194 */
195 function _civicrm_api3_contribution_delete_spec(&$params) {
196 $params['id']['api.aliases'] = array('contribution_id');
197 }
198
199 /**
200 * Retrieve a set of contributions.
201 *
202 * @param array $params
203 * Input parameters.
204 *
205 * @return array
206 * Array of contributions, if error an array with an error id and error message
207 */
208 function civicrm_api3_contribution_get($params) {
209
210 $mode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
211 list($dao, $query) = _civicrm_api3_get_query_object($params, $mode, 'Contribution');
212
213 $contribution = array();
214 while ($dao->fetch()) {
215 //CRM-8662
216 $contribution_details = $query->store($dao);
217 $softContribution = CRM_Contribute_BAO_ContributionSoft::getSoftContribution($dao->contribution_id, TRUE);
218 $contribution[$dao->contribution_id] = array_merge($contribution_details, $softContribution);
219 // format soft credit for backward compatibility
220 _civicrm_api3_format_soft_credit($contribution[$dao->contribution_id]);
221 }
222 return civicrm_api3_create_success($contribution, $params, 'Contribution', 'get', $dao);
223 }
224
225 /**
226 * This function is used to format the soft credit for backward compatibility.
227 *
228 * As of v4.4 we support multiple soft credit, so now contribution returns array with 'soft_credit' as key
229 * but we still return first soft credit as a part of contribution array
230 *
231 * @param $contribution
232 */
233 function _civicrm_api3_format_soft_credit(&$contribution) {
234 if (!empty($contribution['soft_credit'])) {
235 $contribution['soft_credit_to'] = $contribution['soft_credit'][1]['contact_id'];
236 $contribution['soft_credit_id'] = $contribution['soft_credit'][1]['soft_credit_id'];
237 }
238 }
239
240 /**
241 * Adjust Metadata for Get action.
242 *
243 * The metadata is used for setting defaults, documentation & validation.
244 *
245 * @param array $params
246 * Array of parameters determined by getfields.
247 */
248 function _civicrm_api3_contribution_get_spec(&$params) {
249 $params['contribution_test'] = array(
250 'api.default' => 0,
251 'type' => CRM_Utils_Type::T_BOOLEAN,
252 'title' => 'Get Test Contributions?',
253 );
254 $params['financial_type_id']['api.aliases'] = array('contribution_type_id');
255 $params['contact_id'] = $params['contribution_contact_id'];
256 $params['contact_id']['api.aliases'] = array('contribution_contact_id');
257 unset($params['contribution_contact_id']);
258 }
259
260 /**
261 * Legacy handling for contribution parameters.
262 *
263 * Take the input parameter list as specified in the data model and
264 * convert it into the same format that we use in QF and BAO object.
265 *
266 * @param array $params
267 * property name/value pairs to insert in new contact.
268 * @param array $values
269 * The reformatted properties that we can use internally.
270 *
271 * @return array
272 */
273 function _civicrm_api3_contribute_format_params($params, &$values) {
274 //legacy way of formatting from v2 api - v3 way is to define metadata & do it in the api layer
275 _civicrm_api3_filter_fields_for_bao('Contribution', $params, $values);
276 return array();
277 }
278
279 /**
280 * Adjust Metadata for Transact action.
281 *
282 * The metadata is used for setting defaults, documentation & validation.
283 *
284 * @param array $params
285 * Array of parameters determined by getfields.
286 */
287 function _civicrm_api3_contribution_transact_spec(&$params) {
288 $fields = civicrm_api3('Contribution', 'getfields', array('action' => 'create'));
289 $params = array_merge($params, $fields['values']);
290 $params['receive_date']['api.default'] = 'now';
291 }
292
293 /**
294 * Process a transaction and record it against the contact.
295 *
296 * @param array $params
297 * Input parameters.
298 *
299 * @return array
300 * contribution of created or updated record (or a civicrm error)
301 */
302 function civicrm_api3_contribution_transact($params) {
303 // Set some params specific to payment processing
304 // @todo - fix this function - none of the results checked by civicrm_error would ever be an array with
305 // 'is_error' set
306 // also trxn_id is not saved.
307 // but since there is no test it's not desirable to jump in & make the obvious changes.
308 $params['payment_processor_mode'] = empty($params['is_test']) ? 'live' : 'test';
309 $params['amount'] = $params['total_amount'];
310 if (!isset($params['net_amount'])) {
311 $params['net_amount'] = $params['amount'];
312 }
313 if (!isset($params['invoiceID']) && isset($params['invoice_id'])) {
314 $params['invoiceID'] = $params['invoice_id'];
315 }
316
317 // Some payment processors expect a unique invoice_id - generate one if not supplied
318 $params['invoice_id'] = CRM_Utils_Array::value('invoice_id', $params, md5(uniqid(rand(), TRUE)));
319
320 $paymentProcessor = CRM_Financial_BAO_PaymentProcessor::getPayment($params['payment_processor'], $params['payment_processor_mode']);
321 if (civicrm_error($paymentProcessor)) {
322 return $paymentProcessor;
323 }
324
325 $payment = CRM_Core_Payment::singleton($params['payment_processor_mode'], $paymentProcessor);
326 if (civicrm_error($payment)) {
327 return $payment;
328 }
329
330 $transaction = $payment->doPayment($params);
331
332 $params['payment_instrument_id'] = CRM_Core_DAO::getFieldValue('CRM_Financial_DAO_PaymentProcessorType', $paymentProcessor['payment_processor_type_id'], 'payment_type') == 1 ? 'Credit Card' : 'Debit Card';
333 return civicrm_api('Contribution', 'create', $params);
334 }
335
336 /**
337 * Send a contribution confirmation (receipt or invoice).
338 *
339 * The appropriate online template will be used (the existence of related objects
340 * (e.g. memberships ) will affect this selection
341 *
342 * @param array $params
343 * Input parameters.
344 *
345 * @throws Exception
346 */
347 function civicrm_api3_contribution_sendconfirmation($params) {
348 $contribution = new CRM_Contribute_BAO_Contribution();
349 $contribution->id = $params['id'];
350 if (!$contribution->find(TRUE)) {
351 throw new Exception('Contribution does not exist');
352 }
353 $input = $ids = $cvalues = array('receipt_from_email' => $params['receipt_from_email']);
354 $contribution->loadRelatedObjects($input, $ids, FALSE, TRUE);
355 $contribution->composeMessageArray($input, $ids, $cvalues, FALSE, FALSE);
356 }
357
358 /**
359 * Adjust Metadata for sendconfirmation action.
360 *
361 * The metadata is used for setting defaults, documentation & validation.
362 *
363 * @param array $params
364 * Array of parameters determined by getfields.
365 */
366 function _civicrm_api3_contribution_sendconfirmation_spec(&$params) {
367 $params['id'] = array(
368 'api.required' => 1,
369 'title' => 'Contribution ID',
370 'type' => CRM_Utils_Type::T_INT,
371 );
372 $params['receipt_from_email'] = array(
373 'api.required' => 1,
374 'title' => 'From Email address (string) required until someone provides a patch :-)',
375 'type' => CRM_Utils_Type::T_STRING,
376 );
377 $params['receipt_from_name'] = array(
378 'title' => 'From Name (string)',
379 'type' => CRM_Utils_Type::T_STRING,
380 );
381 $params['cc_receipt'] = array(
382 'title' => 'CC Email address (string)',
383 'type' => CRM_Utils_Type::T_STRING,
384 );
385 $params['bcc_receipt'] = array(
386 'title' => 'BCC Email address (string)',
387 'type' => CRM_Utils_Type::T_STRING,
388 );
389 $params['receipt_text'] = array(
390 'title' => 'Message (string)',
391 'type' => CRM_Utils_Type::T_STRING,
392 );
393 }
394
395 /**
396 * Complete an existing (pending) transaction.
397 *
398 * This will update related entities (participant, membership, pledge etc)
399 * and take any complete actions from the contribution page (e.g. send receipt).
400 *
401 * @todo - most of this should live in the BAO layer but as we want it to be an addition
402 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
403 *
404 * @param array $params
405 * Input parameters.
406 *
407 * @throws API_Exception
408 * Api result array.
409 */
410 function civicrm_api3_contribution_completetransaction(&$params) {
411
412 $input = $ids = array();
413 $contribution = new CRM_Contribute_BAO_Contribution();
414 $contribution->id = $params['id'];
415 $contribution->find(TRUE);
416 if (!$contribution->id == $params['id']) {
417 throw new API_Exception('A valid contribution ID is required', 'invalid_data');
418 }
419 try {
420 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
421 throw new API_Exception('failed to load related objects');
422 }
423 elseif ($contribution->contribution_status_id == CRM_Core_OptionGroup::getValue('contribution_status', 'Completed', 'name')) {
424 throw new API_Exception(ts('Contribution already completed'));
425 }
426 $input['trxn_id'] = !empty($params['trxn_id']) ? $params['trxn_id'] : $contribution->trxn_id;
427 $params = _ipn_process_transaction($params, $contribution, $input, $ids);
428 }
429 catch(Exception $e) {
430 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
431 }
432 }
433
434 /**
435 * Provide function metadata.
436 *
437 * @param array $params
438 */
439 function _civicrm_api3_contribution_completetransaction_spec(&$params) {
440 $params['id'] = array(
441 'title' => 'Contribution ID',
442 'type' => CRM_Utils_Type::T_INT,
443 'api.required' => TRUE,
444 );
445 $params['trxn_id'] = array(
446 'title' => 'Transaction ID',
447 'type' => CRM_Utils_Type::T_STRING,
448 );
449 $params['is_email_receipt'] = array(
450 'title' => 'Send email Receipt?',
451 'type' => CRM_Utils_Type::T_BOOLEAN,
452 );
453 }
454
455 /**
456 * Complete an existing (pending) transaction.
457 *
458 * This will update related entities (participant, membership, pledge etc)
459 * and take any complete actions from the contribution page (e.g. send receipt).
460 *
461 * @todo - most of this should live in the BAO layer but as we want it to be an addition
462 * to 4.3 which is already stable we should add it to the api layer & re-factor into the BAO layer later
463 *
464 * @param array $params
465 * Input parameters.
466 *
467 * @throws API_Exception
468 * Api result array.
469 */
470 function civicrm_api3_contribution_repeattransaction(&$params) {
471 $input = $ids = array();
472 $contribution = new CRM_Contribute_BAO_Contribution();
473 $contribution->id = $params['original_contribution_id'];
474 if (!$contribution->find(TRUE)) {
475 throw new API_Exception(
476 'A valid original contribution ID is required', 'invalid_data');
477 }
478 $original_contribution = clone $contribution;
479 try {
480 if (!$contribution->loadRelatedObjects($input, $ids, FALSE, TRUE)) {
481 throw new API_Exception('failed to load related objects');
482 }
483
484 unset($contribution->id, $contribution->receive_date, $contribution->invoice_id);
485 $contribution->contribution_status_id = $params['contribution_status_id'];
486 $contribution->receive_date = $params['receive_date'];
487 // Have not set trxn_id to required but an e-notice if not provided seems appropriate.
488 $input['trxn_id'] = $params['trxn_id'];
489
490 $params = _ipn_process_transaction($params, $contribution, $input, $ids, $original_contribution);
491 }
492 catch(Exception $e) {
493 throw new API_Exception('failed to load related objects' . $e->getMessage() . "\n" . $e->getTraceAsString());
494 }
495 }
496
497 /**
498 * Calls IPN complete transaction for completing or repeating a transaction.
499 *
500 * The IPN function is overloaded with two purposes - this is simply a wrapper for that
501 * when separating them in the api layer.
502 *
503 * @param array $params
504 * @param CRM_Contribute_BAO_Contribution $contribution
505 * @param array $input
506 *
507 * @param array $ids
508 *
509 * @param CRM_Contribute_BAO_Contribution $firstContribution
510 *
511 * @return mixed
512 */
513 function _ipn_process_transaction(&$params, $contribution, $input, $ids, $firstContribution = NULL) {
514 $objects = $contribution->_relatedObjects;
515 $objects['contribution'] = &$contribution;
516
517 if ($firstContribution) {
518 $objects['first_contribution'] = $firstContribution;
519 }
520 $input['component'] = $contribution->_component;
521 $input['is_test'] = $contribution->is_test;
522 $input['amount'] = $contribution->total_amount;
523 if (isset($params['is_email_receipt'])) {
524 $input['is_email_receipt'] = $params['is_email_receipt'];
525 }
526 // @todo required for base ipn but problematic as api layer handles this
527 $transaction = new CRM_Core_Transaction();
528 $ipn = new CRM_Core_Payment_BaseIPN();
529 $ipn->completeTransaction($input, $ids, $objects, $transaction, !empty($contribution->contribution_recur_id));
530 return $params;
531 }
532
533 /**
534 * Provide function metadata.
535 *
536 * @param array $params
537 */
538 function _civicrm_api3_contribution_repeattransaction_spec(&$params) {
539 $params['original_contribution_id'] = array(
540 'title' => 'Original Contribution ID',
541 'type' => CRM_Utils_Type::T_INT,
542 'api.required' => TRUE,
543 );
544 $params['trxn_id'] = array(
545 'title' => 'Transaction ID',
546 'type' => CRM_Utils_Type::T_STRING,
547 );
548 $params['is_email_receipt'] = array(
549 'title' => 'Send email Receipt?',
550 'type' => CRM_Utils_Type::T_BOOLEAN,
551 );
552 $params['contribution_status_id'] = array(
553 'title' => 'Contribution Status ID',
554 'name' => 'contribution_status_id',
555 'type' => CRM_Utils_Type::T_INT,
556 'pseudoconstant' => array(
557 'optionGroupName' => 'contribution_status',
558 ),
559 'api.required' => TRUE,
560 );
561 $params['receive_date'] = array(
562 'title' => 'Contribution Receive Date',
563 'name' => 'receive_date',
564 'type' => CRM_Utils_Type::T_DATE,
565 'api.default' => 'now',
566 );
567 $params['trxn_id'] = array(
568 'title' => 'Transaction ID',
569 'name' => 'trxn_id',
570 'type' => CRM_Utils_Type::T_STRING,
571 );
572 $params['payment_processor_id'] = array(
573 'description' => ts('Payment processor ID, will be loaded from contribution_recur if not provided'),
574 'title' => 'Payment processor ID',
575 'name' => 'payment_processor_id',
576 'type' => CRM_Utils_Type::T_INT,
577 );
578 }