3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
37 * This class gets the name of the file to upload
39 class CRM_Contribute_Import_Form_MapField
extends CRM_Import_Form_MapField
{
45 * Function to set variables up before form is built
50 public function preProcess() {
51 $this->_mapperFields
= $this->get('fields');
52 asort($this->_mapperFields
);
54 $this->_columnCount
= $this->get('columnCount');
55 $this->assign('columnCount', $this->_columnCount
);
56 $this->_dataValues
= $this->get('dataValues');
57 $this->assign('dataValues', $this->_dataValues
);
59 $skipColumnHeader = $this->controller
->exportValue('DataSource', 'skipColumnHeader');
60 $this->_onDuplicate
= $this->get('onDuplicate', isset($onDuplicate) ?
$onDuplicate : "");
62 if ($skipColumnHeader) {
63 $this->assign('skipColumnHeader', $skipColumnHeader);
64 $this->assign('rowDisplayCount', 3);
65 /* if we had a column header to skip, stash it for later */
67 $this->_columnHeaders
= $this->_dataValues
[0];
70 $this->assign('rowDisplayCount', 2);
72 $highlightedFields = array();
73 $highlightedFields[] = 'financial_type';
74 //CRM-2219 removing other required fields since for updation only
75 //invoice id or trxn id or contribution id is required.
76 if ($this->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_UPDATE
) {
77 $remove = array('contribution_contact_id', 'email', 'first_name', 'last_name', 'external_identifier');
78 foreach ($remove as $value) {
79 unset($this->_mapperFields
[$value]);
82 //modify field title only for update mode. CRM-3245
84 'contribution_id', 'invoice_id', 'trxn_id') as $key) {
85 $this->_mapperFields
[$key] .= ' (match to contribution record)';
86 $highlightedFields[] = $key;
89 elseif ($this->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_SKIP
) {
90 unset($this->_mapperFields
['contribution_id']);
91 $highlightedFieldsArray = array('contribution_contact_id', 'email', 'first_name', 'last_name', 'external_identifier', 'total_amount');
92 foreach ($highlightedFieldsArray as $name) {
93 $highlightedFields[] = $name;
97 // modify field title for contribution status
98 $this->_mapperFields
['contribution_status_id'] = ts('Contribution Status');
100 $this->assign('highlightedFields', $highlightedFields);
104 * Function to actually build the form
109 public function buildQuickForm() {
110 //to save the current mappings
111 if (!$this->get('savedMapping')) {
112 $saveDetailsName = ts('Save this field mapping');
113 $this->applyFilter('saveMappingName', 'trim');
114 $this->add('text', 'saveMappingName', ts('Name'));
115 $this->add('text', 'saveMappingDesc', ts('Description'));
118 $savedMapping = $this->get('savedMapping');
120 list($mappingName, $mappingContactType, $mappingLocation, $mappingPhoneType, $mappingRelation) = CRM_Core_BAO_Mapping
::getMappingFields($savedMapping);
122 $mappingName = $mappingName[1];
123 $mappingContactType = $mappingContactType[1];
124 $mappingLocation = CRM_Utils_Array
::value('1', CRM_Utils_Array
::value(1, $mappingLocation));
125 $mappingPhoneType = CRM_Utils_Array
::value('1', CRM_Utils_Array
::value(1, $mappingPhoneType));
126 $mappingRelation = CRM_Utils_Array
::value('1', CRM_Utils_Array
::value(1, $mappingRelation));
128 //mapping is to be loaded from database
130 $params = array('id' => $savedMapping);
132 $mappingDetails = CRM_Core_BAO_Mapping
::retrieve($params, $temp);
134 $this->assign('loadedMapping', $mappingDetails->name
);
135 $this->set('loadedMapping', $savedMapping);
137 $getMappingName = new CRM_Core_DAO_Mapping();
138 $getMappingName->id
= $savedMapping;
139 $getMappingName->mapping_type
= 'Import Contributions';
140 $getMappingName->find();
141 while ($getMappingName->fetch()) {
142 $mapperName = $getMappingName->name
;
145 $this->assign('savedName', $mapperName);
147 $this->add('hidden', 'mappingId', $savedMapping);
149 $this->addElement('checkbox', 'updateMapping', ts('Update this field mapping'), NULL);
150 $saveDetailsName = ts('Save as a new field mapping');
151 $this->add('text', 'saveMappingName', ts('Name'));
152 $this->add('text', 'saveMappingDesc', ts('Description'));
155 $this->addElement('checkbox', 'saveMapping', $saveDetailsName, NULL, array('onclick' => "showSaveDetails(this)"));
157 $this->addFormRule(array('CRM_Contribute_Import_Form_MapField', 'formRule'), $this);
159 //-------- end of saved mapping stuff ---------
162 $mapperKeys = array_keys($this->_mapperFields
);
163 $hasHeaders = !empty($this->_columnHeaders
);
164 $headerPatterns = $this->get('headerPatterns');
165 $dataPatterns = $this->get('dataPatterns');
166 $hasLocationTypes = $this->get('fieldTypes');
168 /* Initialize all field usages to false */
170 foreach ($mapperKeys as $key) {
171 $this->_fieldUsed
[$key] = FALSE;
173 $this->_location_types
= CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
174 $sel1 = $this->_mapperFields
;
176 if (!$this->get('onDuplicate')) {
178 unset($sel1['contribution_id']);
181 // start of soft credit section
182 // get contact type for this import
183 $contactTypeId = $this->get('contactType');
184 $contactTypes = array(
185 CRM_Import_Parser
::CONTACT_INDIVIDUAL
=> 'Individual',
186 CRM_Import_Parser
::CONTACT_HOUSEHOLD
=> 'Household',
187 CRM_Import_Parser
::CONTACT_ORGANIZATION
=> 'Organization',
190 $contactType = $contactTypes[$contactTypeId];
192 // get importable fields for contact type
193 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
195 // get the Dedupe rule for this contact type and build soft credit array
197 'contact_type' => $contactType,
198 'used' => 'Unsupervised',
200 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
201 $softCreditFields = array();
202 if (is_array($fieldsArray)) {
203 foreach ($fieldsArray as $value) {
204 //skip if there is no dupe rule
205 if ($value == 'none') {
208 $softCreditFields[$value] = $contactFields[trim($value)]['title'];
212 $softCreditFields['contact_id'] = ts('Contact ID');
213 $softCreditFields['external_identifier'] = ts('External Identifier');
215 $sel2['soft_credit'] = $softCreditFields;
217 // end of soft credit section
219 $js = "<script type='text/javascript'>\n";
220 $formName = 'document.forms.' . $this->_name
;
222 //used to warn for mismatch column count or mismatch mapping
225 for ($i = 0; $i < $this->_columnCount
; $i++
) {
226 $sel = & $this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
228 if ($this->get('savedMapping')) {
229 if (isset($mappingName[$i])) {
230 if ($mappingName[$i] != ts('- do not import -')) {
232 $mappingHeader = array_keys($this->_mapperFields
, $mappingName[$i]);
233 // reusing contact_type field array for soft credit
234 $softField = isset($mappingContactType[$i]) ?
$mappingContactType[$i] : 0;
237 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
240 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
241 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
242 $defaults["mapper[$i]"] = array(
243 CRM_Utils_Array
::value(0, $mappingHeader),
244 ($softField) ?
$softField : "",
245 (isset($locationId)) ?
$locationId : "",
246 (isset($phoneType)) ?
$phoneType : "",
251 $defaults["mapper[$i]"] = array();
254 for ($k = 1; $k < 4; $k++
) {
255 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
260 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
261 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
264 $defaults["mapper[$i]"] = array($this->defaultFromHeader($this->_columnHeaders
[$i], $headerPatterns));
267 $defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
270 //end of load mapping
273 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
275 // Infer the default from the skipped headers if we have them
276 $defaults["mapper[$i]"] = array(
277 $this->defaultFromHeader(CRM_Utils_Array
::value($i, $this->_columnHeaders
),
280 // $defaultLocationType->id
285 // Otherwise guess the default from the form of the data
286 $defaults["mapper[$i]"] = array(
287 $this->defaultFromData($dataPatterns, $i),
288 // $defaultLocationType->id
293 $sel->setOptions(array($sel1, $sel2, (isset($sel3)) ?
$sel3 : "", (isset($sel4)) ?
$sel4 : ""));
295 $js .= "</script>\n";
296 $this->assign('initHideBoxes', $js);
298 //set warning if mismatch in more than
299 if (isset($mappingName)) {
300 if (($this->_columnCount
!= count($mappingName))) {
304 if ($warning != 0 && $this->get('savedMapping')) {
305 $session = CRM_Core_Session
::singleton();
306 $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.'));
309 $session = CRM_Core_Session
::singleton();
310 $session->setStatus(NULL);
313 $this->setDefaults($defaults);
315 $this->addButtons(array(
318 'name' => ts('<< Previous'),
322 'name' => ts('Continue >>'),
323 'spacing' => ' ',
328 'name' => ts('Cancel'),
335 * global validation rules for the form
337 * @param array $fields posted values of the form
339 * @return array list of errors to be posted back to the form
343 static function formRule($fields, $files, $self) {
345 $fieldMessage = NULL;
347 if (!array_key_exists('savedMapping', $fields)) {
348 $importKeys = array();
349 foreach ($fields['mapper'] as $mapperPart) {
350 $importKeys[] = $mapperPart[0];
353 $contactTypeId = $self->get('contactType');
354 $contactTypes = array(
355 CRM_Import_Parser
::CONTACT_INDIVIDUAL
=> 'Individual',
356 CRM_Import_Parser
::CONTACT_HOUSEHOLD
=> 'Household',
357 CRM_Import_Parser
::CONTACT_ORGANIZATION
=> 'Organization',
360 'used' => 'Unsupervised',
361 'contact_type' => $contactTypes[$contactTypeId],
363 list($ruleFields, $threshold) = CRM_Dedupe_BAO_RuleGroup
::dedupeRuleFieldsWeight($params);
365 foreach ($importKeys as $key => $val) {
366 if (array_key_exists($val, $ruleFields)) {
367 $weightSum +
= $ruleFields[$val];
370 foreach ($ruleFields as $field => $weight) {
371 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
374 // FIXME: should use the schema titles, not redeclare them
375 $requiredFields = array(
376 'contribution_contact_id' => ts('Contact ID'),
377 'total_amount' => ts('Total Amount'),
378 'financial_type' => ts('Financial Type')
381 foreach ($requiredFields as $field => $title) {
382 if (!in_array($field, $importKeys)) {
383 if ($field == 'contribution_contact_id') {
384 if (!($weightSum >= $threshold ||
in_array('external_identifier', $importKeys)) &&
385 $self->_onDuplicate
!= CRM_Import_Parser
::DUPLICATE_UPDATE
387 $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(
391 elseif ($self->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_UPDATE
&&
392 !(in_array('invoice_id', $importKeys) ||
in_array('trxn_id', $importKeys) ||
393 in_array('contribution_id', $importKeys)
396 $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 />';
400 if ($self->_onDuplicate
!= CRM_Import_Parser
::DUPLICATE_UPDATE
) {
401 $errors['_qf_default'] .= ts('Missing required field: %1', array(
409 //at least one field should be mapped during update.
410 if ($self->_onDuplicate
== CRM_Import_Parser
::DUPLICATE_UPDATE
) {
412 foreach ($self->_mapperFields
as $key => $field) {
413 if (in_array($key, $importKeys) &&
414 !in_array($key, array('doNotImport', 'contribution_id', 'invoice_id', 'trxn_id'))
421 $errors['_qf_default'] .= ts('At least one contribution field needs to be mapped for update during update mode.') . '<br />';
426 if (!empty($fields['saveMapping'])) {
427 $nameField = CRM_Utils_Array
::value('saveMappingName', $fields);
428 if (empty($nameField)) {
429 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
432 $mappingTypeId = CRM_Core_OptionGroup
::getValue('mapping_type', 'Import Contribution', 'name');
433 if (CRM_Core_BAO_Mapping
::checkMapping($nameField, $mappingTypeId)) {
434 $errors['saveMappingName'] = ts('Duplicate Import Contribution Mapping Name');
439 if (!empty($errors)) {
440 if (!empty($errors['saveMappingName'])) {
442 $assignError = new CRM_Core_Page();
443 $assignError->assign('mappingDetailsError', $_flag);
452 * Process the mapped fields and map it into the uploaded file
453 * preview the file and extract some summary statistics
458 public function postProcess() {
459 $params = $this->controller
->exportValues('MapField');
461 //reload the mapfield if load mapping is pressed
462 if (!empty($params['savedMapping'])) {
463 $this->set('savedMapping', $params['savedMapping']);
464 $this->controller
->resetPage($this->_name
);
468 $fileName = $this->controller
->exportValue('DataSource', 'uploadFile');
469 $skipColumnHeader = $this->controller
->exportValue('DataSource', 'skipColumnHeader');
471 $config = CRM_Core_Config
::singleton();
472 $seperator = $config->fieldSeparator
;
474 $mapper = $mapperKeys = $mapperKeysMain = $mapperSoftCredit = $softCreditFields = $mapperPhoneType = array();
475 $mapperKeys = $this->controller
->exportValue($this->_name
, 'mapper');
477 for ($i = 0; $i < $this->_columnCount
; $i++
) {
478 $mapper[$i] = $this->_mapperFields
[$mapperKeys[$i][0]];
479 $mapperKeysMain[$i] = $mapperKeys[$i][0];
481 if (isset($mapperKeys[$i][0]) && $mapperKeys[$i][0] == 'soft_credit') {
482 $mapperSoftCredit[$i] = $mapperKeys[$i][1];
483 list($first, $second) = explode('_', $mapperSoftCredit[$i]);
484 $softCreditFields[$i] = ucwords($first . " " . $second);
487 $mapperSoftCredit[$i] = $softCreditFields[$i] = NULL;
488 $softCreditFields[$i] = NULL;
492 $this->set('mapper', $mapper);
493 $this->set('softCreditFields', $softCreditFields);
495 // store mapping Id to display it in the preview page
496 $this->set('loadMappingId', CRM_Utils_Array
::value('mappingId', $params));
498 //Updating Mapping Records
499 if (!empty($params['updateMapping'])) {
500 $mappingFields = new CRM_Core_DAO_MappingField();
501 $mappingFields->mapping_id
= $params['mappingId'];
502 $mappingFields->find();
504 $mappingFieldsId = array();
505 while ($mappingFields->fetch()) {
506 if ($mappingFields->id
) {
507 $mappingFieldsId[$mappingFields->column_number
] = $mappingFields->id
;
511 for ($i = 0; $i < $this->_columnCount
; $i++
) {
512 $updateMappingFields = new CRM_Core_DAO_MappingField();
513 $updateMappingFields->id
= $mappingFieldsId[$i];
514 $updateMappingFields->mapping_id
= $params['mappingId'];
515 $updateMappingFields->column_number
= $i;
516 $updateMappingFields->name
= $mapper[$i];
518 //reuse contact_type field in db to store fields associated with soft credit
519 $updateMappingFields->contact_type
= isset($mapperSoftCredit[$i]) ?
$mapperSoftCredit[$i] : NULL;
520 $updateMappingFields->save();
524 //Saving Mapping Details and Records
525 if (!empty($params['saveMapping'])) {
526 $mappingParams = array(
527 'name' => $params['saveMappingName'],
528 'description' => $params['saveMappingDesc'],
529 'mapping_type_id' => CRM_Core_OptionGroup
::getValue('mapping_type',
530 'Import Contribution',
534 $saveMapping = CRM_Core_BAO_Mapping
::add($mappingParams);
536 for ($i = 0; $i < $this->_columnCount
; $i++
) {
537 $saveMappingFields = new CRM_Core_DAO_MappingField();
538 $saveMappingFields->mapping_id
= $saveMapping->id
;
539 $saveMappingFields->column_number
= $i;
540 $saveMappingFields->name
= $mapper[$i];
542 //reuse contact_type field in db to store fields associated with soft credit
543 $saveMappingFields->contact_type
= isset($mapperSoftCredit[$i]) ?
$mapperSoftCredit[$i] : NULL;
544 $saveMappingFields->save();
546 $this->set('savedMapping', $saveMappingFields->mapping_id
);
549 $parser = new CRM_Contribute_Import_Parser_Contribution($mapperKeysMain, $mapperSoftCredit, $mapperPhoneType);
550 $parser->run($fileName, $seperator, $mapper, $skipColumnHeader,
551 CRM_Import_Parser
::MODE_PREVIEW
, $this->get('contactType')
554 // add all the necessary variables to the form