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->isUpdateExisting()
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->isUpdateExisting() &&
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 $highlightedFields = ['financial_type_id', 'total_amount'];
78 //CRM-2219 removing other required fields since for updation only
79 //invoice id or trxn id or contribution id is required.
80 if ($this->isUpdateExisting()) {
82 'contribution_contact_id',
86 'external_identifier',
88 foreach ($remove as $value) {
89 unset($this->_mapperFields
[$value]);
92 //modify field title only for update mode. CRM-3245
98 $this->_mapperFields
[$key] .= ' (match to contribution record)';
99 $highlightedFields[] = $key;
102 elseif ($this->isSkipExisting()) {
103 unset($this->_mapperFields
['contribution_id']);
104 $highlightedFieldsArray = [
105 'contribution_contact_id',
109 'external_identifier',
111 foreach ($highlightedFieldsArray as $name) {
112 $highlightedFields[] = $name;
116 // modify field title for contribution status
117 $this->_mapperFields
['contribution_status_id'] = ts('Contribution Status');
119 $this->assign('highlightedFields', $highlightedFields);
123 * Build the form object.
125 * @throws \CiviCRM_API3_Exception
127 public function buildQuickForm() {
128 $savedMappingID = $this->getSubmittedValue('savedMapping');
130 $this->buildSavedMappingFields($savedMappingID);
133 'CRM_Contribute_Import_Form_MapField',
137 //-------- end of saved mapping stuff ---------
140 $mapperKeys = array_keys($this->_mapperFields
);
141 $hasHeaders = $this->getSubmittedValue('skipColumnHeader');
142 $headerPatterns = $this->getHeaderPatterns();
143 $dataPatterns = $this->getDataPatterns();
144 $mapperKeysValues = $this->getSubmittedValue('mapper');
145 $columnHeaders = $this->getColumnHeaders();
146 $fieldMappings = $this->getFieldMappings();
148 /* Initialize all field usages to false */
149 foreach ($mapperKeys as $key) {
150 $this->_fieldUsed
[$key] = FALSE;
152 $sel1 = $this->_mapperFields
;
154 if (!$this->isUpdateExisting()) {
156 unset($sel1['contribution_id']);
159 $softCreditFields['contact_id'] = ts('Contact ID');
160 $softCreditFields['external_identifier'] = ts('External ID');
161 $softCreditFields['email'] = ts('Email');
163 $sel2['soft_credit'] = $softCreditFields;
164 $sel3['soft_credit']['contact_id'] = $sel3['soft_credit']['external_identifier'] = $sel3['soft_credit']['email'] = CRM_Core_OptionGroup
::values('soft_credit_type');
167 // end of soft credit section
168 $js = "<script type='text/javascript'>\n";
169 $formName = 'document.forms.' . $this->_name
;
171 //used to warn for mismatch column count or mismatch mapping
174 foreach ($columnHeaders as $i => $columnHeader) {
175 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', [1 => $i]), NULL);
177 if ($this->getSubmittedValue('savedMapping')) {
178 // $mappingContactType is not really a contact type - the data has been mangled
179 // into that field - see https://lab.civicrm.org/dev/core/-/issues/654
180 [$mappingName, $mappingContactType] = CRM_Core_BAO_Mapping
::getMappingFields($savedMappingID);
181 $fieldMapping = $fieldMappings[$i] ??
NULL;
182 $mappingContactType = $mappingContactType[1];
183 if (isset($fieldMappings[$i])) {
184 if ($fieldMapping['name'] !== ts('do_not_import')) {
185 $softField = $mappingContactType[$i] ??
'';
188 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
191 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
192 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
193 $defaults["mapper[$i]"] = [
194 $fieldMapping['name'],
196 // Since the soft credit type id is not stored we can't load it here.
202 $defaults["mapper[$i]"] = [];
205 for ($k = 1; $k < 4; $k++
) {
206 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
211 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
212 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
215 $defaults["mapper[$i]"] = [$this->defaultFromHeader($columnHeader, $headerPatterns)];
218 $defaults["mapper[$i]"] = [$this->defaultFromData($dataPatterns, $i)];
221 //end of load mapping
224 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_0_');\n";
226 // do array search first to see if has mapped key
227 $columnKey = array_search($columnHeader, $this->_mapperFields
);
228 if (isset($this->_fieldUsed
[$columnKey])) {
229 $defaults["mapper[$i]"] = $columnKey;
230 $this->_fieldUsed
[$key] = TRUE;
233 // Infer the default from the column names if we have them
234 $defaults["mapper[$i]"] = [
235 $this->defaultFromHeader($columnHeader, $headerPatterns),
241 // Otherwise guess the default from the form of the data
242 $defaults["mapper[$i]"] = [
243 $this->defaultFromData($dataPatterns, $i),
247 if (!empty($mapperKeysValues) && ($mapperKeysValues[$i][0] ??
NULL) === 'soft_credit') {
248 $softCreditField = $mapperKeysValues[$i][1];
249 $softCreditTypeID = $mapperKeysValues[$i][2];
250 $js .= "cj('#mapper_" . $i . "_1').val($softCreditField);\n";
251 $js .= "cj('#mapper_" . $i . "_2').val($softCreditTypeID);\n";
254 $sel->setOptions([$sel1, $sel2, $sel3, $sel4]);
256 $js .= "</script>\n";
257 $this->assign('initHideBoxes', $js);
258 $this->setDefaults($defaults);
260 $this->addFormButtons();
264 * Global validation rules for the form.
266 * @param array $fields
267 * Posted values of the form.
273 * list of errors to be posted back to the form
275 public static function formRule($fields, $files, $self) {
277 $fieldMessage = NULL;
278 $contactORContributionId = $self->isUpdateExisting() ?
'contribution_id' : 'contribution_contact_id';
279 if (!array_key_exists('savedMapping', $fields)) {
281 foreach ($fields['mapper'] as $mapperPart) {
282 $importKeys[] = $mapperPart[0];
286 'used' => 'Unsupervised',
287 'contact_type' => $self->getContactType(),
289 [$ruleFields, $threshold] = CRM_Dedupe_BAO_DedupeRuleGroup
::dedupeRuleFieldsWeight($params);
291 foreach ($importKeys as $key => $val) {
292 if (array_key_exists($val, $ruleFields)) {
293 $weightSum +
= $ruleFields[$val];
295 if ($val == "soft_credit") {
296 $mapperKey = CRM_Utils_Array
::key('soft_credit', $importKeys);
297 if (empty($fields['mapper'][$mapperKey][1])) {
298 if (empty($errors['_qf_default'])) {
299 $errors['_qf_default'] = '';
301 $errors['_qf_default'] .= ts('Missing required fields: Soft Credit') . '<br />';
305 foreach ($ruleFields as $field => $weight) {
306 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
308 $errors = self
::checkRequiredFields($self, $contactORContributionId, $importKeys, $errors, $weightSum, $threshold, $fieldMessage);
310 //at least one field should be mapped during update.
311 if ($self->isUpdateExisting()) {
313 foreach ($self->_mapperFields
as $key => $field) {
314 if (in_array($key, $importKeys) &&
327 $errors['_qf_default'] .= ts('At least one contribution field needs to be mapped for update during update mode.') . '<br />';
332 if (!empty($fields['saveMapping'])) {
333 $nameField = $fields['saveMappingName'] ??
NULL;
334 if (empty($nameField)) {
335 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
338 if (CRM_Core_BAO_Mapping
::checkMapping($nameField, CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Contribution'))) {
339 $errors['saveMappingName'] = ts('Duplicate Import Contribution Mapping Name');
344 if (!empty($errors)) {
345 if (!empty($errors['saveMappingName'])) {
347 $assignError = new CRM_Core_Page();
348 $assignError->assign('mappingDetailsError', $_flag);
350 if (!empty($errors['_qf_default'])) {
351 CRM_Core_Session
::setStatus($errors['_qf_default'], ts("Error"), "error");
360 * Get the mapping name per the civicrm_mapping_field.type_id option group.
364 public function getMappingTypeName(): string {
365 return 'Import Contribution';
369 * @return \CRM_Contribute_Import_Parser_Contribution
371 protected function getParser(): CRM_Contribute_Import_Parser_Contribution
{
372 if (!$this->parser
) {
373 $this->parser
= new CRM_Contribute_Import_Parser_Contribution();
374 $this->parser
->setUserJobID($this->getUserJobID());
375 $this->parser
->init();
377 return $this->parser
;