3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
18 use Civi\Api4\Contact
;
22 * Class to parse contribution csv files.
24 class CRM_Contribute_Import_Parser_Contribution
extends CRM_Import_Parser
{
26 protected $_mapperKeys;
29 * Array of successfully imported contribution id's
33 protected $_newContributions;
40 public function __construct($mapperKeys = []) {
41 parent
::__construct();
42 $this->_mapperKeys
= $mapperKeys;
46 * Contribution-specific result codes
47 * @see CRM_Import_Parser result code constants
49 const SOFT_CREDIT
= 512, SOFT_CREDIT_ERROR
= 1024, PLEDGE_PAYMENT
= 2048, PLEDGE_PAYMENT_ERROR
= 4096;
63 * Separator being used
66 protected $_separator;
69 * Total number of lines in file
72 protected $_lineCount;
75 * Running total number of valid soft credit rows
78 protected $_validSoftCreditRowCount;
81 * Running total number of invalid soft credit rows
84 protected $_invalidSoftCreditRowCount;
87 * Running total number of valid pledge payment rows
90 protected $_validPledgePaymentRowCount;
93 * Running total number of invalid pledge payment rows
96 protected $_invalidPledgePaymentRowCount;
99 * Array of pledge payment error lines, bounded by MAX_ERROR
102 protected $_pledgePaymentErrors;
105 * Array of pledge payment error lines, bounded by MAX_ERROR
108 protected $_softCreditErrors;
111 * Filename of pledge payment error data
115 protected $_pledgePaymentErrorsFileName;
118 * Filename of soft credit error data
122 protected $_softCreditErrorsFileName;
125 * Whether the file has a column header or not
129 protected $_haveColumnHeader;
132 * @param string $fileName
133 * @param string $separator
135 * @param bool $skipColumnHeader
137 * @param int $contactType
138 * @param int $onDuplicate
139 * @param int $statusID
140 * @param int $totalRowCount
149 $skipColumnHeader = FALSE,
150 $mode = self
::MODE_PREVIEW
,
151 $contactType = self
::CONTACT_INDIVIDUAL
,
152 $onDuplicate = self
::DUPLICATE_SKIP
,
154 $totalRowCount = NULL
156 if (!is_array($fileName)) {
157 throw new CRM_Core_Exception('Unable to determine import file');
159 $fileName = $fileName['name'];
160 // Since $this->_contactType is still being called directly do a get call
161 // here to make sure it is instantiated.
162 $this->getContactType();
166 $this->_haveColumnHeader
= $skipColumnHeader;
168 $this->_separator
= $separator;
170 $fd = fopen($fileName, "r");
175 $this->_lineCount
= $this->_validSoftCreditRowCount
= $this->_validPledgePaymentRowCount
= 0;
176 $this->_invalidRowCount
= $this->_validCount
= $this->_invalidSoftCreditRowCount
= $this->_invalidPledgePaymentRowCount
= 0;
177 $this->_totalCount
= 0;
180 $this->_warnings
= [];
181 $this->_pledgePaymentErrors
= [];
182 $this->_softCreditErrors
= [];
184 $this->progressImport($statusID);
185 $startTimestamp = $currTimestamp = $prevTimestamp = time();
188 $this->_fileSize
= number_format(filesize($fileName) / 1024.0, 2);
190 if ($mode == self
::MODE_MAPFIELD
) {
194 $this->_activeFieldCount
= count($this->_activeFields
);
200 $values = fgetcsv($fd, 8192, $separator);
205 self
::encloseScrub($values);
207 // skip column header if we're not in mapfield mode
208 if ($mode != self
::MODE_MAPFIELD
&& $skipColumnHeader) {
209 $skipColumnHeader = FALSE;
213 /* trim whitespace around the values */
216 foreach ($values as $k => $v) {
217 $values[$k] = trim($v, " \t\r\n");
220 if (CRM_Utils_System
::isNull($values)) {
224 $this->_totalCount++
;
226 if ($mode == self
::MODE_MAPFIELD
) {
227 $returnCode = CRM_Import_Parser
::VALID
;
229 // Note that import summary appears to be unused
230 elseif ($mode == self
::MODE_PREVIEW ||
$mode == self
::MODE_SUMMARY
) {
231 $returnCode = $this->summary($values);
233 elseif ($mode == self
::MODE_IMPORT
) {
234 $returnCode = $this->import($onDuplicate, $values);
235 if ($statusID && (($this->_lineCount %
50) == 0)) {
236 $prevTimestamp = $this->progressImport($statusID, FALSE, $startTimestamp, $prevTimestamp, $totalRowCount);
240 $returnCode = self
::ERROR
;
243 // note that a line could be valid but still produce a warning
244 if ($returnCode == self
::VALID
) {
245 $this->_validCount++
;
246 if ($mode == self
::MODE_MAPFIELD
) {
247 $this->_rows
[] = $values;
248 $this->_activeFieldCount
= max($this->_activeFieldCount
, count($values));
252 if ($returnCode == self
::SOFT_CREDIT
) {
253 $this->_validSoftCreditRowCount++
;
254 $this->_validCount++
;
255 if ($mode == self
::MODE_MAPFIELD
) {
256 $this->_rows
[] = $values;
257 $this->_activeFieldCount
= max($this->_activeFieldCount
, count($values));
261 if ($returnCode == self
::PLEDGE_PAYMENT
) {
262 $this->_validPledgePaymentRowCount++
;
263 $this->_validCount++
;
264 if ($mode == self
::MODE_MAPFIELD
) {
265 $this->_rows
[] = $values;
266 $this->_activeFieldCount
= max($this->_activeFieldCount
, count($values));
270 if ($returnCode == self
::ERROR
) {
271 $this->_invalidRowCount++
;
272 $recordNumber = $this->_lineCount
;
273 if ($this->_haveColumnHeader
) {
276 array_unshift($values, $recordNumber);
277 $this->_errors
[] = $values;
280 if ($returnCode == self
::PLEDGE_PAYMENT_ERROR
) {
281 $this->_invalidPledgePaymentRowCount++
;
282 $recordNumber = $this->_lineCount
;
283 if ($this->_haveColumnHeader
) {
286 array_unshift($values, $recordNumber);
287 $this->_pledgePaymentErrors
[] = $values;
290 if ($returnCode == self
::SOFT_CREDIT_ERROR
) {
291 $this->_invalidSoftCreditRowCount++
;
292 $recordNumber = $this->_lineCount
;
293 if ($this->_haveColumnHeader
) {
296 array_unshift($values, $recordNumber);
297 $this->_softCreditErrors
[] = $values;
300 if ($returnCode == self
::DUPLICATE
) {
301 $this->_duplicateCount++
;
302 $recordNumber = $this->_lineCount
;
303 if ($this->_haveColumnHeader
) {
306 array_unshift($values, $recordNumber);
307 $this->_duplicates
[] = $values;
308 if ($onDuplicate != self
::DUPLICATE_SKIP
) {
309 $this->_validCount++
;
313 // if we are done processing the maxNumber of lines, break
314 if ($this->_maxLinesToProcess
> 0 && $this->_validCount
>= $this->_maxLinesToProcess
) {
321 if ($mode == self
::MODE_PREVIEW ||
$mode == self
::MODE_IMPORT
) {
322 $customHeaders = $mapper;
324 $customfields = CRM_Core_BAO_CustomField
::getFields('Contribution');
325 foreach ($customHeaders as $key => $value) {
326 if ($id = CRM_Core_BAO_CustomField
::getKeyID($value)) {
327 $customHeaders[$key] = $customfields[$id][0];
330 if ($this->_invalidRowCount
) {
331 // removed view url for invlaid contacts
332 $headers = array_merge([
336 $this->_errorFileName
= self
::errorFileName(self
::ERROR
);
337 self
::exportCSV($this->_errorFileName
, $headers, $this->_errors
);
340 if ($this->_invalidPledgePaymentRowCount
) {
341 // removed view url for invlaid contacts
342 $headers = array_merge([
346 $this->_pledgePaymentErrorsFileName
= self
::errorFileName(self
::PLEDGE_PAYMENT_ERROR
);
347 self
::exportCSV($this->_pledgePaymentErrorsFileName
, $headers, $this->_pledgePaymentErrors
);
350 if ($this->_invalidSoftCreditRowCount
) {
351 // removed view url for invlaid contacts
352 $headers = array_merge([
356 $this->_softCreditErrorsFileName
= self
::errorFileName(self
::SOFT_CREDIT_ERROR
);
357 self
::exportCSV($this->_softCreditErrorsFileName
, $headers, $this->_softCreditErrors
);
360 if ($this->_duplicateCount
) {
361 $headers = array_merge([
363 ts('View Contribution URL'),
366 $this->_duplicateFileName
= self
::errorFileName(self
::DUPLICATE
);
367 self
::exportCSV($this->_duplicateFileName
, $headers, $this->_duplicates
);
373 * Given a list of the importable field keys that the user has selected
374 * set the active fields array to this list
376 * @param array $fieldKeys mapped array of values
378 public function setActiveFields($fieldKeys) {
379 $this->_activeFieldCount
= count($fieldKeys);
380 foreach ($fieldKeys as $key) {
381 if (empty($this->_fields
[$key])) {
382 $this->_activeFields
[] = new CRM_Contribute_Import_Field('', ts('- do not import -'));
385 $this->_activeFields
[] = clone($this->_fields
[$key]);
391 * Get the field mappings for the import.
393 * This is the same format as saved in civicrm_mapping_field except
394 * that location_type_id = 'Primary' rather than empty where relevant.
395 * Also 'im_provider_id' is mapped to the 'real' field name 'provider_id'
398 * @throws \API_Exception
400 protected function getFieldMappings(): array {
402 foreach ($this->getSubmittedValue('mapper') as $i => $mapperRow) {
403 $mappedField = $this->getMappingFieldFromMapperInput($mapperRow, 0, $i);
404 // Just for clarity since 0 is a pseudo-value
405 unset($mappedField['mapping_id']);
406 $mappedFields[] = $mappedField;
408 return $mappedFields;
412 * Transform the input parameters into the form handled by the input routine.
414 * @param array $values
415 * Input parameters as they come in from the datasource
416 * eg. ['Bob', 'Smith', 'bob@example.org', '123-456']
419 * Parameters mapped to CiviCRM fields based on the mapping. eg.
421 * 'total_amount' => '1230.99',
422 * 'financial_type_id' => 1,
423 * 'external_identifier' => 'abcd',
424 * 'soft_credit' => [3 => ['external_identifier' => '123', 'soft_credit_type_id' => 1]]
426 * @throws \API_Exception
428 public function getMappedRow(array $values): array {
430 foreach ($this->getFieldMappings() as $i => $mappedField) {
431 if (!empty($mappedField['soft_credit_match_field'])) {
432 $params['soft_credit'][$i] = ['soft_credit_type_id' => $mappedField['soft_credit_type_id'], $mappedField['soft_credit_match_field'] => $values[$i]];
435 $params[$this->getFieldMetadata($mappedField['name'])['name']] = $values[$i];
442 * @param string $name
445 * @param string $headerPattern
446 * @param string $dataPattern
448 public function addField($name, $title, $type = CRM_Utils_Type
::T_INT
, $headerPattern = '//', $dataPattern = '//') {
450 $this->_fields
['doNotImport'] = new CRM_Contribute_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
453 $tempField = CRM_Contact_BAO_Contact
::importableFields('All', NULL);
454 if (!array_key_exists($name, $tempField)) {
455 $this->_fields
[$name] = new CRM_Contribute_Import_Field($name, $title, $type, $headerPattern, $dataPattern);
458 $this->_fields
[$name] = new CRM_Contact_Import_Field($name, $title, $type, $headerPattern, $dataPattern,
459 CRM_Utils_Array
::value('hasLocationType', $tempField[$name])
466 * Store parser values.
468 * @param CRM_Core_Session $store
472 public function set($store, $mode = self
::MODE_SUMMARY
) {
473 $store->set('fileSize', $this->_fileSize
);
474 $store->set('lineCount', $this->_lineCount
);
475 $store->set('separator', $this->_separator
);
476 $store->set('fields', $this->getSelectValues());
478 $store->set('headerPatterns', $this->getHeaderPatterns());
479 $store->set('dataPatterns', $this->getDataPatterns());
480 $store->set('columnCount', $this->_activeFieldCount
);
482 $store->set('totalRowCount', $this->_totalCount
);
483 $store->set('validRowCount', $this->_validCount
);
484 $store->set('invalidRowCount', $this->_invalidRowCount
);
485 $store->set('invalidSoftCreditRowCount', $this->_invalidSoftCreditRowCount
);
486 $store->set('validSoftCreditRowCount', $this->_validSoftCreditRowCount
);
487 $store->set('invalidPledgePaymentRowCount', $this->_invalidPledgePaymentRowCount
);
488 $store->set('validPledgePaymentRowCount', $this->_validPledgePaymentRowCount
);
490 switch ($this->_contactType
) {
492 $store->set('contactType', CRM_Import_Parser
::CONTACT_INDIVIDUAL
);
496 $store->set('contactType', CRM_Import_Parser
::CONTACT_HOUSEHOLD
);
500 $store->set('contactType', CRM_Import_Parser
::CONTACT_ORGANIZATION
);
503 if ($this->_invalidRowCount
) {
504 $store->set('errorsFileName', $this->_errorFileName
);
506 if (isset($this->_rows
) && !empty($this->_rows
)) {
507 $store->set('dataValues', $this->_rows
);
510 if ($this->_invalidPledgePaymentRowCount
) {
511 $store->set('pledgePaymentErrorsFileName', $this->_pledgePaymentErrorsFileName
);
514 if ($this->_invalidSoftCreditRowCount
) {
515 $store->set('softCreditErrorsFileName', $this->_softCreditErrorsFileName
);
518 if ($mode == self
::MODE_IMPORT
) {
519 $store->set('duplicateRowCount', $this->_duplicateCount
);
520 if ($this->_duplicateCount
) {
521 $store->set('duplicatesFileName', $this->_duplicateFileName
);
527 * Export data to a CSV file.
529 * @param string $fileName
530 * @param array $header
533 public static function exportCSV($fileName, $header, $data) {
535 $fd = fopen($fileName, 'w');
537 foreach ($header as $key => $value) {
538 $header[$key] = "\"$value\"";
540 $config = CRM_Core_Config
::singleton();
541 $output[] = implode($config->fieldSeparator
, $header);
543 foreach ($data as $datum) {
544 foreach ($datum as $key => $value) {
545 if (isset($value[0]) && is_array($value)) {
546 foreach ($value[0] as $k1 => $v1) {
547 if ($k1 == 'location_type_id') {
554 $datum[$key] = "\"$value\"";
557 $output[] = implode($config->fieldSeparator
, $datum);
559 fwrite($fd, implode("\n", $output));
564 * Determines the file extension based on error code.
567 * Error code constant.
571 public static function errorFileName($type) {
577 $config = CRM_Core_Config
::singleton();
578 $fileName = $config->uploadDir
. "sqlImport";
581 case self
::SOFT_CREDIT_ERROR
:
582 $fileName .= '.softCreditErrors';
585 case self
::PLEDGE_PAYMENT_ERROR
:
586 $fileName .= '.pledgePaymentErrors';
590 $fileName = parent
::errorFileName($type);
598 * Determines the file name based on error code.
601 * Error code constant.
605 public static function saveFileName($type) {
612 case self
::SOFT_CREDIT_ERROR
:
613 $fileName = 'Import_Soft_Credit_Errors.csv';
616 case self
::PLEDGE_PAYMENT_ERROR
:
617 $fileName = 'Import_Pledge_Payment_Errors.csv';
621 $fileName = parent
::saveFileName($type);
629 * The initializer code, called before the processing
631 public function init() {
632 $this->setFieldMetadata();
633 foreach ($this->getImportableFieldsMetadata() as $name => $field) {
634 $this->addField($name, $field['title'], $field['type'], $field['headerPattern'], $field['dataPattern']);
637 $this->_newContributions
= [];
639 $this->setActiveFields($this->_mapperKeys
);
643 * Set field metadata.
645 protected function setFieldMetadata() {
646 if (empty($this->importableFieldsMetadata
)) {
647 $fields = CRM_Contribute_BAO_Contribution
::importableFields($this->_contactType
, FALSE);
649 $fields = array_merge($fields,
652 'title' => ts('Soft Credit'),
653 'softCredit' => TRUE,
654 'headerPattern' => '/Soft Credit/i',
659 // add pledge fields only if its is enabled
660 if (CRM_Core_Permission
::access('CiviPledge')) {
662 'pledge_payment' => [
663 'title' => ts('Pledge Payment'),
664 'headerPattern' => '/Pledge Payment/i',
667 'title' => ts('Pledge ID'),
668 'headerPattern' => '/Pledge ID/i',
672 $fields = array_merge($fields, $pledgeFields);
674 foreach ($fields as $name => $field) {
675 $fields[$name] = array_merge([
676 'type' => CRM_Utils_Type
::T_INT
,
677 'dataPattern' => '//',
678 'headerPattern' => '//',
681 $this->importableFieldsMetadata
= $fields;
686 * Handle the values in summary mode.
688 * @param array $values
689 * The array of values belonging to this line.
692 * CRM_Import_Parser::VALID or CRM_Import_Parser::ERROR
694 public function summary(&$values) {
695 $params = $this->getMappedRow($values);
698 $errorMessage = implode('; ', $this->formatDateFields($params));
699 //date-Format part ends
701 $params['contact_type'] = 'Contribution';
703 //checking error in custom data
704 CRM_Contact_Import_Parser_Contact
::isErrorInCustomData($params, $errorMessage);
707 $tempMsg = "Invalid value for field(s) : $errorMessage";
708 array_unshift($values, $tempMsg);
709 $errorMessage = NULL;
710 return CRM_Import_Parser
::ERROR
;
713 return CRM_Import_Parser
::VALID
;
717 * Handle the values in import mode.
719 * @param int $onDuplicate
720 * The code for what action to take on duplicates.
721 * @param array $values
722 * The array of values belonging to this line.
725 * the result of this processing - one of
726 * - CRM_Import_Parser::VALID
727 * - CRM_Import_Parser::ERROR
728 * - CRM_Import_Parser::SOFT_CREDIT_ERROR
729 * - CRM_Import_Parser::PLEDGE_PAYMENT_ERROR
730 * - CRM_Import_Parser::DUPLICATE
731 * - CRM_Import_Parser::SOFT_CREDIT (successful creation)
732 * - CRM_Import_Parser::PLEDGE_PAYMENT (successful creation)
734 public function import($onDuplicate, &$values) {
735 // first make sure this is a valid line
736 $response = $this->summary($values);
737 if ($response != CRM_Import_Parser
::VALID
) {
738 return CRM_Import_Parser
::ERROR
;
741 $params = $this->getMappedRow($values);
742 $formatted = ['version' => 3, 'skipRecentView' => TRUE, 'skipCleanMoney' => FALSE, 'contribution_id' => $params['id'] ??
NULL];
744 if (isset($params['total_amount']) && $params['total_amount'] == 0) {
745 $params['total_amount'] = '0.00';
747 $this->formatInput($params, $formatted);
750 foreach ($params as $key => $field) {
751 if ($field == NULL ||
$field === '') {
754 $paramValues[$key] = $field;
757 //import contribution record according to select contact type
758 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_SKIP
&&
759 (!empty($paramValues['contribution_contact_id']) ||
!empty($paramValues['external_identifier']))
761 $paramValues['contact_type'] = $this->_contactType
;
763 elseif ($onDuplicate == CRM_Import_Parser
::DUPLICATE_UPDATE
&&
764 (!empty($paramValues['contribution_id']) ||
!empty($values['trxn_id']) ||
!empty($paramValues['invoice_id']))
766 $paramValues['contact_type'] = $this->_contactType
;
768 elseif (!empty($paramValues['pledge_payment'])) {
769 $paramValues['contact_type'] = $this->_contactType
;
772 //need to pass $onDuplicate to check import mode.
773 if (!empty($paramValues['pledge_payment'])) {
774 $paramValues['onDuplicate'] = $onDuplicate;
777 $formatError = $this->deprecatedFormatParams($paramValues, $formatted, TRUE, $onDuplicate);
779 catch (CRM_Core_Exception
$e) {
780 array_unshift($values, $e->getMessage());
781 $errorMapping = ['soft_credit' => self
::SOFT_CREDIT_ERROR
, 'pledge_payment' => self
::PLEDGE_PAYMENT_ERROR
];
782 return $errorMapping[$e->getErrorCode()] ?? CRM_Import_Parser
::ERROR
;
786 array_unshift($values, $formatError['error_message']);
787 if (CRM_Utils_Array
::value('error_data', $formatError) == 'soft_credit') {
788 return self
::SOFT_CREDIT_ERROR
;
790 if (CRM_Utils_Array
::value('error_data', $formatError) == 'pledge_payment') {
791 return self
::PLEDGE_PAYMENT_ERROR
;
793 return CRM_Import_Parser
::ERROR
;
796 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_UPDATE
) {
797 //fix for CRM-2219 - Update Contribution
798 // onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE
799 if (!empty($paramValues['invoice_id']) ||
!empty($paramValues['trxn_id']) ||
!empty($paramValues['contribution_id'])) {
801 'id' => $paramValues['contribution_id'] ??
NULL,
802 'trxn_id' => $paramValues['trxn_id'] ??
NULL,
803 'invoice_id' => $paramValues['invoice_id'] ??
NULL,
805 $ids['contribution'] = CRM_Contribute_BAO_Contribution
::checkDuplicateIds($dupeIds);
807 if ($ids['contribution']) {
808 $formatted['id'] = $ids['contribution'];
810 if (!empty($paramValues['note'])) {
812 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Contribute_DAO_Contribution', $ids['contribution'], 'contact_id');
813 $daoNote = new CRM_Core_BAO_Note();
814 $daoNote->entity_table
= 'civicrm_contribution';
815 $daoNote->entity_id
= $ids['contribution'];
816 if ($daoNote->find(TRUE)) {
817 $noteID['id'] = $daoNote->id
;
821 'entity_table' => 'civicrm_contribution',
822 'note' => $paramValues['note'],
823 'entity_id' => $ids['contribution'],
824 'contact_id' => $contactID,
826 CRM_Core_BAO_Note
::add($noteParams, $noteID);
827 unset($formatted['note']);
830 //need to check existing soft credit contribution, CRM-3968
831 if (!empty($formatted['soft_credit'])) {
833 'contact_id' => $formatted['soft_credit'],
834 'contribution_id' => $ids['contribution'],
837 //Delete all existing soft Contribution from contribution_soft table for pcp_id is_null
838 $existingSoftCredit = CRM_Contribute_BAO_ContributionSoft
::getSoftContribution($dupeSoftCredit['contribution_id']);
839 if (isset($existingSoftCredit['soft_credit']) && !empty($existingSoftCredit['soft_credit'])) {
840 foreach ($existingSoftCredit['soft_credit'] as $key => $existingSoftCreditValues) {
841 if (!empty($existingSoftCreditValues['soft_credit_id'])) {
842 civicrm_api3('ContributionSoft', 'delete', [
843 'id' => $existingSoftCreditValues['soft_credit_id'],
851 $formatted['id'] = $ids['contribution'];
853 $newContribution = civicrm_api3('contribution', 'create', $formatted);
854 $this->_newContributions
[] = $newContribution['id'];
856 //return soft valid since we need to show how soft credits were added
857 if (!empty($formatted['soft_credit'])) {
858 return self
::SOFT_CREDIT
;
861 // process pledge payment assoc w/ the contribution
862 return $this->processPledgePayments($formatted);
865 'id' => 'Contribution ID',
866 'trxn_id' => 'Transaction ID',
867 'invoice_id' => 'Invoice ID',
869 foreach ($dupeIds as $k => $v) {
871 $errorMsg[] = "$labels[$k] $v";
874 $errorMsg = implode(' AND ', $errorMsg);
875 array_unshift($values, 'Matching Contribution record not found for ' . $errorMsg . '. Row was skipped.');
876 return CRM_Import_Parser
::ERROR
;
880 if (empty($formatted['contact_id'])) {
882 $error = $this->checkContactDuplicate($paramValues);
884 if (CRM_Core_Error
::isAPIError($error, CRM_Core_ERROR
::DUPLICATE_CONTACT
)) {
885 $matchedIDs = explode(',', $error['error_message']['params'][0]);
886 if (count($matchedIDs) > 1) {
887 array_unshift($values, 'Multiple matching contact records detected for this row. The contribution was not imported');
888 return CRM_Import_Parser
::ERROR
;
890 $cid = $matchedIDs[0];
891 $formatted['contact_id'] = $cid;
893 $newContribution = civicrm_api('contribution', 'create', $formatted);
894 if (civicrm_error($newContribution)) {
895 if (is_array($newContribution['error_message'])) {
896 array_unshift($values, $newContribution['error_message']['message']);
897 if ($newContribution['error_message']['params'][0]) {
898 return CRM_Import_Parser
::DUPLICATE
;
902 array_unshift($values, $newContribution['error_message']);
903 return CRM_Import_Parser
::ERROR
;
907 $this->_newContributions
[] = $newContribution['id'];
908 $formatted['contribution_id'] = $newContribution['id'];
910 //return soft valid since we need to show how soft credits were added
911 if (!empty($formatted['soft_credit'])) {
912 return self
::SOFT_CREDIT
;
915 // process pledge payment assoc w/ the contribution
916 return $this->processPledgePayments($formatted);
919 // Using new Dedupe rule.
921 'contact_type' => $this->_contactType
,
922 'used' => 'Unsupervised',
924 $fieldsArray = CRM_Dedupe_BAO_DedupeRule
::dedupeRuleFields($ruleParams);
926 foreach ($fieldsArray as $value) {
927 if (array_key_exists(trim($value), $params)) {
928 $paramValue = $params[trim($value)];
929 if (is_array($paramValue)) {
930 $disp .= $params[trim($value)][0][trim($value)] . " ";
933 $disp .= $params[trim($value)] . " ";
938 if (!empty($params['external_identifier'])) {
940 $disp .= "AND {$params['external_identifier']}";
943 $disp = $params['external_identifier'];
947 array_unshift($values, 'No matching Contact found for (' . $disp . ')');
948 return CRM_Import_Parser
::ERROR
;
951 if (!empty($paramValues['external_identifier'])) {
952 $checkCid = new CRM_Contact_DAO_Contact();
953 $checkCid->external_identifier
= $paramValues['external_identifier'];
954 $checkCid->find(TRUE);
955 if ($checkCid->id
!= $formatted['contact_id']) {
956 array_unshift($values, 'Mismatch of External ID:' . $paramValues['external_identifier'] . ' and Contact Id:' . $formatted['contact_id']);
957 return CRM_Import_Parser
::ERROR
;
960 $newContribution = civicrm_api('contribution', 'create', $formatted);
961 if (civicrm_error($newContribution)) {
962 if (is_array($newContribution['error_message'])) {
963 array_unshift($values, $newContribution['error_message']['message']);
964 if ($newContribution['error_message']['params'][0]) {
965 return CRM_Import_Parser
::DUPLICATE
;
969 array_unshift($values, $newContribution['error_message']);
970 return CRM_Import_Parser
::ERROR
;
974 $this->_newContributions
[] = $newContribution['id'];
975 $formatted['contribution_id'] = $newContribution['id'];
977 //return soft valid since we need to show how soft credits were added
978 if (!empty($formatted['soft_credit'])) {
979 return self
::SOFT_CREDIT
;
982 // process pledge payment assoc w/ the contribution
983 return $this->processPledgePayments($formatted);
987 * Process pledge payments.
989 * @param array $formatted
993 private function processPledgePayments(array $formatted) {
994 if (!empty($formatted['pledge_payment_id']) && !empty($formatted['pledge_id'])) {
995 //get completed status
996 $completeStatusID = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
998 //need to update payment record to map contribution_id
999 CRM_Core_DAO
::setFieldValue('CRM_Pledge_DAO_PledgePayment', $formatted['pledge_payment_id'],
1000 'contribution_id', $formatted['contribution_id']
1003 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($formatted['pledge_id'],
1004 [$formatted['pledge_payment_id']],
1007 $formatted['total_amount']
1010 return self
::PLEDGE_PAYMENT
;
1015 * Get the array of successfully imported contribution id's
1019 public function &getImportedContributions() {
1020 return $this->_newContributions
;
1024 * Format date fields from input to mysql.
1026 * @param array $params
1029 * Error messages, if any.
1031 public function formatDateFields(&$params) {
1033 $dateType = CRM_Core_Session
::singleton()->get('dateTypes');
1034 foreach ($params as $key => $val) {
1037 case 'receive_date':
1038 if ($dateValue = CRM_Utils_Date
::formatDate($params[$key], $dateType)) {
1039 $params[$key] = $dateValue;
1042 $errorMessage[] = ts('Receive Date');
1047 if ($dateValue = CRM_Utils_Date
::formatDate($params[$key], $dateType)) {
1048 $params[$key] = $dateValue;
1051 $errorMessage[] = ts('Cancel Date');
1055 case 'receipt_date':
1056 if ($dateValue = CRM_Utils_Date
::formatDate($params[$key], $dateType)) {
1057 $params[$key] = $dateValue;
1060 $errorMessage[] = ts('Receipt date');
1064 case 'thankyou_date':
1065 if ($dateValue = CRM_Utils_Date
::formatDate($params[$key], $dateType)) {
1066 $params[$key] = $dateValue;
1069 $errorMessage[] = ts('Thankyou Date');
1075 return $errorMessage;
1079 * Format input params to suit api handling.
1081 * Over time all the parts of deprecatedFormatParams
1082 * and all the parts of the import function on this class that relate to
1083 * reformatting input should be moved here and tests should be added in
1084 * CRM_Contribute_Import_Parser_ContributionTest.
1086 * @param array $params
1087 * @param array $formatted
1089 public function formatInput(&$params, &$formatted = []) {
1090 $dateType = CRM_Core_Session
::singleton()->get('dateTypes');
1091 $customDataType = !empty($params['contact_type']) ?
$params['contact_type'] : 'Contribution';
1092 $customFields = CRM_Core_BAO_CustomField
::getFields($customDataType);
1093 // @todo call formatDateFields & move custom data handling there.
1094 // Also note error handling for dates is currently in deprecatedFormatParams
1095 // we should use the error handling in formatDateFields.
1096 foreach ($params as $key => $val) {
1097 // @todo - call formatDateFields instead.
1100 case 'receive_date':
1102 case 'receipt_date':
1103 case 'thankyou_date':
1104 $params[$key] = CRM_Utils_Date
::formatDate($params[$key], $dateType);
1107 case 'pledge_payment':
1108 $params[$key] = CRM_Utils_String
::strtobool($val);
1112 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) {
1113 if ($customFields[$customFieldID]['data_type'] == 'Date') {
1114 CRM_Contact_Import_Parser_Contact
::formatCustomDate($params, $formatted, $dateType, $key);
1115 unset($params[$key]);
1117 elseif ($customFields[$customFieldID]['data_type'] == 'Boolean') {
1118 $params[$key] = CRM_Utils_String
::strtoboolstr($val);
1126 * take the input parameter list as specified in the data model and
1127 * convert it into the same format that we use in QF and BAO object
1129 * @param array $params
1130 * Associative array of property name/value
1131 * pairs to insert in new contact.
1132 * @param array $values
1133 * The reformatted properties that we can use internally.
1134 * @param bool $create
1135 * @param int $onDuplicate
1137 * @return array|CRM_Error
1138 * @throws \CRM_Core_Exception
1140 private function deprecatedFormatParams($params, &$values, $create = FALSE, $onDuplicate = NULL) {
1141 require_once 'CRM/Utils/DeprecatedUtils.php';
1142 // copy all the contribution fields as is
1143 require_once 'api/v3/utils.php';
1144 $fields = CRM_Core_DAO
::getExportableFieldsWithPseudoConstants('CRM_Contribute_BAO_Contribution');
1146 _civicrm_api3_store_values($fields, $params, $values);
1148 $customFields = CRM_Core_BAO_CustomField
::getFields('Contribution', FALSE, FALSE, NULL, NULL, FALSE, FALSE, FALSE);
1150 foreach ($params as $key => $value) {
1151 // ignore empty values or empty arrays etc
1152 if (CRM_Utils_System
::isNull($value)) {
1156 // Handling Custom Data
1157 if ($customFieldID = CRM_Core_BAO_CustomField
::getKeyID($key)) {
1158 $values[$key] = $value;
1159 $type = $customFields[$customFieldID]['html_type'];
1160 if (CRM_Core_BAO_CustomField
::isSerialized($customFields[$customFieldID])) {
1161 $values[$key] = self
::unserializeCustomValue($customFieldID, $value, $type);
1163 elseif ($type == 'Select' ||
$type == 'Radio' ||
1164 ($type == 'Autocomplete-Select' &&
1165 $customFields[$customFieldID]['data_type'] == 'String'
1168 $customOption = CRM_Core_BAO_CustomOption
::getCustomOption($customFieldID, TRUE);
1169 foreach ($customOption as $customFldID => $customValue) {
1170 $val = $customValue['value'] ??
NULL;
1171 $label = $customValue['label'] ??
NULL;
1172 $label = strtolower($label);
1173 $value = strtolower(trim($value));
1174 if (($value == $label) ||
($value == strtolower($val))) {
1175 $values[$key] = $val;
1184 if (!CRM_Utils_Rule
::integer($value)) {
1185 return civicrm_api3_create_error("contact_id not valid: $value");
1187 $dao = new CRM_Core_DAO();
1189 $svq = $dao->singleValueQuery("SELECT is_deleted FROM civicrm_contact WHERE id = $value",
1193 return civicrm_api3_create_error("Invalid Contact ID: There is no contact record with contact_id = $value.");
1195 elseif ($svq == 1) {
1196 return civicrm_api3_create_error("Invalid Contact ID: contact_id $value is a soft-deleted contact.");
1198 $values['contact_id'] = $value;
1201 case 'contact_type':
1202 // import contribution record according to select contact type
1203 require_once 'CRM/Contact/DAO/Contact.php';
1204 $contactType = new CRM_Contact_DAO_Contact();
1205 $contactId = $params['contribution_contact_id'] ??
NULL;
1206 $externalId = $params['external_identifier'] ??
NULL;
1207 $email = $params['email'] ??
NULL;
1208 //when insert mode check contact id or external identifier
1209 if ($contactId ||
$externalId) {
1210 $contactType->id
= $contactId;
1211 $contactType->external_identifier
= $externalId;
1212 if ($contactType->find(TRUE)) {
1213 if ($params['contact_type'] != $contactType->contact_type
) {
1214 return civicrm_api3_create_error("Contact Type is wrong: $contactType->contact_type");
1219 if (!CRM_Utils_Rule
::email($email)) {
1220 return civicrm_api3_create_error("Invalid email address $email provided. Row was skipped");
1223 // get the contact id from duplicate contact rule, if more than one contact is returned
1224 // we should return error, since current interface allows only one-one mapping
1227 'contact_type' => $params['contact_type'],
1229 $checkDedupe = _civicrm_api3_deprecated_duplicate_formatted_contact($emailParams);
1230 if (!$checkDedupe['is_error']) {
1231 return civicrm_api3_create_error("Invalid email address(doesn't exist) $email. Row was skipped");
1233 $matchingContactIds = explode(',', $checkDedupe['error_message']['params'][0]);
1234 if (count($matchingContactIds) > 1) {
1235 return civicrm_api3_create_error("Invalid email address(duplicate) $email. Row was skipped");
1237 if (count($matchingContactIds) == 1) {
1238 $params['contribution_contact_id'] = $matchingContactIds[0];
1241 elseif (!empty($params['contribution_id']) ||
!empty($params['trxn_id']) ||
!empty($params['invoice_id'])) {
1242 // when update mode check contribution id or trxn id or
1244 $contactId = new CRM_Contribute_DAO_Contribution();
1245 if (!empty($params['contribution_id'])) {
1246 $contactId->id
= $params['contribution_id'];
1248 elseif (!empty($params['trxn_id'])) {
1249 $contactId->trxn_id
= $params['trxn_id'];
1251 elseif (!empty($params['invoice_id'])) {
1252 $contactId->invoice_id
= $params['invoice_id'];
1254 if ($contactId->find(TRUE)) {
1255 $contactType->id
= $contactId->contact_id
;
1256 if ($contactType->find(TRUE)) {
1257 if ($params['contact_type'] != $contactType->contact_type
) {
1258 return civicrm_api3_create_error("Contact Type is wrong: $contactType->contact_type");
1264 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_UPDATE
) {
1265 return civicrm_api3_create_error("Empty Contribution and Invoice and Transaction ID. Row was skipped.");
1270 case 'receive_date':
1272 case 'receipt_date':
1273 case 'thankyou_date':
1274 if (!CRM_Utils_Rule
::dateTime($value)) {
1275 return civicrm_api3_create_error("$key not a valid date: $value");
1279 case 'non_deductible_amount':
1280 case 'total_amount':
1283 // @todo add test like testPaymentTypeLabel & remove these lines as we can anticipate error will still be caught & handled.
1284 if (!CRM_Utils_Rule
::money($value)) {
1285 return civicrm_api3_create_error("$key not a valid amount: $value");
1290 if (!CRM_Utils_Rule
::currencyCode($value)) {
1291 return civicrm_api3_create_error("currency not a valid code: $value");
1296 // import contribution record according to select contact type
1297 // validate contact id and external identifier.
1298 foreach ($value as $softKey => $softParam) {
1299 $values['soft_credit'][$softKey] = [
1300 'contact_id' => $this->lookupMatchingContact($softParam),
1301 'soft_credit_type_id' => $softParam['soft_credit_type_id'],
1306 case 'pledge_payment':
1309 // giving respect to pledge_payment flag.
1310 if (empty($params['pledge_payment'])) {
1314 // get total amount of from import fields
1315 $totalAmount = $params['total_amount'] ??
NULL;
1317 $onDuplicate = $params['onDuplicate'] ??
NULL;
1319 // we need to get contact id $contributionContactID to
1320 // retrieve pledge details as well as to validate pledge ID
1322 // first need to check for update mode
1323 if ($onDuplicate == CRM_Import_Parser
::DUPLICATE_UPDATE
&&
1324 ($params['contribution_id'] ||
$params['trxn_id'] ||
$params['invoice_id'])
1326 $contribution = new CRM_Contribute_DAO_Contribution();
1327 if ($params['contribution_id']) {
1328 $contribution->id
= $params['contribution_id'];
1330 elseif ($params['trxn_id']) {
1331 $contribution->trxn_id
= $params['trxn_id'];
1333 elseif ($params['invoice_id']) {
1334 $contribution->invoice_id
= $params['invoice_id'];
1337 if ($contribution->find(TRUE)) {
1338 $contributionContactID = $contribution->contact_id
;
1339 if (!$totalAmount) {
1340 $totalAmount = $contribution->total_amount
;
1344 return civicrm_api3_create_error('No match found for specified contact in pledge payment data. Row was skipped.');
1348 // first get the contact id for given contribution record.
1349 if (!empty($params['contribution_contact_id'])) {
1350 $contributionContactID = $params['contribution_contact_id'];
1352 elseif (!empty($params['external_identifier'])) {
1353 require_once 'CRM/Contact/DAO/Contact.php';
1354 $contact = new CRM_Contact_DAO_Contact();
1355 $contact->external_identifier
= $params['external_identifier'];
1356 if ($contact->find(TRUE)) {
1357 $contributionContactID = $params['contribution_contact_id'] = $values['contribution_contact_id'] = $contact->id
;
1360 return civicrm_api3_create_error('No match found for specified contact in pledge payment data. Row was skipped.');
1364 // we need to get contribution contact using de dupe
1365 $error = $this->checkContactDuplicate($params);
1367 if (isset($error['error_message']['params'][0])) {
1368 $matchedIDs = explode(',', $error['error_message']['params'][0]);
1370 // check if only one contact is found
1371 if (count($matchedIDs) > 1) {
1372 return civicrm_api3_create_error($error['error_message']['message']);
1374 $contributionContactID = $params['contribution_contact_id'] = $values['contribution_contact_id'] = $matchedIDs[0];
1377 return civicrm_api3_create_error('No match found for specified contact in contribution data. Row was skipped.');
1382 if (!empty($params['pledge_id'])) {
1383 if (CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge', $params['pledge_id'], 'contact_id') != $contributionContactID) {
1384 return civicrm_api3_create_error('Invalid Pledge ID provided. Contribution row was skipped.');
1386 $values['pledge_id'] = $params['pledge_id'];
1389 // check if there are any pledge related to this contact, with payments pending or in progress
1390 require_once 'CRM/Pledge/BAO/Pledge.php';
1391 $pledgeDetails = CRM_Pledge_BAO_Pledge
::getContactPledges($contributionContactID);
1393 if (empty($pledgeDetails)) {
1394 return civicrm_api3_create_error('No open pledges found for this contact. Contribution row was skipped.');
1396 if (count($pledgeDetails) > 1) {
1397 return civicrm_api3_create_error('This contact has more than one open pledge. Unable to determine which pledge to apply the contribution to. Contribution row was skipped.');
1400 // this mean we have only one pending / in progress pledge
1401 $values['pledge_id'] = $pledgeDetails[0];
1404 // we need to check if oldest payment amount equal to contribution amount
1405 require_once 'CRM/Pledge/BAO/PledgePayment.php';
1406 $pledgePaymentDetails = CRM_Pledge_BAO_PledgePayment
::getOldestPledgePayment($values['pledge_id']);
1408 if ($pledgePaymentDetails['amount'] == $totalAmount) {
1409 $values['pledge_payment_id'] = $pledgePaymentDetails['id'];
1412 return civicrm_api3_create_error('Contribution and Pledge Payment amount mismatch for this record. Contribution row was skipped.');
1416 case 'contribution_campaign_id':
1417 if (empty(CRM_Core_DAO
::getFieldValue('CRM_Campaign_DAO_Campaign', $params['contribution_campaign_id']))) {
1418 return civicrm_api3_create_error('Invalid Campaign ID provided. Contribution row was skipped.');
1420 $values['contribution_campaign_id'] = $params['contribution_campaign_id'];
1424 // Hande name or label for fields with options.
1425 if (isset($fields[$key]) &&
1426 // Yay - just for a surprise we are inconsistent on whether we pass the pseudofield (payment_instrument)
1427 // or the field name (contribution_status_id)
1428 // @todo - payment_instrument is goneburger - now payment_instrument_id - how
1430 (!empty($fields[$key]['is_pseudofield_for']) ||
!empty($fields[$key]['pseudoconstant']))
1432 $realField = $fields[$key]['is_pseudofield_for'] ??
$key;
1433 $realFieldSpec = $fields[$realField];
1434 $values[$key] = $this->parsePseudoConstantField($value, $realFieldSpec);
1440 if (array_key_exists('note', $params)) {
1441 $values['note'] = $params['note'];
1445 // CRM_Contribute_BAO_Contribution::add() handles contribution_source
1446 // So, if $values contains contribution_source, convert it to source
1447 $changes = ['contribution_source' => 'source'];
1449 foreach ($changes as $orgVal => $changeVal) {
1450 if (isset($values[$orgVal])) {
1451 $values[$changeVal] = $values[$orgVal];
1452 unset($values[$orgVal]);
1461 * Get the civicrm_mapping_field appropriate layout for the mapper input.
1463 * The input looks something like ['street_address', 1]
1464 * and would be mapped to ['name' => 'street_address', 'location_type_id' =>
1467 * @param array $fieldMapping
1468 * @param int $mappingID
1469 * @param int $columnNumber
1472 * @throws \API_Exception
1474 public function getMappingFieldFromMapperInput(array $fieldMapping, int $mappingID, int $columnNumber): array {
1476 'name' => $fieldMapping[0],
1477 'mapping_id' => $mappingID,
1478 'column_number' => $columnNumber,
1479 // The name of the field to match the soft credit on is (crazily)
1480 // stored in 'contact_type'
1481 'contact_type' => $fieldMapping[1] ??
NULL,
1482 // We also store the field in a sensible key, even if it isn't saved sensibly.
1483 'soft_credit_match_field' => $fieldMapping[1] ??
NULL,
1484 // This field is actually not saved at all :-( It is lost each time.
1485 'soft_credit_type_id' => $fieldMapping[2] ??
NULL,
1490 * Lookup matching contact.
1492 * This looks up the matching contact from the contact id, external identifier
1493 * or email. For the email a straight email search is done - this is equivalent
1494 * to what happens on a dedupe rule lookup when the only field is 'email' - but
1495 * we can't be sure the rule is 'just email' - and we are not collecting the
1496 * fields for any other lookup in the case of soft credits (if we
1497 * extend this function to main-contact-lookup we can handle full dedupe
1498 * lookups - but note the error messages will need tweaking.
1500 * @param array $params
1505 * @throws \API_Exception
1506 * @throws \CRM_Core_Exception
1508 private function lookupMatchingContact(array $params): int {
1509 $lookupField = !empty($params['contact_id']) ?
'contact_id' : (!empty($params['external_identifier']) ?
'external_identifier' : 'email');
1510 if (empty($params['email'])) {
1511 $contact = Contact
::get(FALSE)->addSelect('id')
1512 ->addWhere($lookupField, '=', $params[$lookupField])
1514 if (count($contact) !== 1) {
1515 throw new CRM_Core_Exception(ts("Soft Credit %1 - %2 doesn't exist. Row was skipped.",
1517 1 => $this->getFieldMetadata($lookupField),
1518 2 => $params['contact_id'] ??
$params['external_identifier'],
1521 return $contact->first()['id'];
1524 if (!CRM_Utils_Rule
::email($params['email'])) {
1525 throw new CRM_Core_Exception(ts('Invalid email address %1 provided for Soft Credit. Row was skipped'), [1 => $params['email']]);
1527 $emails = Email
::get(FALSE)
1528 ->addWhere('contact_id.is_deleted', '=', 0)
1529 ->addWhere('contact_id.contact_type', '=', $this->getContactType())
1530 ->addWhere('email', '=', $params['email'])
1531 ->addSelect('contact_id')->execute();
1532 if (count($emails) === 0) {
1533 throw new CRM_Core_Exception(ts("Invalid email address(doesn't exist) %1 for Soft Credit. Row was skipped", [1 => $params['email']]));
1535 if (count($emails) > 1) {
1536 throw new CRM_Core_Exception(ts('Invalid email address(duplicate) %1 for Soft Credit. Row was skipped', [1 => $params['email']]));
1538 return $emails->first()['contact_id'];
1542 * @param array $mappedField
1543 * Field detail as would be saved in field_mapping table
1544 * or as returned from getMappingFieldFromMapperInput
1547 * @throws \API_Exception
1549 public function getMappedFieldLabel(array $mappedField): string {
1550 if (empty($this->importableFieldsMetadata
)) {
1551 $this->setFieldMetadata();
1554 $title[] = $this->getFieldMetadata($mappedField['name'])['title'];
1555 if ($mappedField['soft_credit_match_field']) {
1556 $title[] = $this->getFieldMetadata($mappedField['soft_credit_match_field'])['title'];
1558 if ($mappedField['soft_credit_type_id']) {
1559 $title[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', $mappedField['soft_credit_type_id']);
1562 return implode(' - ', $title);