Merge pull request #10782 from JMAConsulting/CRM-20947
[civicrm-core.git] / CRM / Batch / Form / Entry.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
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
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
6a488035
TO
32 */
33
34/**
ce064e4f 35 * This class provides the functionality for batch entry for contributions/memberships.
6a488035
TO
36 */
37class CRM_Batch_Form_Entry extends CRM_Core_Form {
38
39 /**
eceb18cc 40 * Maximum profile fields that will be displayed.
6a488035
TO
41 */
42 protected $_rowCount = 1;
43
44 /**
eceb18cc 45 * Batch id.
6a488035
TO
46 */
47 protected $_batchId;
48
49 /**
eceb18cc 50 * Batch information.
6a488035
TO
51 */
52 protected $_batchInfo = array();
53
54 /**
eceb18cc 55 * Store the profile id associated with the batch type.
6a488035
TO
56 */
57 protected $_profileId;
58
59 public $_action;
8ef12e64 60
6a488035
TO
61 public $_mode;
62
63 public $_params;
64
6a488035 65 /**
fe482240 66 * When not to reset sort_name.
6a488035
TO
67 */
68 protected $_preserveDefault = TRUE;
69
70 /**
0880a9d0 71 * Contact fields.
6a488035
TO
72 */
73 protected $_contactFields = array();
74
afe349ef 75 /**
0880a9d0 76 * Fields array of fields in the batch profile.
afe349ef 77 * (based on the uf_field table data)
78 * (this can't be protected as it is passed into the CRM_Contact_Form_Task_Batch::parseStreetAddress function
79 * (although a future refactoring might hopefully change that so it uses the api & the function is not
80 * required
81 * @var array
82 */
83 public $_fields = array();
353ffa53 84
6a488035 85 /**
eceb18cc 86 * Build all the data structures needed to build the form.
8ef12e64 87 */
00be9182 88 public function preProcess() {
6a488035
TO
89 $this->_batchId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
90
91 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
8ef12e64 92
6a488035
TO
93 if (empty($this->_batchInfo)) {
94 $params = array('id' => $this->_batchId);
95 CRM_Batch_BAO_Batch::retrieve($params, $this->_batchInfo);
96
57465e2a 97 $this->assign('batchTotal', !empty($this->_batchInfo['total']) ? $this->_batchInfo['total'] : NULL);
6a488035
TO
98 $this->assign('batchType', $this->_batchInfo['type_id']);
99
100 // get the profile id associted with this batch type
101 $this->_profileId = CRM_Batch_BAO_Batch::getProfileId($this->_batchInfo['type_id']);
102 }
aefb0b79 103 CRM_Core_Resources::singleton()
353ffa53
TO
104 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
105 ->addSetting(array('batch' => array('type_id' => $this->_batchInfo['type_id'])))
106 ->addSetting(array('setting' => array('monetaryThousandSeparator' => CRM_Core_Config::singleton()->monetaryThousandSeparator)))
107 ->addSetting(array('setting' => array('monetaryDecimalPoint' => CRM_Core_Config::singleton()->monetaryDecimalPoint)));
111f65f4 108
6a488035
TO
109 }
110
cbd44e94 111 /**
bf48aa29 112 * Set Batch ID.
113 *
114 * @param int $id
cbd44e94 115 */
123fe8fe 116 public function setBatchID($id) {
117 $this->_batchId = $id;
118 }
119
6a488035 120 /**
eceb18cc 121 * Build the form object.
6a488035 122 */
00be9182 123 public function buildQuickForm() {
6a488035
TO
124 if (!$this->_profileId) {
125 CRM_Core_Error::fatal(ts('Profile for bulk data entry is missing.'));
126 }
127
128 $this->addElement('hidden', 'batch_id', $this->_batchId);
129
691df66d 130 $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
6a488035 131 // get the profile information
d556e751 132 if ($this->_batchInfo['type_id'] == $batchTypes['Contribution']) {
6a488035
TO
133 CRM_Utils_System::setTitle(ts('Batch Data Entry for Contributions'));
134 $customFields = CRM_Core_BAO_CustomField::getFields('Contribution');
135 }
691df66d 136 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
6a488035
TO
137 CRM_Utils_System::setTitle(ts('Batch Data Entry for Memberships'));
138 $customFields = CRM_Core_BAO_CustomField::getFields('Membership');
139 }
691df66d
TO
140 elseif ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
141 CRM_Utils_System::setTitle(ts('Batch Data Entry for Pledge Payments'));
142 $customFields = CRM_Core_BAO_CustomField::getFields('Contribution');
143 }
6a488035
TO
144 $this->_fields = array();
145 $this->_fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, CRM_Core_Action::VIEW);
146
147 // remove file type field and then limit fields
148 $suppressFields = FALSE;
149 $removehtmlTypes = array('File', 'Autocomplete-Select');
150 foreach ($this->_fields as $name => $field) {
151 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) &&
152 in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
153 ) {
154 $suppressFields = TRUE;
155 unset($this->_fields[$name]);
156 }
157
158 //fix to reduce size as we are using this field in grid
159 if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) {
160 //shrink class to "form-text-medium"
161 $this->_fields[$name]['attributes']['size'] = 19;
162 }
163 }
164
165 $this->addFormRule(array('CRM_Batch_Form_Entry', 'formRule'), $this);
166
167 // add the force save button
168 $forceSave = $this->getButtonName('upload', 'force');
169
170 $this->addElement('submit',
171 $forceSave,
172 ts('Ignore Mismatch & Process the Batch?')
173 );
174
175 $this->addButtons(array(
176 array(
177 'type' => 'upload',
178 'name' => ts('Validate & Process the Batch'),
21dfd5f5 179 'isDefault' => TRUE,
6a488035
TO
180 ),
181 array(
182 'type' => 'cancel',
183 'name' => ts('Save & Continue Later'),
21dfd5f5 184 ),
6a488035
TO
185 )
186 );
187
188 $this->assign('rowCount', $this->_batchInfo['item_count'] + 1);
189
190 $fileFieldExists = FALSE;
191 $preserveDefaultsArray = array(
353ffa53
TO
192 'first_name',
193 'last_name',
194 'middle_name',
6a488035
TO
195 'organization_name',
196 'household_name',
197 );
198
199 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
70223980 200 $contactReturnProperties = array();
00f6e1a8 201 $config = CRM_Core_Config::singleton();
5056dc8e 202
6a488035 203 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
353ffa53
TO
204 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', array(
205 'create' => TRUE,
acb1052e 206 'placeholder' => ts('- select -'),
353ffa53 207 ));
6a488035
TO
208
209 // special field specific to membership batch udpate
210 if ($this->_batchInfo['type_id'] == 2) {
211 $options = array(
212 1 => ts('Add Membership'),
213 2 => ts('Renew Membership'),
214 );
215 $this->add('select', "member_option[$rowNumber]", '', $options);
216 }
00f6e1a8 217 if ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
691df66d 218 $options = array('' => '-select-');
04e6444d 219 $optionTypes = array(
220 '1' => ts('Adjust Pledge Payment Schedule?'),
221 '2' => ts('Adjust Total Pledge Amount?'),
222 );
8e2b1206 223 $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes);
224 if (!empty($this->_batchId) && !empty($this->_batchInfo['data']) && !empty($rowNumber)) {
225 $dataValues = json_decode($this->_batchInfo['data'], TRUE);
5542b7c2 226 if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) {
227 $pledgeIDs = CRM_Pledge_BAO_Pledge::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]);
228 foreach ($pledgeIDs as $pledgeID) {
229 $pledgePayment = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeID);
5056dc8e 230 $options += array($pledgeID => CRM_Utils_Date::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']);
5542b7c2 231 }
8e2b1206 232 }
233 }
5056dc8e 234
b8e805eb 235 $this->add('select', "open_pledges[$rowNumber]", '', $options);
691df66d 236 }
8e2b1206 237
6a488035
TO
238 foreach ($this->_fields as $name => $field) {
239 if (in_array($field['field_type'], $contactTypes)) {
57465e2a 240 $fld = explode('-', $field['name']);
5b1666f7 241 $contactReturnProperties[$field['name']] = $fld[0];
6a488035
TO
242 }
243 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
244
245 if (in_array($field['name'], $preserveDefaultsArray)) {
246 $this->_preserveDefault = FALSE;
247 }
248 }
249 }
75140351 250
3f8a2e90 251 // CRM-19477: Display Error for Batch Sizes Exceeding php.ini max_input_vars
252 // Notes: $this->_elementIndex gives an approximate count of the variables being sent
75140351 253 // An offset value is set to deal with additional vars that are likely passed.
3f8a2e90 254 // There may be a more accurate way to do this...
49accad3 255 $offset = 50; // set an offset to account for other vars we are not counting
75140351 256 if ((count($this->_elementIndex) + $offset) > ini_get("max_input_vars")) {
257 CRM_Core_Error::fatal(ts('Batch size is too large. Increase value of php.ini setting "max_input_vars" (current val = ' . ini_get("max_input_vars") . ')'));
49accad3 258 }
75140351 259
6a488035 260 $this->assign('fields', $this->_fields);
57465e2a 261 CRM_Core_Resources::singleton()
353ffa53
TO
262 ->addSetting(array(
263 'contact' => array(
264 'return' => implode(',', $contactReturnProperties),
265 'fieldmap' => array_flip($contactReturnProperties),
acb1052e 266 ),
353ffa53 267 ));
6a488035
TO
268
269 // don't set the status message when form is submitted.
270 $buttonName = $this->controller->getButtonName('submit');
271
272 if ($suppressFields && $buttonName != '_qf_Entry_next') {
ec5b3633 273 CRM_Core_Session::setStatus(ts("File or Autocomplete-Select type field(s) in the selected profile are not supported for Update multiple records."), ts('Some Fields Excluded'), 'info');
6a488035
TO
274 }
275 }
276
277 /**
eceb18cc 278 * Form validations.
6a488035 279 *
82d480a5
TO
280 * @param array $params
281 * Posted values of the form.
282 * @param array $files
283 * List of errors to be posted back to the form.
1620f0bc 284 * @param \CRM_Batch_Form_Entry $self
82d480a5 285 * Form object.
6a488035 286 *
a6c01b45
CW
287 * @return array
288 * list of errors to be posted back to the form
6a488035 289 */
00be9182 290 public static function formRule($params, $files, $self) {
6a488035 291 $errors = array();
5056dc8e 292 $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
dddb4c8c 293 $fields = array(
4db803dd
CW
294 'total_amount' => ts('Amount'),
295 'financial_type' => ts('Financial Type'),
296 'payment_instrument' => ts('Payment Method'),
dddb4c8c 297 );
6a488035 298
0576b84b
SB
299 //CRM-16480 if contact is selected, validate financial type and amount field.
300 foreach ($params['field'] as $key => $value) {
47087bdc 301 if (isset($value['trxn_id'])) {
302 if (0 < CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', array(1 => array($value['trxn_id'], 'String')))) {
303 $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database');
304 }
305 }
61f45887 306 foreach ($fields as $field => $label) {
dddb4c8c 307 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
ef0c5805 308 $errors["field[$key][$field]"] = ts('%1 is a required field.', array(1 => $label));
dddb4c8c 309 }
0576b84b
SB
310 }
311 }
312
a7488080 313 if (!empty($params['_qf_Entry_upload_force'])) {
0576b84b
SB
314 if (!empty($errors)) {
315 return $errors;
316 }
6a488035
TO
317 return TRUE;
318 }
319
320 $batchTotal = 0;
321 foreach ($params['field'] as $key => $value) {
322 $batchTotal += $value['total_amount'];
323
5ee60152 324 //validate for soft credit fields
ccec9d6b 325 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
d1401e86 326 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
5ee60152 327 }
8cc574cf 328 if (!empty($params['soft_credit_amount']) && !empty($params['soft_credit_amount'][$key]) && CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value($key, $params['soft_credit_amount'])) > CRM_Utils_Rule::cleanMoney($value['total_amount'])) {
5ee60152
RN
329 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
330 }
8ef12e64 331
6a488035 332 //membership type is required for membership batch entry
5056dc8e 333 if ($self->_batchInfo['type_id'] == $batchTypes['Membership']) {
a7488080 334 if (empty($value['membership_type'][1])) {
6a488035
TO
335 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
336 }
337 }
338 }
b8e805eb 339 if ($self->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
5056dc8e 340 foreach (array_unique($params["open_pledges"]) as $value) {
42724136 341 if (!empty($value)) {
342 $duplicateRows = array_keys($params["open_pledges"], $value);
343 }
344 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
5056dc8e 345 foreach ($duplicateRows as $key) {
7f6a92ef 346 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
5056dc8e 347 }
348 }
349 }
350 }
28e8aa1b 351 if ((string) $batchTotal != $self->_batchInfo['total']) {
6a488035
TO
352 $self->assign('batchAmountMismatch', TRUE);
353 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
354 }
355
356 if (!empty($errors)) {
357 return $errors;
358 }
359
360 $self->assign('batchAmountMismatch', FALSE);
361 return TRUE;
362 }
363
364 /**
eceb18cc 365 * Override default cancel action.
6a488035 366 */
00be9182 367 public function cancelAction() {
6a488035
TO
368 // redirect to batch listing
369 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
370 CRM_Utils_System::civiExit();
371 }
372
373 /**
c490a46a 374 * Set default values for the form.
6a488035 375 */
00be9182 376 public function setDefaultValues() {
6a488035
TO
377 if (empty($this->_fields)) {
378 return;
379 }
380
381 // for add mode set smart defaults
481a74f4 382 if ($this->_action & CRM_Core_Action::ADD) {
3d927ee7 383 $currentDate = date('Y-m-d H-i-s');
6a488035 384
363544d7 385 $completeStatus = CRM_Contribute_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
8ef12e64 386 $specialFields = array(
04b40eab 387 'join_date' => date('Y-m-d'),
6a488035 388 'receive_date' => $currentDate,
21dfd5f5 389 'contribution_status_id' => $completeStatus,
6a488035
TO
390 );
391
392 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
481a74f4 393 foreach ($specialFields as $key => $value) {
8ef12e64 394 $defaults['field'][$rowNumber][$key] = $value;
6a488035 395 }
8ef12e64 396 }
6a488035
TO
397 }
398 else {
6c97864e 399 // get the cached info from data column of civicrm_batch
400 $data = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId, 'data');
401 $defaults = json_decode($data, TRUE);
c0d307ec 402 $defaults = $defaults['values'];
6a488035 403 }
6c97864e 404
6a488035
TO
405 return $defaults;
406 }
407
408 /**
eceb18cc 409 * Process the form after the input has been submitted and validated.
6a488035
TO
410 */
411 public function postProcess() {
412 $params = $this->controller->exportValues($this->_name);
6a488035 413 $params['actualBatchTotal'] = 0;
d556e751 414
415 // get the profile information
04b40eab 416 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
00f6e1a8 417 if (in_array($this->_batchInfo['type_id'], array($batchTypes['Pledge Payment'], $batchTypes['Contribution']))) {
6a488035
TO
418 $this->processContribution($params);
419 }
d556e751 420 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
6a488035
TO
421 $this->processMembership($params);
422 }
d556e751 423
6a488035
TO
424 // update batch to close status
425 $paramValues = array(
426 'id' => $this->_batchId,
427 // close status
1a453756 428 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'),
6a488035
TO
429 'total' => $params['actualBatchTotal'],
430 );
431
432 CRM_Batch_BAO_Batch::create($paramValues);
433
6a488035
TO
434 // set success status
435 CRM_Core_Session::setStatus("", ts("Batch Processed."), "success");
436
437 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
438 }
439
440 /**
eceb18cc 441 * Process contribution records.
6a488035 442 *
82d480a5
TO
443 * @param array $params
444 * Associated array of submitted values.
6a488035 445 *
ce064e4f 446 * @return bool
6a488035
TO
447 */
448 private function processContribution(&$params) {
6a488035
TO
449
450 // get the price set associated with offline contribution record.
9da8dc8c 451 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
452 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
85020e43
EM
453 $priceFieldID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldID($this->_priceSet);
454 $priceFieldValueID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldValueID($this->_priceSet);
6a488035 455
6a488035
TO
456 if (isset($params['field'])) {
457 foreach ($params['field'] as $key => $value) {
458 // if contact is not selected we should skip the row
ccec9d6b 459 if (empty($params['primary_contact_id'][$key])) {
6a488035
TO
460 continue;
461 }
462
ccec9d6b 463 $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
6a488035
TO
464
465 // update contact information
466 $this->updateContactInfo($value);
467
5ee60152 468 //build soft credit params
ccec9d6b
CW
469 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
470 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
0689c15c 471 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
9e1854a1 472
473 //CRM-15350: if soft-credit-type profile field is disabled or removed then
474 //we choose configured SCT default value
475 if (!empty($params['soft_credit_type'][$key])) {
476 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
477 }
478 else {
479 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup::getDefaultValue("soft_credit_type");
480 }
6a488035
TO
481 }
482
b7714c80
AH
483 // Build PCP params
484 if (!empty($params['pcp_made_through_id'][$key])) {
485 $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key];
486 $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]);
487 if (!empty($params['pcp_roll_nickname'][$key])) {
488 $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key];
489 }
490 if (!empty($params['pcp_personal_note'][$key])) {
491 $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key];
492 }
493 }
494
6a488035 495 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
df1f662a 496 NULL,
6a488035
TO
497 'Contribution'
498 );
499
a7488080 500 if (!empty($value['send_receipt'])) {
6a488035
TO
501 $value['receipt_date'] = date('Y-m-d His');
502 }
2e4a81d5
EM
503 // these translations & date handling are required because we are calling BAO directly rather than the api
504 $fieldTranslations = array(
505 'financial_type' => 'financial_type_id',
506 'payment_instrument' => 'payment_instrument_id',
507 'contribution_source' => 'source',
508 'contribution_note' => 'note',
6a488035 509
2e4a81d5
EM
510 );
511 foreach ($fieldTranslations as $formField => $baoField) {
5542b7c2 512 if (isset($value[$formField])) {
2e4a81d5
EM
513 $value[$baoField] = $value[$formField];
514 }
515 unset($value[$formField]);
6a488035
TO
516 }
517
518 $params['actualBatchTotal'] += $value['total_amount'];
6a488035
TO
519 $value['batch_id'] = $this->_batchId;
520 $value['skipRecentView'] = TRUE;
521
522 // build line item params
691df66d 523 $this->_priceSet['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
86bfa4f6 524 $value['price_' . $priceFieldID] = 1;
6a488035
TO
525
526 $lineItem = array();
9da8dc8c 527 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
6a488035 528
c039f658 529 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
530 // function to get correct amount level consistently. Remove setting of the amount level in
531 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
532 // to cover all variants.
6a488035
TO
533 unset($value['amount_level']);
534
2e4a81d5 535 //CRM-11529 for back office transactions
8ef12e64 536 //when financial_type_id is passed in form, update the
2e4a81d5 537 //line items with the financial type selected in form
c039f658 538 // @todo - create a price set or price field per financial type & simply choose the appropriate
539 // price field rather than working around the fact that each price_field is supposed to have a financial
540 // type & we are allowing that to be overridden.
8cc574cf 541 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
6a488035
TO
542 foreach ($lineItem[$priceSetId] as &$values) {
543 $values['financial_type_id'] = $value['financial_type_id'];
544 }
545 }
546 $value['line_item'] = $lineItem;
6a488035 547 //finally call contribution create for all the magic
1273d77c 548 $contribution = CRM_Contribute_BAO_Contribution::create($value);
d556e751 549 $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
34b568c4 550 if (!empty($this->_batchInfo['type_id']) && ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment'])) {
04e6444d 551 $adjustTotalAmount = FALSE;
5056dc8e 552 if (isset($params['option_type'][$key])) {
553 if ($params['option_type'][$key] == 2) {
554 $adjustTotalAmount = TRUE;
555 }
04e6444d 556 }
ce70f330 557 $pledgeId = $params['open_pledges'][$key];
5056dc8e 558 if (is_numeric($pledgeId)) {
559 $result = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId);
560 $pledgePaymentId = 0;
481a74f4 561 foreach ($result as $key => $values) {
5056dc8e 562 if ($values['status'] != 'Completed') {
563 $pledgePaymentId = $values['id'];
564 break;
565 }
04e6444d 566 }
5056dc8e 567 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id);
568 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId,
569 array($pledgePaymentId),
570 $contribution->contribution_status_id,
571 NULL,
572 $contribution->total_amount,
573 $adjustTotalAmount
574 );
04e6444d 575 }
04e6444d 576 }
5056dc8e 577
6a488035 578 //process premiums
a7488080 579 if (!empty($value['product_name'])) {
6a488035
TO
580 if ($value['product_name'][0] > 0) {
581 list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
582
583 $value['hidden_Premium'] = 1;
584 $value['product_option'] = CRM_Utils_Array::value(
585 $value['product_name'][1],
586 $options[$value['product_name'][0]]
587 );
588
589 $premiumParams = array(
590 'product_id' => $value['product_name'][0],
591 'contribution_id' => $contribution->id,
592 'product_option' => $value['product_option'],
593 'quantity' => 1,
594 );
595 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
596 }
597 }
598 // end of premium
599
600 //send receipt mail.
5056dc8e 601 if ($contribution->id && !empty($value['send_receipt'])) {
691df66d
TO
602 // add the domain email id
603 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
604 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
605 $value['from_email_address'] = $domainEmail;
606 $value['contribution_id'] = $contribution->id;
43f77a2c 607 if (!empty($value['soft_credit'])) {
608 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id));
609 }
481a74f4 610 CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $value);
6a488035
TO
611 }
612 }
613 }
2e4a81d5 614 return TRUE;
6a488035 615 }
6a488035
TO
616
617 /**
eceb18cc 618 * Process membership records.
6a488035 619 *
82d480a5
TO
620 * @param array $params
621 * Associated array of submitted values.
6a488035 622 *
6a488035 623 *
2e4a81d5 624 * @return bool
6a488035
TO
625 */
626 private function processMembership(&$params) {
6a488035 627
fd4b9293 628 // get the price set associated with offline membership
9da8dc8c 629 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
630 $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
6a488035
TO
631
632 if (isset($params['field'])) {
04b40eab 633 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
6a488035
TO
634 $customFields = array();
635 foreach ($params['field'] as $key => $value) {
636 // if contact is not selected we should skip the row
ccec9d6b 637 if (empty($params['primary_contact_id'][$key])) {
6a488035
TO
638 continue;
639 }
640
ccec9d6b 641 $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
6a488035
TO
642
643 // update contact information
644 $this->updateContactInfo($value);
645
646 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
647
a7488080 648 if (!empty($value['send_receipt'])) {
6a488035
TO
649 $value['receipt_date'] = date('Y-m-d His');
650 }
651
a7488080 652 if (!empty($value['membership_source'])) {
6a488035
TO
653 $value['source'] = $value['membership_source'];
654 }
655
656 unset($value['membership_source']);
657
658 //Get the membership status
a7488080 659 if (!empty($value['membership_status'])) {
6a488035
TO
660 $value['status_id'] = $value['membership_status'];
661 unset($value['membership_status']);
662 }
663
664 if (empty($customFields)) {
665 // membership type custom data
666 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
667
668 $customFields = CRM_Utils_Array::crmArrayMerge($customFields,
669 CRM_Core_BAO_CustomField::getFields('Membership',
670 FALSE, FALSE, NULL, NULL, TRUE
671 )
672 );
673 }
674
675 //check for custom data
676 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key],
6a488035
TO
677 $key,
678 'Membership',
679 $membershipTypeId
680 );
681
a7488080 682 if (!empty($value['financial_type'])) {
6a488035
TO
683 $value['financial_type_id'] = $value['financial_type'];
684 }
685
a7488080 686 if (!empty($value['payment_instrument'])) {
6a488035
TO
687 $value['payment_instrument_id'] = $value['payment_instrument'];
688 }
689
690 // handle soft credit
9e1854a1 691 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
ccec9d6b 692 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
0689c15c 693 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
9e1854a1 694
695 //CRM-15350: if soft-credit-type profile field is disabled or removed then
696 //we choose Gift as default value as per Gift Membership rule
697 if (!empty($params['soft_credit_type'][$key])) {
698 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
699 }
700 else {
1a453756 701 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
9e1854a1 702 }
6a488035
TO
703 }
704
6a488035
TO
705 $params['actualBatchTotal'] += $value['total_amount'];
706
707 unset($value['financial_type']);
708 unset($value['payment_instrument']);
709
710 $value['batch_id'] = $this->_batchId;
711 $value['skipRecentView'] = TRUE;
712
713 // make entry in line item for contribution
8ef12e64 714
6a488035
TO
715 $editedFieldParams = array(
716 'price_set_id' => $priceSetId,
21dfd5f5 717 'name' => $value['membership_type'][0],
6a488035
TO
718 );
719
720 $editedResults = array();
9da8dc8c 721 CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
6a488035
TO
722
723 if (!empty($editedResults)) {
724 unset($this->_priceSet['fields']);
725 $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
726 unset($this->_priceSet['fields'][$editedResults['id']]['options']);
727 $fid = $editedResults['id'];
728 $editedFieldParams = array(
729 'price_field_id' => $editedResults['id'],
21dfd5f5 730 'membership_type_id' => $value['membership_type_id'],
6a488035
TO
731 );
732
733 $editedResults = array();
9da8dc8c 734 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
6a488035 735 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
a7488080 736 if (!empty($value['total_amount'])) {
6a488035
TO
737 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
738 }
739
740 $fieldID = key($this->_priceSet['fields']);
741 $value['price_' . $fieldID] = $editedResults['id'];
742
8ef12e64 743 $lineItem = array();
9da8dc8c 744 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
6a488035
TO
745 $value, $lineItem[$priceSetId]
746 );
747
8ef12e64 748 //CRM-11529 for backoffice transactions
749 //when financial_type_id is passed in form, update the
6a488035 750 //lineitems with the financial type selected in form
8cc574cf 751 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
6a488035
TO
752 foreach ($lineItem[$priceSetId] as &$values) {
753 $values['financial_type_id'] = $value['financial_type_id'];
754 }
755 }
8ef12e64 756
6a488035
TO
757 $value['lineItems'] = $lineItem;
758 $value['processPriceSet'] = TRUE;
759 }
760 // end of contribution related section
761
762 unset($value['membership_type']);
8ef12e64 763
691df66d 764 $value['is_renew'] = FALSE;
481a74f4 765 if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
61767a1d
EM
766
767 // The following parameter setting may be obsolete.
6a488035 768 $this->_params = $params;
691df66d 769 $value['is_renew'] = TRUE;
61767a1d
EM
770 $isPayLater = CRM_Utils_Array::value('is_pay_later', $params);
771 $campaignId = NULL;
772 if (isset($this->_values) && is_array($this->_values) && !empty($this->_values)) {
773 $campaignId = CRM_Utils_Array::value('campaign_id', $this->_params);
774 if (!array_key_exists('campaign_id', $this->_params)) {
775 $campaignId = CRM_Utils_Array::value('campaign_id', $this->_values);
776 }
777 }
04b40eab 778
779 $formDates = array(
780 'end_date' => CRM_Utils_Array::value('membership_end_date', $value),
781 'start_date' => CRM_Utils_Array::value('membership_start_date', $value),
782 );
620ce374 783 $membershipSource = CRM_Utils_Array::value('source', $value);
356bfcaf 784 list($membership) = CRM_Member_BAO_Membership::processMembership(
61767a1d 785 $value['contact_id'], $value['membership_type_id'], FALSE,
55d094e7 786 //$numTerms should be default to 1.
787 NULL, NULL, $value['custom'], 1, NULL, FALSE,
620ce374 788 NULL, $membershipSource, $isPayLater, $campaignId, $formDates
6a488035
TO
789 );
790
791 // make contribution entry
28cc62fc 792 $contrbutionParams = array_merge($value, array('membership_id' => $membership->id));
3febe800 793 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
794 // This form should set the correct params & not call this fn directly.
28cc62fc 795 CRM_Member_BAO_Membership::recordMembershipContribution($contrbutionParams);
8ef12e64 796 }
6a488035 797 else {
04b40eab 798 $dateTypes = array(
799 'join_date' => 'joinDate',
800 'membership_start_date' => 'startDate',
801 'membership_end_date' => 'endDate',
802 );
803
804 $dates = array(
805 'join_date',
806 'start_date',
807 'end_date',
808 'reminder_date',
809 );
810 foreach ($dateTypes as $dateField => $dateVariable) {
811 $$dateVariable = CRM_Utils_Date::processDate($value[$dateField]);
812 $fDate[$dateField] = CRM_Utils_Array::value($dateField, $value);
813 }
814
815 $calcDates = array();
816 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId,
817 $joinDate, $startDate, $endDate
818 );
819
820 foreach ($calcDates as $memType => $calcDate) {
821 foreach ($dates as $d) {
822 //first give priority to form values then calDates.
823 $date = CRM_Utils_Array::value($d, $value);
824 if (!$date) {
825 $date = CRM_Utils_Array::value($d, $calcDate);
826 }
827
828 $value[$d] = CRM_Utils_Date::processDate($date);
829 }
830 }
831
832 unset($value['membership_start_date']);
833 unset($value['membership_end_date']);
834 $ids = array();
835 $membership = CRM_Member_BAO_Membership::create($value, $ids);
6a488035
TO
836 }
837
838 //process premiums
a7488080 839 if (!empty($value['product_name'])) {
6a488035
TO
840 if ($value['product_name'][0] > 0) {
841 list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
842
843 $value['hidden_Premium'] = 1;
844 $value['product_option'] = CRM_Utils_Array::value(
845 $value['product_name'][1],
846 $options[$value['product_name'][0]]
847 );
848
849 $premiumParams = array(
850 'product_id' => $value['product_name'][0],
5056dc8e 851 'contribution_id' => CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id'),
6a488035
TO
852 'product_option' => $value['product_option'],
853 'quantity' => 1,
854 );
855 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
856 }
857 }
858 // end of premium
859
860 //send receipt mail.
481a74f4 861 if ($membership->id && !empty($value['send_receipt'])) {
6a488035 862
691df66d
TO
863 // add the domain email id
864 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
865 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
6a488035 866
691df66d 867 $value['from_email_address'] = $domainEmail;
353ffa53 868 $value['membership_id'] = $membership->id;
691df66d 869 $value['contribution_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id');
481a74f4 870 CRM_Member_Form_Membership::emailReceipt($this, $value, $membership);
6a488035
TO
871 }
872 }
873 }
afe349ef 874 return TRUE;
6a488035
TO
875 }
876
877 /**
eceb18cc 878 * Update contact information.
6a488035 879 *
82d480a5
TO
880 * @param array $value
881 * Associated array of submitted values.
6a488035
TO
882 */
883 private function updateContactInfo(&$value) {
884 $value['preserveDBName'] = $this->_preserveDefault;
885
886 //parse street address, CRM-7768
887 CRM_Contact_Form_Task_Batch::parseStreetAddress($value, $this);
888
889 CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields,
890 $value['contact_id']
891 );
892 }
cab024d4 893
afe349ef 894 /**
ce064e4f 895 * Function exists purely for unit testing purposes.
896 *
897 * If you feel tempted to use this in live code then it probably means there is some functionality
898 * that needs to be moved out of the form layer
cab024d4 899 *
4c16123d 900 * @param array $params
cab024d4
EM
901 *
902 * @return bool
afe349ef 903 */
00be9182 904 public function testProcessMembership($params) {
afe349ef 905 return $this->processMembership($params);
906 }
cab024d4
EM
907
908 /**
ce064e4f 909 * Function exists purely for unit testing purposes.
910 *
911 * If you feel tempted to use this in live code then it probably means there is some functionality
912 * that needs to be moved out of the form layer.
cab024d4
EM
913 *
914 * @param array $params
915 *
916 * @return bool
917 */
00be9182 918 public function testProcessContribution($params) {
cab024d4
EM
919 return $this->processContribution($params);
920 }
96025800 921
6a488035 922}