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_Member_Import_Form_MapField
extends CRM_Import_Form_MapField
{
28 public static $_contactType = NULL;
31 * Set variables up before form is built.
35 public function preProcess() {
36 $this->_mapperFields
= $this->get('fields');
37 asort($this->_mapperFields
);
39 $this->_columnCount
= $this->get('columnCount');
40 $this->assign('columnCount', $this->_columnCount
);
41 $this->_dataValues
= $this->get('dataValues');
42 $this->assign('dataValues', $this->_dataValues
);
44 $skipColumnHeader = $this->controller
->exportValue('DataSource', 'skipColumnHeader');
45 $this->_onDuplicate
= $this->get('onDuplicate', $onDuplicate ??
"");
47 $highlightedFields = [];
48 if ($skipColumnHeader) {
49 $this->assign('skipColumnHeader', $skipColumnHeader);
50 $this->assign('rowDisplayCount', 3);
51 /* if we had a column header to skip, stash it for later */
53 $this->_columnHeaders
= $this->_dataValues
[0];
56 $this->assign('rowDisplayCount', 2);
59 //CRM-2219 removing other required fields since for updation only
60 //membership id is required.
61 if ($this->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_UPDATE
) {
62 $remove = array('membership_contact_id', 'email', 'first_name', 'last_name', 'external_identifier');
63 foreach ($remove as $value) {
64 unset($this->_mapperFields
[$value]);
66 $highlightedFieldsArray = array('membership_id', 'membership_start_date', 'membership_type_id');
67 foreach ($highlightedFieldsArray as $name) {
68 $highlightedFields[] = $name;
71 elseif ($this->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_SKIP
) {
72 unset($this->_mapperFields
['membership_id']);
73 $highlightedFieldsArray = array(
74 'membership_contact_id',
76 'external_identifier',
77 'membership_start_date',
80 foreach ($highlightedFieldsArray as $name) {
81 $highlightedFields[] = $name;
86 $this->_mapperFields
['status_id'] = ts('Membership Status');
87 $this->_mapperFields
['membership_type_id'] = ts('Membership Type');
89 self
::$_contactType = $this->get('contactType');
90 $this->assign('highlightedFields', $highlightedFields);
94 * Build the form object.
98 public function buildQuickForm() {
99 //to save the current mappings
100 if (!$this->get('savedMapping')) {
101 $saveDetailsName = ts('Save this field mapping');
102 $this->applyFilter('saveMappingName', 'trim');
103 $this->add('text', 'saveMappingName', ts('Name'));
104 $this->add('text', 'saveMappingDesc', ts('Description'));
107 $savedMapping = $this->get('savedMapping');
109 list($mappingName) = CRM_Core_BAO_Mapping
::getMappingFields($savedMapping);
111 $mappingName = $mappingName[1];
113 //mapping is to be loaded from database
115 $this->set('loadedMapping', $savedMapping);
117 $getMappingName = new CRM_Core_DAO_Mapping();
118 $getMappingName->id
= $savedMapping;
119 $getMappingName->mapping_type
= 'Import Memberships';
120 $getMappingName->find();
121 while ($getMappingName->fetch()) {
122 $mapperName = $getMappingName->name
;
125 $this->assign('savedMappingName', $mapperName);
127 $this->add('hidden', 'mappingId', $savedMapping);
129 $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
130 $saveDetailsName = ts('Save as a new field mapping');
131 $this->add('text', 'saveMappingName', ts('Name'));
132 $this->add('text', 'saveMappingDesc', ts('Description'));
135 $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
137 $this->addFormRule(array('CRM_Member_Import_Form_MapField', 'formRule'), $this);
139 //-------- end of saved mapping stuff ---------
142 $mapperKeys = array_keys($this->_mapperFields
);
143 $hasHeaders = !empty($this->_columnHeaders
);
144 $headerPatterns = $this->get('headerPatterns');
145 $dataPatterns = $this->get('dataPatterns');
147 /* Initialize all field usages to false */
149 foreach ($mapperKeys as $key) {
150 $this->_fieldUsed
[$key] = FALSE;
152 $this->_location_types
= CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
153 $sel1 = $this->_mapperFields
;
154 if (!$this->get('onDuplicate')) {
156 unset($sel1['membership_id']);
161 $js = "<script type='text/javascript'>\n";
162 $formName = 'document.forms.' . $this->_name
;
164 //used to warn for mismatch column count or mismatch mapping
167 for ($i = 0; $i < $this->_columnCount
; $i++
) {
168 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
170 if ($this->get('savedMapping')) {
171 if (isset($mappingName[$i])) {
172 if ($mappingName[$i] != ts('- do not import -')) {
174 $mappingHeader = array_keys($this->_mapperFields
, $mappingName[$i]);
176 //When locationType is not set
177 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
179 //When phoneType is not set
180 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
182 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
184 $defaults["mapper[$i]"] = array($mappingHeader[0]);
188 $defaults["mapper[$i]"] = [];
191 for ($k = 1; $k < 4; $k++
) {
192 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
197 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
198 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
201 $defaults["mapper[$i]"] = array($this->defaultFromHeader($this->_columnHeaders
[$i], $headerPatterns));
204 $defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
207 //end of load mapping
210 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
212 // Infer the default from the skipped headers if we have them
213 $defaults["mapper[$i]"] = array(
214 $this->defaultFromHeader($this->_columnHeaders
[$i],
217 // $defaultLocationType->id
222 // Otherwise guess the default from the form of the data
223 $defaults["mapper[$i]"] = array(
224 $this->defaultFromData($dataPatterns, $i),
225 // $defaultLocationType->id
230 $sel->setOptions(array($sel1, $sel2, (isset($sel3)) ?
$sel3 : "", (isset($sel4)) ?
$sel4 : ""));
232 $js .= "</script>\n";
233 $this->assign('initHideBoxes', $js);
235 //set warning if mismatch in more than
236 if (isset($mappingName)) {
237 if (($this->_columnCount
!= count($mappingName))) {
241 if ($warning != 0 && $this->get('savedMapping')) {
242 $session = CRM_Core_Session
::singleton();
243 $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.'));
246 $session = CRM_Core_Session
::singleton();
247 $session->setStatus(NULL);
250 $this->setDefaults($defaults);
252 $this->addButtons(array(
255 'name' => ts('Previous'),
259 'name' => ts('Continue'),
260 'spacing' => ' ',
265 'name' => ts('Cancel'),
271 * Global validation rules for the form.
273 * @param array $fields
274 * Posted values of the form.
280 * list of errors to be posted back to the form
282 public static function formRule($fields, $files, $self) {
286 foreach ($fields['mapper'] as $mapperPart) {
287 $importKeys[] = $mapperPart[0];
289 // FIXME: should use the schema titles, not redeclare them
290 $requiredFields = array(
291 'membership_contact_id' => ts('Contact ID'),
292 'membership_type_id' => ts('Membership Type'),
293 'membership_start_date' => ts('Membership Start Date'),
296 $contactTypeId = $self->get('contactType');
297 $contactTypes = array(
298 CRM_Import_Parser
::CONTACT_INDIVIDUAL
=> 'Individual',
299 CRM_Import_Parser
::CONTACT_HOUSEHOLD
=> 'Household',
300 CRM_Import_Parser
::CONTACT_ORGANIZATION
=> 'Organization',
303 'used' => 'Unsupervised',
304 'contact_type' => $contactTypes[$contactTypeId],
306 list($ruleFields, $threshold) = CRM_Dedupe_BAO_DedupeRuleGroup
::dedupeRuleFieldsWeight($params);
308 foreach ($importKeys as $key => $val) {
309 if (array_key_exists($val, $ruleFields)) {
310 $weightSum +
= $ruleFields[$val];
314 foreach ($ruleFields as $field => $weight) {
315 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
318 foreach ($requiredFields as $field => $title) {
319 if (!in_array($field, $importKeys)) {
320 if ($field == 'membership_contact_id') {
321 if ((($weightSum >= $threshold ||
in_array('external_identifier', $importKeys)) &&
322 $self->_onDuplicate
!= CRM_Import_Parser
::DUPLICATE_UPDATE
324 in_array('membership_id', $importKeys)
329 if (!isset($errors['_qf_default'])) {
330 $errors['_qf_default'] = '';
332 $errors['_qf_default'] .= ts('Missing required contact matching fields.') . " $fieldMessage " . ts('(Sum of all weights should be greater than or equal to threshold: %1).', array(
334 )) . ' ' . ts('(OR Membership ID if update mode.)') . '<br />';
338 if (!isset($errors['_qf_default'])) {
339 $errors['_qf_default'] = '';
341 $errors['_qf_default'] .= ts('Missing required field: %1', array(
348 if (!empty($fields['saveMapping'])) {
349 $nameField = $fields['saveMappingName'] ??
NULL;
350 if (empty($nameField)) {
351 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
354 if (CRM_Core_BAO_Mapping
::checkMapping($nameField, CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Membership'))) {
355 $errors['saveMappingName'] = ts('Duplicate Import Membership Mapping Name');
360 if (!empty($errors)) {
361 if (!empty($errors['saveMappingName'])) {
363 $assignError = new CRM_Core_Page();
364 $assignError->assign('mappingDetailsError', $_flag);
373 * Process the mapped fields and map it into the uploaded file
374 * preview the file and extract some summary statistics
378 public function postProcess() {
379 $params = $this->controller
->exportValues('MapField');
380 $this->updateUserJobMetadata('submitted_values', $this->getSubmittedValues());
382 $mapperKeys = $this->controller
->exportValue($this->_name
, 'mapper');
383 $mapperKeysMain = [];
385 for ($i = 0; $i < $this->_columnCount
; $i++
) {
386 $mapper[$i] = $this->_mapperFields
[$mapperKeys[$i][0]];
387 $mapperKeysMain[$i] = $mapperKeys[$i][0];
390 $this->set('mapper', $mapper);
392 // store mapping Id to display it in the preview page
393 if (!empty($params['mappingId'])) {
394 $this->set('loadMappingId', $params['mappingId']);
396 //Updating Mapping Records
397 if (!empty($params['updateMapping'])) {
398 $mappingFields = new CRM_Core_DAO_MappingField();
399 $mappingFields->mapping_id
= $params['mappingId'];
400 $mappingFields->find();
402 $mappingFieldsId = [];
403 while ($mappingFields->fetch()) {
404 if ($mappingFields->id
) {
405 $mappingFieldsId[$mappingFields->column_number
] = $mappingFields->id
;
409 for ($i = 0; $i < $this->_columnCount
; $i++
) {
410 $updateMappingFields = new CRM_Core_DAO_MappingField();
411 $updateMappingFields->id
= $mappingFieldsId[$i];
412 $updateMappingFields->mapping_id
= $params['mappingId'];
413 $updateMappingFields->column_number
= $i;
414 $updateMappingFields->name
= $mapper[$i];
415 $updateMappingFields->save();
419 //Saving Mapping Details and Records
420 if (!empty($params['saveMapping'])) {
421 $mappingParams = array(
422 'name' => $params['saveMappingName'],
423 'description' => $params['saveMappingDesc'],
424 'mapping_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Membership'),
426 $saveMapping = CRM_Core_BAO_Mapping
::add($mappingParams);
428 for ($i = 0; $i < $this->_columnCount
; $i++
) {
430 $saveMappingFields = new CRM_Core_DAO_MappingField();
431 $saveMappingFields->mapping_id
= $saveMapping->id
;
432 $saveMappingFields->column_number
= $i;
433 $saveMappingFields->name
= $mapper[$i];
434 $saveMappingFields->save();
436 $this->set('savedMapping', $saveMappingFields->mapping_id
);
439 $parser = new CRM_Member_Import_Parser_Membership($mapperKeysMain);
440 $parser->setUserJobID($this->getUserJobID());
441 $parser->run($this->getSubmittedValue('uploadFile'), $this->getSubmittedValue('fieldSeparator'), $mapper, $this->getSubmittedValue('skipColumnHeader'),
442 CRM_Import_Parser
::MODE_PREVIEW
, $this->get('contactType')
444 // add all the necessary variables to the form
449 * @return \CRM_Member_Import_Parser_Membership
451 protected function getParser(): CRM_Member_Import_Parser_Membership
{
452 if (!$this->parser
) {
453 $this->parser
= new CRM_Member_Import_Parser_Membership();
454 $this->parser
->setUserJobID($this->getUserJobID());
455 $this->parser
->init();
457 return $this->parser
;