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