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
19 * This class gets the name of the file to upload.
21 class CRM_Contribute_Import_Form_MapField
extends CRM_Import_Form_MapField
{
24 * Check if required fields are present.
26 * @param CRM_Contribute_Import_Form_MapField $self
27 * @param string $contactORContributionId
28 * @param array $importKeys
29 * @param array $errors
30 * @param int $weightSum
31 * @param int $threshold
32 * @param string $fieldMessage
36 protected static function checkRequiredFields($self, string $contactORContributionId, array $importKeys, array $errors, int $weightSum, $threshold, string $fieldMessage): array {
37 // FIXME: should use the schema titles, not redeclare them
39 $contactORContributionId == 'contribution_id' ?
'contribution_id' : 'contribution_contact_id' => $contactORContributionId == 'contribution_id' ?
ts('Contribution ID') : ts('Contact ID'),
40 'total_amount' => ts('Total Amount'),
41 'financial_type_id' => ts('Financial Type'),
44 foreach ($requiredFields as $field => $title) {
45 if (!in_array($field, $importKeys)) {
46 if (empty($errors['_qf_default'])) {
47 $errors['_qf_default'] = '';
49 if ($field == $contactORContributionId) {
50 if (!($weightSum >= $threshold ||
in_array('external_identifier', $importKeys)) &&
51 $self->_onDuplicate
!= CRM_Import_Parser
::DUPLICATE_UPDATE
53 $errors['_qf_default'] .= ts('Missing required contact matching fields.') . " $fieldMessage " . ts('(Sum of all weights should be greater than or equal to threshold: %1).', [1 => $threshold]) . '<br />';
55 elseif ($self->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_UPDATE
&&
56 !(in_array('invoice_id', $importKeys) ||
in_array('trxn_id', $importKeys) ||
57 in_array('contribution_id', $importKeys)
60 $errors['_qf_default'] .= ts('Invoice ID or Transaction ID or Contribution ID are required to match to the existing contribution records in Update mode.') . '<br />';
64 $errors['_qf_default'] .= ts('Missing required field: %1', [1 => $title]) . '<br />';
72 * Set variables up before form is built.
74 public function preProcess() {
75 $this->_mapperFields
= $this->getAvailableFields();
76 asort($this->_mapperFields
);
78 $this->_columnCount
= $this->get('columnCount');
79 $this->assign('columnCount', $this->_columnCount
);
80 $this->_dataValues
= $this->get('dataValues');
81 $this->assign('dataValues', $this->_dataValues
);
83 $skipColumnHeader = $this->controller
->exportValue('DataSource', 'skipColumnHeader');
84 $this->_onDuplicate
= $this->get('onDuplicate', $onDuplicate ??
"");
86 if ($skipColumnHeader) {
87 $this->assign('skipColumnHeader', $skipColumnHeader);
88 $this->assign('rowDisplayCount', 3);
89 // If we had a column header to skip, stash it for later
91 $this->_columnHeaders
= $this->_dataValues
[0];
94 $this->assign('rowDisplayCount', 2);
96 $highlightedFields = ['financial_type_id', 'total_amount'];
97 //CRM-2219 removing other required fields since for updation only
98 //invoice id or trxn id or contribution id is required.
99 if ($this->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_UPDATE
) {
101 'contribution_contact_id',
105 'external_identifier',
107 foreach ($remove as $value) {
108 unset($this->_mapperFields
[$value]);
111 //modify field title only for update mode. CRM-3245
117 $this->_mapperFields
[$key] .= ' (match to contribution record)';
118 $highlightedFields[] = $key;
121 elseif ($this->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_SKIP
) {
122 unset($this->_mapperFields
['contribution_id']);
123 $highlightedFieldsArray = [
124 'contribution_contact_id',
128 'external_identifier',
130 foreach ($highlightedFieldsArray as $name) {
131 $highlightedFields[] = $name;
135 // modify field title for contribution status
136 $this->_mapperFields
['contribution_status_id'] = ts('Contribution Status');
138 $this->assign('highlightedFields', $highlightedFields);
142 * Build the form object.
144 * @throws \CiviCRM_API3_Exception
146 public function buildQuickForm() {
147 $savedMappingID = $this->getSubmittedValue('savedMapping');
149 $this->buildSavedMappingFields($savedMappingID);
152 'CRM_Contribute_Import_Form_MapField',
156 //-------- end of saved mapping stuff ---------
159 $mapperKeys = array_keys($this->_mapperFields
);
160 $hasHeaders = !empty($this->_columnHeaders
);
161 $headerPatterns = $this->get('headerPatterns');
162 $dataPatterns = $this->get('dataPatterns');
163 $mapperKeysValues = $this->controller
->exportValue($this->_name
, 'mapper');
165 /* Initialize all field usages to false */
166 foreach ($mapperKeys as $key) {
167 $this->_fieldUsed
[$key] = FALSE;
169 $sel1 = $this->_mapperFields
;
171 if (!$this->get('onDuplicate')) {
173 unset($sel1['contribution_id']);
176 $softCreditFields['contact_id'] = ts('Contact ID');
177 $softCreditFields['external_identifier'] = ts('External ID');
178 $softCreditFields['email'] = ts('Email');
180 $sel2['soft_credit'] = $softCreditFields;
181 $sel3['soft_credit']['contact_id'] = $sel3['soft_credit']['external_identifier'] = $sel3['soft_credit']['email'] = CRM_Core_OptionGroup
::values('soft_credit_type');
184 // end of soft credit section
185 $js = "<script type='text/javascript'>\n";
186 $formName = 'document.forms.' . $this->_name
;
188 //used to warn for mismatch column count or mismatch mapping
191 for ($i = 0; $i < $this->_columnCount
; $i++
) {
192 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
194 if ($this->get('savedMapping')) {
195 list($mappingName, $mappingContactType) = CRM_Core_BAO_Mapping
::getMappingFields($savedMappingID);
197 $mappingName = $mappingName[1];
198 $mappingContactType = $mappingContactType[1];
199 if (isset($mappingName[$i])) {
200 if ($mappingName[$i] != ts('do_not_import')) {
201 $softField = $mappingContactType[$i] ??
'';
204 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
207 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
208 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
209 $defaults["mapper[$i]"] = [
212 // Since the soft credit type id is not stored we can't load it here.
218 $defaults["mapper[$i]"] = [];
221 for ($k = 1; $k < 4; $k++
) {
222 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
227 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
228 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
231 $defaults["mapper[$i]"] = [$this->defaultFromHeader($this->_columnHeaders
[$i], $headerPatterns)];
234 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i)];
237 //end of load mapping
240 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
242 // do array search first to see if has mapped key
243 $columnKey = array_search($this->_columnHeaders
[$i], $this->_mapperFields
);
244 if (isset($this->_fieldUsed
[$columnKey])) {
245 $defaults["mapper[$i]"] = $columnKey;
246 $this->_fieldUsed
[$key] = TRUE;
249 // Infer the default from the column names if we have them
250 $defaults["mapper[$i]"] = [
251 $this->defaultFromHeader($this->_columnHeaders
[$i], $headerPatterns),
257 // Otherwise guess the default from the form of the data
258 $defaults["mapper[$i]"] = [
259 $this->defaultFromData($dataPatterns, $i),
263 if (!empty($mapperKeysValues) && $mapperKeysValues[$i][0] == 'soft_credit') {
264 $js .= "cj('#mapper_" . $i . "_1').val($mapperKeysValues[$i][1]);\n";
265 $js .= "cj('#mapper_" . $i . "_2').val($mapperKeysValues[$i][2]);\n";
268 $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
270 $js .= "</script>\n";
271 $this->assign('initHideBoxes', $js);
273 //set warning if mismatch in more than
274 if (isset($mappingName)) {
275 if (($this->_columnCount
!= count($mappingName))) {
279 if ($warning != 0 && $this->get('savedMapping')) {
280 $session = CRM_Core_Session
::singleton();
281 $session->setStatus(ts('The data columns in this import file appear to be different from the saved mapping. Please verify that you have selected the correct saved mapping before continuing.'));
284 $session = CRM_Core_Session
::singleton();
285 $session->setStatus(NULL);
288 $this->setDefaults($defaults);
293 'name' => ts('Previous'),
297 'name' => ts('Continue'),
298 'spacing' => ' ',
303 'name' => ts('Cancel'),
309 * Global validation rules for the form.
311 * @param array $fields
312 * Posted values of the form.
318 * list of errors to be posted back to the form
320 public static function formRule($fields, $files, $self) {
322 $fieldMessage = NULL;
323 $contactORContributionId = $self->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_UPDATE ?
'contribution_id' : 'contribution_contact_id';
324 if (!array_key_exists('savedMapping', $fields)) {
326 foreach ($fields['mapper'] as $mapperPart) {
327 $importKeys[] = $mapperPart[0];
330 $contactTypeId = $self->get('contactType');
332 CRM_Import_Parser
::CONTACT_INDIVIDUAL
=> 'Individual',
333 CRM_Import_Parser
::CONTACT_HOUSEHOLD
=> 'Household',
334 CRM_Import_Parser
::CONTACT_ORGANIZATION
=> 'Organization',
337 'used' => 'Unsupervised',
338 'contact_type' => $contactTypes[$contactTypeId] ??
'',
340 list($ruleFields, $threshold) = CRM_Dedupe_BAO_DedupeRuleGroup
::dedupeRuleFieldsWeight($params);
342 foreach ($importKeys as $key => $val) {
343 if (array_key_exists($val, $ruleFields)) {
344 $weightSum +
= $ruleFields[$val];
346 if ($val == "soft_credit") {
347 $mapperKey = CRM_Utils_Array
::key('soft_credit', $importKeys);
348 if (empty($fields['mapper'][$mapperKey][1])) {
349 if (empty($errors['_qf_default'])) {
350 $errors['_qf_default'] = '';
352 $errors['_qf_default'] .= ts('Missing required fields: Soft Credit') . '<br />';
356 foreach ($ruleFields as $field => $weight) {
357 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
359 $errors = self
::checkRequiredFields($self, $contactORContributionId, $importKeys, $errors, $weightSum, $threshold, $fieldMessage);
361 //at least one field should be mapped during update.
362 if ($self->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_UPDATE
) {
364 foreach ($self->_mapperFields
as $key => $field) {
365 if (in_array($key, $importKeys) &&
378 $errors['_qf_default'] .= ts('At least one contribution field needs to be mapped for update during update mode.') . '<br />';
383 if (!empty($fields['saveMapping'])) {
384 $nameField = $fields['saveMappingName'] ??
NULL;
385 if (empty($nameField)) {
386 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
389 if (CRM_Core_BAO_Mapping
::checkMapping($nameField, CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Contribution'))) {
390 $errors['saveMappingName'] = ts('Duplicate Import Contribution Mapping Name');
395 if (!empty($errors)) {
396 if (!empty($errors['saveMappingName'])) {
398 $assignError = new CRM_Core_Page();
399 $assignError->assign('mappingDetailsError', $_flag);
401 if (!empty($errors['_qf_default'])) {
402 CRM_Core_Session
::setStatus($errors['_qf_default'], ts("Error"), "error");
411 * Process the mapped fields and map it into the uploaded file preview the file and extract some summary statistics.
413 public function postProcess() {
414 $params = $this->controller
->exportValues('MapField');
416 //reload the mapfield if load mapping is pressed
417 if (!empty($params['savedMapping'])) {
418 $this->set('savedMapping', $params['savedMapping']);
419 $this->controller
->resetPage($this->_name
);
422 $this->updateUserJobMetadata('submitted_values', $this->getSubmittedValues());
424 $mapper = $mapperKeysMain = $mapperSoftCredit = $softCreditFields = $mapperPhoneType = $mapperSoftCreditType = [];
425 $mapperKeys = $this->controller
->exportValue($this->_name
, 'mapper');
427 $softCreditTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
429 for ($i = 0; $i < $this->_columnCount
; $i++
) {
430 $mapper[$i] = $this->_mapperFields
[$mapperKeys[$i][0]];
431 $mapperKeysMain[$i] = $mapperKeys[$i][0];
433 if (isset($mapperKeys[$i][0]) && $mapperKeys[$i][0] == 'soft_credit') {
434 $mapperSoftCredit[$i] = $mapperKeys[$i][1];
435 if (strpos($mapperSoftCredit[$i], '_') !== FALSE) {
436 [$first, $second] = explode('_', $mapperSoftCredit[$i]);
437 $softCreditFields[$i] = ucwords($first . " " . $second);
440 $softCreditFields[$i] = $mapperSoftCredit[$i];
442 $mapperSoftCreditType[$i] = [
443 'value' => $mapperKeys[$i][2] ??
'',
444 'label' => $softCreditTypes[$mapperKeys[$i][2]] ??
'',
448 $mapperSoftCredit[$i] = $softCreditFields[$i] = $mapperSoftCreditType[$i] = NULL;
452 $this->set('mapper', $mapper);
453 $this->set('softCreditFields', $softCreditFields);
454 $this->set('mapperSoftCreditType', $mapperSoftCreditType);
456 // store mapping Id to display it in the preview page
457 $this->set('loadMappingId', CRM_Utils_Array
::value('mappingId', $params));
459 //Updating Mapping Records
460 if (!empty($params['updateMapping'])) {
461 for ($i = 0; $i < $this->_columnCount
; $i++
) {
462 $this->saveMappingField($params['mappingId'], $i, TRUE);
466 //Saving Mapping Details and Records
467 if (!empty($params['saveMapping'])) {
469 'name' => $params['saveMappingName'],
470 'description' => $params['saveMappingDesc'],
471 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Contribution'),
473 $saveMapping = CRM_Core_BAO_Mapping
::add($mappingParams);
475 for ($i = 0; $i < $this->_columnCount
; $i++
) {
476 $this->saveMappingField($saveMapping->id
, $i, FALSE);
478 $this->set('savedMapping', $saveMapping->id
);
481 $parser = new CRM_Contribute_Import_Parser_Contribution($mapperKeysMain);
482 $parser->setUserJobID($this->getUserJobID());
484 $this->getSubmittedValue('uploadFile'),
485 $this->getSubmittedValue('fieldSeparator'),
487 $this->getSubmittedValue('skipColumnHeader'),
488 CRM_Import_Parser
::MODE_PREVIEW
,
489 $this->get('contactType')
492 // add all the necessary variables to the form
497 * @return \CRM_Contribute_Import_Parser_Contribution
499 protected function getParser(): CRM_Contribute_Import_Parser_Contribution
{
500 if (!$this->parser
) {
501 $this->parser
= new CRM_Contribute_Import_Parser_Contribution();
502 $this->parser
->setUserJobID($this->getUserJobID());
503 $this->parser
->init();
505 return $this->parser
;