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