Merge pull request #23332 from darrick/dupeQuery
[civicrm-core.git] / CRM / Member / Import / Form / MapField.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class gets the name of the file to upload
20 */
21 class CRM_Member_Import_Form_MapField extends CRM_Import_Form_MapField {
22
23
24 /**
25 * store contactType.
26 *
27 * @var int
28 */
29 public static $_contactType = NULL;
30
31 /**
32 * Set variables up before form is built.
33 *
34 * @return void
35 */
36 public function preProcess() {
37 $this->_mapperFields = $this->get('fields');
38 asort($this->_mapperFields);
39
40 $this->_columnCount = $this->get('columnCount');
41 $this->assign('columnCount', $this->_columnCount);
42 $this->_dataValues = $this->get('dataValues');
43 $this->assign('dataValues', $this->_dataValues);
44
45 $skipColumnHeader = $this->controller->exportValue('DataSource', 'skipColumnHeader');
46 $this->_onDuplicate = $this->get('onDuplicate', $onDuplicate ?? "");
47
48 $highlightedFields = [];
49 if ($skipColumnHeader) {
50 $this->assign('skipColumnHeader', $skipColumnHeader);
51 $this->assign('rowDisplayCount', 3);
52 /* if we had a column header to skip, stash it for later */
53
54 $this->_columnHeaders = $this->_dataValues[0];
55 }
56 else {
57 $this->assign('rowDisplayCount', 2);
58 }
59
60 //CRM-2219 removing other required fields since for updation only
61 //membership id is required.
62 if ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_UPDATE) {
63 $remove = array('membership_contact_id', 'email', 'first_name', 'last_name', 'external_identifier');
64 foreach ($remove as $value) {
65 unset($this->_mapperFields[$value]);
66 }
67 $highlightedFieldsArray = array('membership_id', 'membership_start_date', 'membership_type_id');
68 foreach ($highlightedFieldsArray as $name) {
69 $highlightedFields[] = $name;
70 }
71 }
72 elseif ($this->_onDuplicate == CRM_Import_Parser::DUPLICATE_SKIP) {
73 unset($this->_mapperFields['membership_id']);
74 $highlightedFieldsArray = array(
75 'membership_contact_id',
76 'email',
77 'external_identifier',
78 'membership_start_date',
79 'membership_type_id',
80 );
81 foreach ($highlightedFieldsArray as $name) {
82 $highlightedFields[] = $name;
83 }
84 }
85
86 // modify field title
87 $this->_mapperFields['status_id'] = ts('Membership Status');
88 $this->_mapperFields['membership_type_id'] = ts('Membership Type');
89
90 self::$_contactType = $this->get('contactType');
91 $this->assign('highlightedFields', $highlightedFields);
92 }
93
94 /**
95 * Build the form object.
96 *
97 * @return void
98 */
99 public function buildQuickForm() {
100 //to save the current mappings
101 if (!$this->get('savedMapping')) {
102 $saveDetailsName = ts('Save this field mapping');
103 $this->applyFilter('saveMappingName', 'trim');
104 $this->add('text', 'saveMappingName', ts('Name'));
105 $this->add('text', 'saveMappingDesc', ts('Description'));
106 }
107 else {
108 $savedMapping = $this->get('savedMapping');
109
110 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingRelation) = CRM_Core_BAO_Mapping::getMappingFields($savedMapping);
111
112 $mappingName = $mappingName[1];
113 $mappingContactType = $mappingContactType[1];
114 $mappingLocation = $mappingLocation['1'] ?? NULL;
115 $mappingPhoneType = $mappingPhoneType['1'] ?? NULL;
116 $mappingRelation = $mappingRelation['1'] ?? NULL;
117
118 //mapping is to be loaded from database
119
120 $this->set('loadedMapping', $savedMapping);
121
122 $getMappingName = new CRM_Core_DAO_Mapping();
123 $getMappingName->id = $savedMapping;
124 $getMappingName->mapping_type = 'Import Memberships';
125 $getMappingName->find();
126 while ($getMappingName->fetch()) {
127 $mapperName = $getMappingName->name;
128 }
129
130 $this->assign('savedMappingName', $mapperName);
131
132 $this->add('hidden', 'mappingId', $savedMapping);
133
134 $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
135 $saveDetailsName = ts('Save as a new field mapping');
136 $this->add('text', 'saveMappingName', ts('Name'));
137 $this->add('text', 'saveMappingDesc', ts('Description'));
138 }
139
140 $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
141
142 $this->addFormRule(array('CRM_Member_Import_Form_MapField', 'formRule'), $this);
143
144 //-------- end of saved mapping stuff ---------
145
146 $defaults = [];
147 $mapperKeys = array_keys($this->_mapperFields);
148 $hasHeaders = !empty($this->_columnHeaders);
149 $headerPatterns = $this->get('headerPatterns');
150 $dataPatterns = $this->get('dataPatterns');
151
152 /* Initialize all field usages to false */
153
154 foreach ($mapperKeys as $key) {
155 $this->_fieldUsed[$key] = FALSE;
156 }
157 $this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
158 $sel1 = $this->_mapperFields;
159 if (!$this->get('onDuplicate')) {
160 unset($sel1['id']);
161 unset($sel1['membership_id']);
162 }
163
164 $sel2[''] = NULL;
165
166 $js = "<script type='text/javascript'>\n";
167 $formName = 'document.forms.' . $this->_name;
168
169 //used to warn for mismatch column count or mismatch mapping
170 $warning = 0;
171
172 for ($i = 0; $i < $this->_columnCount; $i++) {
173 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
174 $jsSet = FALSE;
175 if ($this->get('savedMapping')) {
176 if (isset($mappingName[$i])) {
177 if ($mappingName[$i] != ts('- do not import -')) {
178
179 $mappingHeader = array_keys($this->_mapperFields, $mappingName[$i]);
180
181 //When locationType is not set
182 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
183
184 //When phoneType is not set
185 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
186
187 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
188
189 $defaults["mapper[$i]"] = array($mappingHeader[0]);
190 $jsSet = TRUE;
191 }
192 else {
193 $defaults["mapper[$i]"] = [];
194 }
195 if (!$jsSet) {
196 for ($k = 1; $k < 4; $k++) {
197 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
198 }
199 }
200 }
201 else {
202 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
203 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
204
205 if ($hasHeaders) {
206 $defaults["mapper[$i]"] = array($this->defaultFromHeader($this->_columnHeaders[$i], $headerPatterns));
207 }
208 else {
209 $defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
210 }
211 }
212 //end of load mapping
213 }
214 else {
215 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
216 if ($hasHeaders) {
217 // Infer the default from the skipped headers if we have them
218 $defaults["mapper[$i]"] = array(
219 $this->defaultFromHeader($this->_columnHeaders[$i],
220 $headerPatterns
221 ),
222 // $defaultLocationType->id
223 0,
224 );
225 }
226 else {
227 // Otherwise guess the default from the form of the data
228 $defaults["mapper[$i]"] = array(
229 $this->defaultFromData($dataPatterns, $i),
230 // $defaultLocationType->id
231 0,
232 );
233 }
234 }
235 $sel->setOptions(array($sel1, $sel2, (isset($sel3)) ? $sel3 : "", (isset($sel4)) ? $sel4 : ""));
236 }
237 $js .= "</script>\n";
238 $this->assign('initHideBoxes', $js);
239
240 //set warning if mismatch in more than
241 if (isset($mappingName)) {
242 if (($this->_columnCount != count($mappingName))) {
243 $warning++;
244 }
245 }
246 if ($warning != 0 && $this->get('savedMapping')) {
247 $session = CRM_Core_Session::singleton();
248 $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.'));
249 }
250 else {
251 $session = CRM_Core_Session::singleton();
252 $session->setStatus(NULL);
253 }
254
255 $this->setDefaults($defaults);
256
257 $this->addButtons(array(
258 array(
259 'type' => 'back',
260 'name' => ts('Previous'),
261 ),
262 array(
263 'type' => 'next',
264 'name' => ts('Continue'),
265 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
266 'isDefault' => TRUE,
267 ),
268 array(
269 'type' => 'cancel',
270 'name' => ts('Cancel'),
271 ),
272 ));
273 }
274
275 /**
276 * Global validation rules for the form.
277 *
278 * @param array $fields
279 * Posted values of the form.
280 *
281 * @param $files
282 * @param self $self
283 *
284 * @return array
285 * list of errors to be posted back to the form
286 */
287 public static function formRule($fields, $files, $self) {
288 $errors = [];
289
290 if (!array_key_exists('savedMapping', $fields)) {
291 $importKeys = [];
292 foreach ($fields['mapper'] as $mapperPart) {
293 $importKeys[] = $mapperPart[0];
294 }
295 // FIXME: should use the schema titles, not redeclare them
296 $requiredFields = array(
297 'membership_contact_id' => ts('Contact ID'),
298 'membership_type_id' => ts('Membership Type'),
299 'membership_start_date' => ts('Membership Start Date'),
300 );
301
302 $contactTypeId = $self->get('contactType');
303 $contactTypes = array(
304 CRM_Import_Parser::CONTACT_INDIVIDUAL => 'Individual',
305 CRM_Import_Parser::CONTACT_HOUSEHOLD => 'Household',
306 CRM_Import_Parser::CONTACT_ORGANIZATION => 'Organization',
307 );
308 $params = array(
309 'used' => 'Unsupervised',
310 'contact_type' => $contactTypes[$contactTypeId],
311 );
312 list($ruleFields, $threshold) = CRM_Dedupe_BAO_DedupeRuleGroup::dedupeRuleFieldsWeight($params);
313 $weightSum = 0;
314 foreach ($importKeys as $key => $val) {
315 if (array_key_exists($val, $ruleFields)) {
316 $weightSum += $ruleFields[$val];
317 }
318 }
319 $fieldMessage = '';
320 foreach ($ruleFields as $field => $weight) {
321 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
322 }
323
324 foreach ($requiredFields as $field => $title) {
325 if (!in_array($field, $importKeys)) {
326 if ($field == 'membership_contact_id') {
327 if ((($weightSum >= $threshold || in_array('external_identifier', $importKeys)) &&
328 $self->_onDuplicate != CRM_Import_Parser::DUPLICATE_UPDATE
329 ) ||
330 in_array('membership_id', $importKeys)
331 ) {
332 continue;
333 }
334 else {
335 if (!isset($errors['_qf_default'])) {
336 $errors['_qf_default'] = '';
337 }
338 $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(
339 1 => $threshold,
340 )) . ' ' . ts('(OR Membership ID if update mode.)') . '<br />';
341 }
342 }
343 else {
344 if (!isset($errors['_qf_default'])) {
345 $errors['_qf_default'] = '';
346 }
347 $errors['_qf_default'] .= ts('Missing required field: %1', array(
348 1 => $title,
349 )) . '<br />';
350 }
351 }
352 }
353 }
354
355 if (!empty($fields['saveMapping'])) {
356 $nameField = $fields['saveMappingName'] ?? NULL;
357 if (empty($nameField)) {
358 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
359 }
360 else {
361 if (CRM_Core_BAO_Mapping::checkMapping($nameField, CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Membership'))) {
362 $errors['saveMappingName'] = ts('Duplicate Import Membership Mapping Name');
363 }
364 }
365 }
366
367 if (!empty($errors)) {
368 if (!empty($errors['saveMappingName'])) {
369 $_flag = 1;
370 $assignError = new CRM_Core_Page();
371 $assignError->assign('mappingDetailsError', $_flag);
372 }
373 return $errors;
374 }
375
376 return TRUE;
377 }
378
379 /**
380 * Process the mapped fields and map it into the uploaded file
381 * preview the file and extract some summary statistics
382 *
383 * @return void
384 */
385 public function postProcess() {
386 $params = $this->controller->exportValues('MapField');
387 //reload the mapfield if load mapping is pressed
388 if (!empty($params['savedMapping'])) {
389 $this->set('savedMapping', $params['savedMapping']);
390 $this->controller->resetPage($this->_name);
391 return;
392 }
393 $this->updateUserJobMetadata('submitted_values', $this->getSubmittedValues());
394
395 $mapper = [];
396 $mapperKeys = $this->controller->exportValue($this->_name, 'mapper');
397 $mapperKeysMain = [];
398
399 for ($i = 0; $i < $this->_columnCount; $i++) {
400 $mapper[$i] = $this->_mapperFields[$mapperKeys[$i][0]];
401 $mapperKeysMain[$i] = $mapperKeys[$i][0];
402 }
403
404 $this->set('mapper', $mapper);
405
406 // store mapping Id to display it in the preview page
407 if (!empty($params['mappingId'])) {
408 $this->set('loadMappingId', $params['mappingId']);
409 }
410 //Updating Mapping Records
411 if (!empty($params['updateMapping'])) {
412 $mappingFields = new CRM_Core_DAO_MappingField();
413 $mappingFields->mapping_id = $params['mappingId'];
414 $mappingFields->find();
415
416 $mappingFieldsId = [];
417 while ($mappingFields->fetch()) {
418 if ($mappingFields->id) {
419 $mappingFieldsId[$mappingFields->column_number] = $mappingFields->id;
420 }
421 }
422
423 for ($i = 0; $i < $this->_columnCount; $i++) {
424 $updateMappingFields = new CRM_Core_DAO_MappingField();
425 $updateMappingFields->id = $mappingFieldsId[$i];
426 $updateMappingFields->mapping_id = $params['mappingId'];
427 $updateMappingFields->column_number = $i;
428 $updateMappingFields->name = $mapper[$i];
429 $updateMappingFields->save();
430 }
431 }
432
433 //Saving Mapping Details and Records
434 if (!empty($params['saveMapping'])) {
435 $mappingParams = array(
436 'name' => $params['saveMappingName'],
437 'description' => $params['saveMappingDesc'],
438 'mapping_type_id' => CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Membership'),
439 );
440 $saveMapping = CRM_Core_BAO_Mapping::add($mappingParams);
441
442 for ($i = 0; $i < $this->_columnCount; $i++) {
443
444 $saveMappingFields = new CRM_Core_DAO_MappingField();
445 $saveMappingFields->mapping_id = $saveMapping->id;
446 $saveMappingFields->column_number = $i;
447 $saveMappingFields->name = $mapper[$i];
448 $saveMappingFields->save();
449 }
450 $this->set('savedMapping', $saveMappingFields->mapping_id);
451 }
452
453 $parser = new CRM_Member_Import_Parser_Membership($mapperKeysMain);
454 $parser->setUserJobID($this->getUserJobID());
455 $parser->run($this->getSubmittedValue('uploadFile'), $this->getSubmittedValue('fieldSeparator'), $mapper, $this->getSubmittedValue('skipColumnHeader'),
456 CRM_Import_Parser::MODE_PREVIEW, $this->get('contactType')
457 );
458 // add all the necessary variables to the form
459 $parser->set($this);
460 }
461
462 }