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