3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * class to parse contribution csv files
39 class CRM_Contribute_Import_Parser_Contribution
extends CRM_Contribute_Import_Parser
{
41 protected $_mapperKeys;
43 private $_contactIdIndex;
44 private $_totalAmountIndex;
45 private $_contributionTypeIndex;
47 protected $_mapperSoftCredit;
48 //protected $_mapperPhoneType;
51 * Array of successfully imported contribution id's
55 protected $_newContributions;
60 function __construct(&$mapperKeys, $mapperSoftCredit = NULL, $mapperPhoneType = NULL, $mapperSoftCreditType = NULL) {
61 parent
::__construct();
62 $this->_mapperKeys
= &$mapperKeys;
63 $this->_mapperSoftCredit
= &$mapperSoftCredit;
64 $this->_mapperSoftCreditType
= &$mapperSoftCreditType;
68 * the initializer code, called before the processing
74 $fields = CRM_Contribute_BAO_Contribution
::importableFields($this->_contactType
, FALSE);
76 $fields = array_merge($fields,
78 'soft_credit' => array(
79 'title' => ts('Soft Credit'),
81 'headerPattern' => '/Soft Credit/i',
86 // add pledge fields only if its is enabled
87 if (CRM_Core_Permission
::access('CiviPledge')) {
88 $pledgeFields = array(
89 'pledge_payment' => array(
90 'title' => ts('Pledge Payment'),
91 'headerPattern' => '/Pledge Payment/i',
94 'title' => ts('Pledge ID'),
95 'headerPattern' => '/Pledge ID/i',
99 $fields = array_merge($fields, $pledgeFields);
101 foreach ($fields as $name => $field) {
102 $field['type'] = CRM_Utils_Array
::value('type', $field, CRM_Utils_Type
::T_INT
);
103 $field['dataPattern'] = CRM_Utils_Array
::value('dataPattern', $field, '//');
104 $field['headerPattern'] = CRM_Utils_Array
::value('headerPattern', $field, '//');
105 $this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
108 $this->_newContributions
= array();
110 $this->setActiveFields($this->_mapperKeys
);
111 $this->setActiveFieldSoftCredit($this->_mapperSoftCredit
);
112 $this->setActiveFieldSoftCreditType($this->_mapperSoftCreditType
);
114 // FIXME: we should do this in one place together with Form/MapField.php
115 $this->_contactIdIndex
= -1;
116 $this->_totalAmountIndex
= -1;
117 $this->_contributionTypeIndex
= -1;
120 foreach ($this->_mapperKeys
as $key) {
122 case 'contribution_contact_id':
123 $this->_contactIdIndex
= $index;
127 $this->_totalAmountIndex
= $index;
130 case 'financial_type':
131 $this->_contributionTypeIndex
= $index;
139 * handle the values in mapField mode
141 * @param array $values the array of values belonging to this line
146 function mapField(&$values) {
147 return CRM_Import_Parser
::VALID
;
151 * handle the values in preview mode
153 * @param array $values the array of values belonging to this line
155 * @return boolean the result of this processing
158 function preview(&$values) {
159 return $this->summary($values);
163 * handle the values in summary mode
165 * @param array $values the array of values belonging to this line
167 * @return boolean the result of this processing
170 function summary(&$values) {
171 $erroneousField = NULL;
172 $response = $this->setActiveFieldValues($values, $erroneousField);
174 $params = &$this->getActiveFieldParams();
175 $errorMessage = NULL;
178 $session = CRM_Core_Session
::singleton();
179 $dateType = $session->get('dateTypes');
180 foreach ($params as $key => $val) {
184 if ($dateValue = CRM_Utils_Date
::formatDate($params[$key], $dateType)) {
185 $params[$key] = $dateValue;
188 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Receive Date', $errorMessage);
193 if ($dateValue = CRM_Utils_Date
::formatDate($params[$key], $dateType)) {
194 $params[$key] = $dateValue;
197 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Cancel Date', $errorMessage);
202 if ($dateValue = CRM_Utils_Date
::formatDate($params[$key], $dateType)) {
203 $params[$key] = $dateValue;
206 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Receipt date', $errorMessage);
210 case 'thankyou_date':
211 if ($dateValue = CRM_Utils_Date
::formatDate($params[$key], $dateType)) {
212 $params[$key] = $dateValue;
215 CRM_Contact_Import_Parser_Contact
::addToErrorMsg('Thankyou Date', $errorMessage);
221 //date-Format part ends
223 $params['contact_type'] = 'Contribution';
225 //checking error in custom data
226 CRM_Contact_Import_Parser_Contact
::isErrorInCustomData($params, $errorMessage);
229 $tempMsg = "Invalid value for field(s) : $errorMessage";
230 array_unshift($values, $tempMsg);
231 $errorMessage = NULL;
232 return CRM_Import_Parser
::ERROR
;
235 return CRM_Import_Parser
::VALID
;
239 * handle the values in import mode
241 * @param int $onDuplicate the code for what action to take on duplicates
242 * @param array $values the array of values belonging to this line
244 * @return boolean the result of this processing
247 function import($onDuplicate, &$values) {
248 // first make sure this is a valid line
249 $response = $this->summary($values);
250 if ($response != CRM_Import_Parser
::VALID
) {
254 $params = &$this->getActiveFieldParams();
255 $formatted = array('version' => 3);
257 // don't add to recent items, CRM-4399
258 $formatted['skipRecentView'] = TRUE;
261 $session = CRM_Core_Session
::singleton();
262 $dateType = $session->get('dateTypes');
264 $customFields = CRM_Core_BAO_CustomField
::getFields(CRM_Utils_Array
::value('contact_type', $params));
267 if (isset($params['total_amount']) && $params['total_amount'] == 0) {
268 $params['total_amount'] = '0.00';
270 foreach ($params as $key => $val) {
276 case 'thankyou_date':
277 $params[$key] = CRM_Utils_Date
::formatDate($params[$key], $dateType);
279 case 'pledge_payment':
280 $params[$key] = CRM_Utils_String
::strtobool($val);
283 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) {
284 if ($customFields[$customFieldID]['data_type'] == 'Date') {
285 CRM_Contact_Import_Parser_Contact
::formatCustomDate($params, $formatted, $dateType, $key);
286 unset($params[$key]);
288 elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
289 $params[$key] = CRM_Utils_String
::strtoboolstr($val);
294 //date-Format part ends
296 static $indieFields = NULL;
297 if ($indieFields == NULL) {
298 $tempIndieFields = CRM_Contribute_DAO_Contribution
::import();
299 $indieFields = $tempIndieFields;
302 $paramValues = array();
303 foreach ($params as $key => $field) {
304 if ($field == NULL ||
$field === '') {
307 $paramValues[$key] = $field;
310 //import contribution record according to select contact type
311 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_SKIP
&&
312 (!empty($paramValues['contribution_contact_id']) ||
!empty($paramValues['external_identifier']))
314 $paramValues['contact_type'] = $this->_contactType
;
316 elseif ($onDuplicate == CRM_Import_Parser
::DUPLICATE_UPDATE
&&
317 (!empty($paramValues['contribution_id']) ||
!empty($values['trxn_id']) ||
!empty($paramValues['invoice_id']))
319 $paramValues['contact_type'] = $this->_contactType
;
321 elseif (!empty($params['soft_credit'])) {
322 $paramValues['contact_type'] = $this->_contactType
;
324 elseif (!empty($paramValues['pledge_payment'])) {
325 $paramValues['contact_type'] = $this->_contactType
;
328 //need to pass $onDuplicate to check import mode.
329 if (!empty($paramValues['pledge_payment'])) {
330 $paramValues['onDuplicate'] = $onDuplicate;
332 require_once 'CRM/Utils/DeprecatedUtils.php';
333 $formatError = _civicrm_api3_deprecated_formatted_param($paramValues, $formatted, TRUE, $onDuplicate);
336 array_unshift($values, $formatError['error_message']);
337 if (CRM_Utils_Array
::value('error_data', $formatError) == 'soft_credit') {
338 return CRM_Contribute_Import_Parser
::SOFT_CREDIT_ERROR
;
340 elseif (CRM_Utils_Array
::value('error_data', $formatError) == 'pledge_payment') {
341 return CRM_Contribute_Import_Parser
::PLEDGE_PAYMENT_ERROR
;
343 return CRM_Import_Parser
::ERROR
;
346 if ($onDuplicate != CRM_Import_Parser
::DUPLICATE_UPDATE
) {
347 $formatted['custom'] = CRM_Core_BAO_CustomField
::postProcess($formatted,
348 CRM_Core_DAO
::$_nullObject,
354 //fix for CRM-2219 - Update Contribution
355 // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE
356 if (!empty($paramValues['invoice_id']) ||
!empty($paramValues['trxn_id']) ||
!empty($paramValues['contribution_id'])) {
358 'id' => CRM_Utils_Array
::value('contribution_id', $paramValues),
359 'trxn_id' => CRM_Utils_Array
::value('trxn_id', $paramValues),
360 'invoice_id' => CRM_Utils_Array
::value('invoice_id', $paramValues),
363 $ids['contribution'] = CRM_Contribute_BAO_Contribution
::checkDuplicateIds($dupeIds);
365 if ($ids['contribution']) {
366 $formatted['id'] = $ids['contribution'];
367 $formatted['custom'] = CRM_Core_BAO_CustomField
::postProcess($formatted,
368 CRM_Core_DAO
::$_nullObject,
373 if (!empty($paramValues['note'])) {
375 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'contact_id');
376 $daoNote = new CRM_Core_BAO_Note();
377 $daoNote->entity_table
= 'civicrm_contribution';
378 $daoNote->entity_id
= $ids['contribution'];
379 if ($daoNote->find(TRUE)) {
380 $noteID['id'] = $daoNote->id
;
384 'entity_table' => 'civicrm_contribution',
385 'note' => $paramValues['note'],
386 'entity_id' => $ids['contribution'],
387 'contact_id' => $contactID,
389 CRM_Core_BAO_Note
::add($noteParams, $noteID);
390 unset($formatted['note']);
393 //need to check existing soft credit contribution, CRM-3968
394 if (!empty($formatted['soft_credit'])) {
395 $dupeSoftCredit = array(
396 'contact_id' => $formatted['soft_credit'],
397 'contribution_id' => $ids['contribution'],
400 //Delete all existing soft Contribution from contribution_soft table for pcp_id is_null
401 $existingSoftCredit = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($dupeSoftCredit['contribution_id']);
402 if(isset($existingSoftCredit['soft_credit']) && !empty($existingSoftCredit['soft_credit'])){
403 foreach($existingSoftCredit['soft_credit'] as $key => $existingSoftCreditValues){
404 if (!empty($existingSoftCreditValues['soft_credit_id'])) {
405 $deleteParams = array(
406 'id' => $existingSoftCreditValues['soft_credit_id'],
409 CRM_Contribute_BAO_ContributionSoft
::del($deleteParams);
415 $newContribution = CRM_Contribute_BAO_Contribution
::create($formatted, $ids);
416 $this->_newContributions
[] = $newContribution->id
;
418 //return soft valid since we need to show how soft credits were added
419 if (!empty($formatted['soft_credit'])) {
420 return CRM_Contribute_Import_Parser
::SOFT_CREDIT
;
423 // process pledge payment assoc w/ the contribution
424 return self
::processPledgePayments($formatted);
426 return CRM_Import_Parser
::VALID
;
430 'id' => 'Contribution ID',
431 'trxn_id' => 'Transaction ID',
432 'invoice_id' => 'Invoice ID',
434 foreach ($dupeIds as $k => $v) {
436 $errorMsg[] = "$labels[$k] $v";
439 $errorMsg = implode(' AND ', $errorMsg);
440 array_unshift($values, 'Matching Contribution record not found for ' . $errorMsg . '. Row was skipped.');
441 return CRM_Import_Parser
::ERROR
;
446 if ($this->_contactIdIndex
< 0) {
447 // set the contact type if its not set
448 if (!isset($paramValues['contact_type'])) {
449 $paramValues['contact_type'] = $this->_contactType
;
452 $paramValues['version'] = 3;
453 //retrieve contact id using contact dedupe rule
454 require_once 'CRM/Utils/DeprecatedUtils.php';
455 $error = _civicrm_api3_deprecated_check_contact_dedupe($paramValues);
457 if (CRM_Core_Error
::isAPIError($error, CRM_Core_ERROR
::DUPLICATE_CONTACT
)) {
458 $matchedIDs = explode(',', $error['error_message']['params'][0]);
459 if (count($matchedIDs) > 1) {
460 array_unshift($values, 'Multiple matching contact records detected for this row. The contribution was not imported');
461 return CRM_Import_Parser
::ERROR
;
464 $cid = $matchedIDs[0];
465 $formatted['contact_id'] = $cid;
467 $newContribution = civicrm_api('contribution', 'create', $formatted);
468 if (civicrm_error($newContribution)) {
469 if (is_array($newContribution['error_message'])) {
470 array_unshift($values, $newContribution['error_message']['message']);
471 if ($newContribution['error_message']['params'][0]) {
472 return CRM_Import_Parser
::DUPLICATE
;
476 array_unshift($values, $newContribution['error_message']);
477 return CRM_Import_Parser
::ERROR
;
481 $this->_newContributions
[] = $newContribution['id'];
482 $formatted['contribution_id'] = $newContribution['id'];
484 //return soft valid since we need to show how soft credits were added
485 if (!empty($formatted['soft_credit'])) {
486 return CRM_Contribute_Import_Parser
::SOFT_CREDIT
;
489 // process pledge payment assoc w/ the contribution
490 return self
::processPledgePayments($formatted);
492 return CRM_Import_Parser
::VALID
;
496 // Using new Dedupe rule.
498 'contact_type' => $this->_contactType
,
499 'used' => 'Unsupervised',
501 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
503 foreach ($fieldsArray as $value) {
504 if (array_key_exists(trim($value), $params)) {
505 $paramValue = $params[trim($value)];
506 if (is_array($paramValue)) {
507 $disp .= $params[trim($value)][0][trim($value)] . " ";
510 $disp .= $params[trim($value)] . " ";
515 if (!empty($params['external_identifier'])) {
517 $disp .= "AND {$params['external_identifier']}";
520 $disp = $params['external_identifier'];
524 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
525 return CRM_Import_Parser
::ERROR
;
529 if (!empty($paramValues['external_identifier'])) {
530 $checkCid = new CRM_Contact_DAO_Contact();
531 $checkCid->external_identifier
= $paramValues['external_identifier'];
532 $checkCid->find(TRUE);
533 if ($checkCid->id
!= $formatted['contact_id']) {
534 array_unshift($values, 'Mismatch of External identifier :' . $paramValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
535 return CRM_Import_Parser
::ERROR
;
538 $newContribution = civicrm_api('contribution', 'create', $formatted);
539 if (civicrm_error($newContribution)) {
540 if (is_array($newContribution['error_message'])) {
541 array_unshift($values, $newContribution['error_message']['message']);
542 if ($newContribution['error_message']['params'][0]) {
543 return CRM_Import_Parser
::DUPLICATE
;
547 array_unshift($values, $newContribution['error_message']);
548 return CRM_Import_Parser
::ERROR
;
552 $this->_newContributions
[] = $newContribution['id'];
553 $formatted['contribution_id'] = $newContribution['id'];
555 //return soft valid since we need to show how soft credits were added
556 if (!empty($formatted['soft_credit'])) {
557 return CRM_Contribute_Import_Parser
::SOFT_CREDIT
;
560 // process pledge payment assoc w/ the contribution
561 return self
::processPledgePayments($formatted);
563 return CRM_Import_Parser
::VALID
;
568 * process pledge payments
570 function processPledgePayments(&$formatted) {
571 if (!empty($formatted['pledge_payment_id']) && !empty($formatted['pledge_id'])) {
572 //get completed status
573 $completeStatusID = CRM_Core_OptionGroup
::getValue('contribution_status', 'Completed', 'name');
575 //need to update payment record to map contribution_id
576 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $formatted['pledge_payment_id'],
577 'contribution_id', $formatted['contribution_id']
580 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($formatted['pledge_id'],
581 array($formatted['pledge_payment_id']),
584 $formatted['total_amount']
587 return CRM_Contribute_Import_Parser
::PLEDGE_PAYMENT
;
592 * Get the array of successfully imported contribution id's
597 function &getImportedContributions() {
598 return $this->_newContributions
;
602 * the initializer code, called before the processing