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() {
77 $this->_columnCount
= $this->get('columnCount');
78 $skipColumnHeader = $this->getSubmittedValue('skipColumnHeader');
79 $this->_onDuplicate
= $this->getSubmittedValue('onDuplicate');
80 $this->assign('skipColumnHeader', $skipColumnHeader);
82 $highlightedFields = ['financial_type_id', 'total_amount'];
83 //CRM-2219 removing other required fields since for updation only
84 //invoice id or trxn id or contribution id is required.
85 if ($this->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_UPDATE
) {
87 'contribution_contact_id',
91 'external_identifier',
93 foreach ($remove as $value) {
94 unset($this->_mapperFields
[$value]);
97 //modify field title only for update mode. CRM-3245
103 $this->_mapperFields
[$key] .= ' (match to contribution record)';
104 $highlightedFields[] = $key;
107 elseif ($this->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_SKIP
) {
108 unset($this->_mapperFields
['contribution_id']);
109 $highlightedFieldsArray = [
110 'contribution_contact_id',
114 'external_identifier',
116 foreach ($highlightedFieldsArray as $name) {
117 $highlightedFields[] = $name;
121 // modify field title for contribution status
122 $this->_mapperFields
['contribution_status_id'] = ts('Contribution Status');
124 $this->assign('highlightedFields', $highlightedFields);
128 * Build the form object.
130 * @throws \CiviCRM_API3_Exception
132 public function buildQuickForm() {
133 $savedMappingID = $this->getSubmittedValue('savedMapping');
135 $this->buildSavedMappingFields($savedMappingID);
138 'CRM_Contribute_Import_Form_MapField',
142 //-------- end of saved mapping stuff ---------
145 $mapperKeys = array_keys($this->_mapperFields
);
146 $hasHeaders = $this->getSubmittedValue('skipColumnHeader');
147 $headerPatterns = $this->getHeaderPatterns();
148 $dataPatterns = $this->getDataPatterns();
149 $mapperKeysValues = $this->getSubmittedValue('mapper');
150 $columnHeaders = $this->getColumnHeaders();
152 /* Initialize all field usages to false */
153 foreach ($mapperKeys as $key) {
154 $this->_fieldUsed
[$key] = FALSE;
156 $sel1 = $this->_mapperFields
;
158 if (!$this->get('onDuplicate')) {
160 unset($sel1['contribution_id']);
163 $softCreditFields['contact_id'] = ts('Contact ID');
164 $softCreditFields['external_identifier'] = ts('External ID');
165 $softCreditFields['email'] = ts('Email');
167 $sel2['soft_credit'] = $softCreditFields;
168 $sel3['soft_credit']['contact_id'] = $sel3['soft_credit']['external_identifier'] = $sel3['soft_credit']['email'] = CRM_Core_OptionGroup
::values('soft_credit_type');
171 // end of soft credit section
172 $js = "<script type='text/javascript'>\n";
173 $formName = 'document.forms.' . $this->_name
;
175 //used to warn for mismatch column count or mismatch mapping
178 foreach ($columnHeaders as $i => $columnHeader) {
179 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
181 if ($this->get('savedMapping')) {
182 [$mappingName, $mappingContactType] = CRM_Core_BAO_Mapping
::getMappingFields($savedMappingID);
184 $mappingName = $mappingName[1];
185 $mappingContactType = $mappingContactType[1];
186 if (isset($mappingName[$i])) {
187 if ($mappingName[$i] != ts('do_not_import')) {
188 $softField = $mappingContactType[$i] ??
'';
191 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
194 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
195 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
196 $defaults["mapper[$i]"] = [
199 // Since the soft credit type id is not stored we can't load it here.
205 $defaults["mapper[$i]"] = [];
208 for ($k = 1; $k < 4; $k++
) {
209 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
214 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
215 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
218 $defaults["mapper[$i]"] = [$this->defaultFromHeader($columnHeader, $headerPatterns)];
221 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i)];
224 //end of load mapping
227 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
229 // do array search first to see if has mapped key
230 $columnKey = array_search($columnHeader, $this->_mapperFields
);
231 if (isset($this->_fieldUsed
[$columnKey])) {
232 $defaults["mapper[$i]"] = $columnKey;
233 $this->_fieldUsed
[$key] = TRUE;
236 // Infer the default from the column names if we have them
237 $defaults["mapper[$i]"] = [
238 $this->defaultFromHeader($columnHeader, $headerPatterns),
244 // Otherwise guess the default from the form of the data
245 $defaults["mapper[$i]"] = [
246 $this->defaultFromData($dataPatterns, $i),
250 if (!empty($mapperKeysValues) && ($mapperKeysValues[$i][0] ??
NULL) === 'soft_credit') {
251 $softCreditField = $mapperKeysValues[$i][1];
252 $softCreditTypeID = $mapperKeysValues[$i][2];
253 $js .= "cj('#mapper_" . $i . "_1').val($softCreditField);\n";
254 $js .= "cj('#mapper_" . $i . "_2').val($softCreditTypeID);\n";
257 $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
259 $js .= "</script>\n";
260 $this->assign('initHideBoxes', $js);
262 //set warning if mismatch in more than
263 if (isset($mappingName)) {
264 if (($this->_columnCount
!= count($mappingName))) {
268 if ($warning != 0 && $this->get('savedMapping')) {
269 $session = CRM_Core_Session
::singleton();
270 $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.'));
273 $session = CRM_Core_Session
::singleton();
274 $session->setStatus(NULL);
277 $this->setDefaults($defaults);
279 $this->addFormButtons();
283 * Global validation rules for the form.
285 * @param array $fields
286 * Posted values of the form.
292 * list of errors to be posted back to the form
294 public static function formRule($fields, $files, $self) {
296 $fieldMessage = NULL;
297 $contactORContributionId = $self->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_UPDATE ?
'contribution_id' : 'contribution_contact_id';
298 if (!array_key_exists('savedMapping', $fields)) {
300 foreach ($fields['mapper'] as $mapperPart) {
301 $importKeys[] = $mapperPart[0];
305 'used' => 'Unsupervised',
306 'contact_type' => $self->getContactType(),
308 [$ruleFields, $threshold] = CRM_Dedupe_BAO_DedupeRuleGroup
::dedupeRuleFieldsWeight($params);
310 foreach ($importKeys as $key => $val) {
311 if (array_key_exists($val, $ruleFields)) {
312 $weightSum +
= $ruleFields[$val];
314 if ($val == "soft_credit") {
315 $mapperKey = CRM_Utils_Array
::key('soft_credit', $importKeys);
316 if (empty($fields['mapper'][$mapperKey][1])) {
317 if (empty($errors['_qf_default'])) {
318 $errors['_qf_default'] = '';
320 $errors['_qf_default'] .= ts('Missing required fields: Soft Credit') . '<br />';
324 foreach ($ruleFields as $field => $weight) {
325 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
327 $errors = self
::checkRequiredFields($self, $contactORContributionId, $importKeys, $errors, $weightSum, $threshold, $fieldMessage);
329 //at least one field should be mapped during update.
330 if ($self->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_UPDATE
) {
332 foreach ($self->_mapperFields
as $key => $field) {
333 if (in_array($key, $importKeys) &&
346 $errors['_qf_default'] .= ts('At least one contribution field needs to be mapped for update during update mode.') . '<br />';
351 if (!empty($fields['saveMapping'])) {
352 $nameField = $fields['saveMappingName'] ??
NULL;
353 if (empty($nameField)) {
354 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
357 if (CRM_Core_BAO_Mapping
::checkMapping($nameField, CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Contribution'))) {
358 $errors['saveMappingName'] = ts('Duplicate Import Contribution Mapping Name');
363 if (!empty($errors)) {
364 if (!empty($errors['saveMappingName'])) {
366 $assignError = new CRM_Core_Page();
367 $assignError->assign('mappingDetailsError', $_flag);
369 if (!empty($errors['_qf_default'])) {
370 CRM_Core_Session
::setStatus($errors['_qf_default'], ts("Error"), "error");
379 * Get the mapping name per the civicrm_mapping_field.type_id option group.
383 public function getMappingTypeName(): string {
384 return 'Import Contribution';
388 * @return \CRM_Contribute_Import_Parser_Contribution
390 protected function getParser(): CRM_Contribute_Import_Parser_Contribution
{
391 if (!$this->parser
) {
392 $this->parser
= new CRM_Contribute_Import_Parser_Contribution();
393 $this->parser
->setUserJobID($this->getUserJobID());
394 $this->parser
->init();
396 return $this->parser
;