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