Membership form flow tidy-up
[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 * Build the form object.
25 *
26 * @return void
27 */
28 public function buildQuickForm() {
29 $this->buildSavedMappingFields($this->getSubmittedValue('savedMapping'));
30 $this->addFormRule(array('CRM_Member_Import_Form_MapField', 'formRule'), $this);
31
32 //-------- end of saved mapping stuff ---------
33
34 $defaults = [];
35 $mapperKeys = array_keys($this->_mapperFields);
36 $columnHeaders = $this->getColumnHeaders();
37 $hasHeaders = $this->getSubmittedValue('skipColumnHeader');
38 $headerPatterns = $this->getHeaderPatterns();
39 $dataPatterns = $this->getDataPatterns();
40
41 /* Initialize all field usages to false */
42
43 foreach ($mapperKeys as $key) {
44 $this->_fieldUsed[$key] = FALSE;
45 }
46 $this->_location_types = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
47 $sel1 = $this->_mapperFields;
48 if (!$this->getSubmittedValue('onDuplicate')) {
49 unset($sel1['id']);
50 unset($sel1['membership_id']);
51 }
52
53 $sel2[''] = NULL;
54
55 $js = "<script type='text/javascript'>\n";
56 $formName = 'document.forms.' . $this->_name;
57
58 //used to warn for mismatch column count or mismatch mapping
59 $warning = 0;
60
61 foreach ($columnHeaders as $i => $columnHeader) {
62 $sel = &$this->addElement('hierselect', "mapper[$i]", ts('Mapper for Field %1', array(1 => $i)), NULL);
63 $jsSet = FALSE;
64 if ($this->get('savedMapping')) {
65 if (isset($mappingName[$i])) {
66 if ($mappingName[$i] != ts('do_not_import')) {
67 //When locationType is not set
68 $js .= "{$formName}['mapper[$i][1]'].style.display = 'none';\n";
69
70 //When phoneType is not set
71 $js .= "{$formName}['mapper[$i][2]'].style.display = 'none';\n";
72
73 $js .= "{$formName}['mapper[$i][3]'].style.display = 'none';\n";
74
75 $defaults["mapper[$i]"] = [$mappingName[$i]];
76 $jsSet = TRUE;
77 }
78 else {
79 $defaults["mapper[$i]"] = [];
80 }
81 if (!$jsSet) {
82 for ($k = 1; $k < 4; $k++) {
83 $js .= "{$formName}['mapper[$i][$k]'].style.display = 'none';\n";
84 }
85 }
86 }
87 else {
88 // this load section to help mapping if we ran out of saved columns when doing Load Mapping
89 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
90
91 if ($hasHeaders) {
92 $defaults["mapper[$i]"] = array($this->defaultFromHeader($columnHeader, $headerPatterns));
93 }
94 else {
95 $defaults["mapper[$i]"] = array($this->defaultFromData($dataPatterns, $i));
96 }
97 }
98 //end of load mapping
99 }
100 else {
101 $js .= "swapOptions($formName, 'mapper[$i]', 0, 3, 'hs_mapper_" . $i . "_');\n";
102 if ($this->getSubmittedValue('skipColumnHeader')) {
103 // Infer the default from the skipped headers if we have them
104 $defaults["mapper[$i]"] = array(
105 $this->defaultFromHeader($columnHeader,
106 $headerPatterns
107 ),
108 // $defaultLocationType->id
109 0,
110 );
111 }
112 else {
113 // Otherwise guess the default from the form of the data
114 $defaults["mapper[$i]"] = array(
115 $this->defaultFromData($dataPatterns, $i),
116 // $defaultLocationType->id
117 0,
118 );
119 }
120 }
121 $sel->setOptions(array($sel1, $sel2, (isset($sel3)) ? $sel3 : "", (isset($sel4)) ? $sel4 : ""));
122 }
123 $js .= "</script>\n";
124 $this->assign('initHideBoxes', $js);
125
126 //set warning if mismatch in more than
127 if (isset($mappingName)) {
128 if (($this->_columnCount != count($mappingName))) {
129 $warning++;
130 }
131 }
132 if ($warning != 0 && $this->get('savedMapping')) {
133 $session = CRM_Core_Session::singleton();
134 $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.'));
135 }
136 else {
137 $session = CRM_Core_Session::singleton();
138 $session->setStatus(NULL);
139 }
140
141 $this->setDefaults($defaults);
142
143 $this->addButtons(array(
144 array(
145 'type' => 'back',
146 'name' => ts('Previous'),
147 ),
148 array(
149 'type' => 'next',
150 'name' => ts('Continue'),
151 'spacing' => '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
152 'isDefault' => TRUE,
153 ),
154 array(
155 'type' => 'cancel',
156 'name' => ts('Cancel'),
157 ),
158 ));
159 }
160
161 /**
162 * Global validation rules for the form.
163 *
164 * @param array $fields
165 * Posted values of the form.
166 *
167 * @param $files
168 * @param self $self
169 *
170 * @return array
171 * list of errors to be posted back to the form
172 */
173 public static function formRule($fields, $files, $self) {
174 $errors = [];
175
176 $importKeys = [];
177 foreach ($fields['mapper'] as $mapperPart) {
178 $importKeys[] = $mapperPart[0];
179 }
180 // FIXME: should use the schema titles, not redeclare them
181 $requiredFields = array(
182 'membership_contact_id' => ts('Contact ID'),
183 'membership_type_id' => ts('Membership Type'),
184 'membership_start_date' => ts('Membership Start Date'),
185 );
186 $params = array(
187 'used' => 'Unsupervised',
188 'contact_type' => $self->getContactType(),
189 );
190 [$ruleFields, $threshold] = CRM_Dedupe_BAO_DedupeRuleGroup::dedupeRuleFieldsWeight($params);
191 $weightSum = 0;
192 foreach ($importKeys as $key => $val) {
193 if (array_key_exists($val, $ruleFields)) {
194 $weightSum += $ruleFields[$val];
195 }
196 }
197 $fieldMessage = '';
198 foreach ($ruleFields as $field => $weight) {
199 $fieldMessage .= ' ' . $field . '(weight ' . $weight . ')';
200 }
201
202 foreach ($requiredFields as $field => $title) {
203 if (!in_array($field, $importKeys)) {
204 if ($field == 'membership_contact_id') {
205 if ((($weightSum >= $threshold || in_array('external_identifier', $importKeys)) &&
206 $self->getSubmittedValue('onDuplicate') != CRM_Import_Parser::DUPLICATE_UPDATE
207 ) ||
208 in_array('membership_id', $importKeys)
209 ) {
210 continue;
211 }
212 else {
213 if (!isset($errors['_qf_default'])) {
214 $errors['_qf_default'] = '';
215 }
216 $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(
217 1 => $threshold,
218 )) . ' ' . ts('(OR Membership ID if update mode.)') . '<br />';
219 }
220 }
221 else {
222 if (!isset($errors['_qf_default'])) {
223 $errors['_qf_default'] = '';
224 }
225 $errors['_qf_default'] .= ts('Missing required field: %1', array(
226 1 => $title,
227 )) . '<br />';
228 }
229 }
230 }
231
232 if (!empty($fields['saveMapping'])) {
233 $nameField = $fields['saveMappingName'] ?? NULL;
234 if (empty($nameField)) {
235 $errors['saveMappingName'] = ts('Name is required to save Import Mapping');
236 }
237 else {
238 if (CRM_Core_BAO_Mapping::checkMapping($nameField, CRM_Core_PseudoConstant::getKey('CRM_Core_BAO_Mapping', 'mapping_type_id', 'Import Membership'))) {
239 $errors['saveMappingName'] = ts('Duplicate Import Membership Mapping Name');
240 }
241 }
242 }
243
244 if (!empty($errors)) {
245 if (!empty($errors['saveMappingName'])) {
246 $_flag = 1;
247 $assignError = new CRM_Core_Page();
248 $assignError->assign('mappingDetailsError', $_flag);
249 }
250 return $errors;
251 }
252
253 return TRUE;
254 }
255
256 /**
257 * Get the mapping name per the civicrm_mapping_field.type_id option group.
258 *
259 * @return string
260 */
261 public function getMappingTypeName(): string {
262 return 'Import Membership';
263 }
264
265 /**
266 * @return \CRM_Member_Import_Parser_Membership
267 */
268 protected function getParser(): CRM_Member_Import_Parser_Membership {
269 if (!$this->parser) {
270 $this->parser = new CRM_Member_Import_Parser_Membership();
271 $this->parser->setUserJobID($this->getUserJobID());
272 $this->parser->init();
273 }
274 return $this->parser;
275 }
276
277 /**
278 * Get the fields to be highlighted in the UI.
279 *
280 * @return array
281 * @throws \CRM_Core_Exception
282 */
283 protected function getHighlightedFields(): array {
284 $highlightedFields = [];
285 //CRM-2219 removing other required fields since for updation only
286 //membership id is required.
287 if ($this->getSubmittedValue('onDuplicate') == CRM_Import_Parser::DUPLICATE_UPDATE) {
288 $remove = [
289 'membership_contact_id',
290 'email',
291 'first_name',
292 'last_name',
293 'external_identifier',
294 ];
295 foreach ($remove as $value) {
296 unset($this->_mapperFields[$value]);
297 }
298 $highlightedFieldsArray = [
299 'membership_id',
300 'membership_start_date',
301 'membership_type_id',
302 ];
303 foreach ($highlightedFieldsArray as $name) {
304 $highlightedFields[] = $name;
305 }
306 }
307 elseif ($this->getSubmittedValue('onDuplicate') == CRM_Import_Parser::DUPLICATE_SKIP) {
308 unset($this->_mapperFields['membership_id']);
309 $highlightedFieldsArray = [
310 'membership_contact_id',
311 'email',
312 'external_identifier',
313 'membership_start_date',
314 'membership_type_id',
315 ];
316 foreach ($highlightedFieldsArray as $name) {
317 $highlightedFields[] = $name;
318 }
319 }
320 return $highlightedFields;
321 }
322
323 }