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