CRM-15701 QA-fixes
[civicrm-core.git] / CRM / Batch / Form / Entry.php
... / ...
CommitLineData
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35
36/**
37 * This class provides the functionality for batch entry for contributions/memberships
38 */
39class CRM_Batch_Form_Entry extends CRM_Core_Form {
40
41 /**
42 * Maximum profile fields that will be displayed
43 *
44 */
45 protected $_rowCount = 1;
46
47 /**
48 * Batch id
49 */
50 protected $_batchId;
51
52 /**
53 * Batch information
54 */
55 protected $_batchInfo = array();
56
57 /**
58 * Store the profile id associated with the batch type
59 */
60 protected $_profileId;
61
62 public $_action;
63
64 public $_mode;
65
66 public $_params;
67
68 public $_membershipId = null;
69 /**
70 * When not to reset sort_name
71 */
72 protected $_preserveDefault = TRUE;
73
74 /**
75 * Contact fields
76 */
77 protected $_contactFields = array();
78
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();
88 /**
89 * Build all the data structures needed to build the form
90 *
91 * @return void
92 * @access public
93 */
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');
98
99 if (empty($this->_batchInfo)) {
100 $params = array('id' => $this->_batchId);
101 CRM_Batch_BAO_Batch::retrieve($params, $this->_batchInfo);
102
103 $this->assign('batchTotal', !empty($this->_batchInfo['total']) ? $this->_batchInfo['total'] : NULL);
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 }
109 CRM_Core_Resources::singleton()
110 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
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
115 }
116
117 /**
118 * Build the form object
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
131 $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id',array('flip' => 1), 'validate');
132 // get the profile information
133 if ($this->_batchInfo['type_id'] == $batchTypes['Contribution']) {
134 CRM_Utils_System::setTitle(ts('Batch Data Entry for Contributions'));
135 $customFields = CRM_Core_BAO_CustomField::getFields('Contribution');
136 }
137 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
138 CRM_Utils_System::setTitle(ts('Batch Data Entry for Memberships'));
139 $customFields = CRM_Core_BAO_CustomField::getFields('Membership');
140 }
141 elseif ($this->_batchInfo['type_id'] == $batchTypes['Pledge']) {
142 CRM_Utils_System::setTitle(ts('Batch Data Entry for Pledges'));
143 $customFields = CRM_Core_BAO_CustomField::getFields('Contribution');
144 }
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');
199 $contactReturnProperties = array();
200 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
201 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', array('create' => TRUE, 'placeholder' => ts('- select -')));
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 }
211 if ($this->_batchInfo['type_id'] == $batchTypes['Pledge']) {
212 $options = array('' => '-select-');
213 $optionTypes = array(
214 '1' => ts('Adjust Pledge Payment Schedule?'),
215 '2' => ts('Adjust Total Pledge Amount?'),
216 );
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);
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 }
226 }
227 }
228 $this->add('select', "open_pledges[$rowNumber]", ts('Open Pledges'), $options);
229 }
230
231 foreach ($this->_fields as $name => $field) {
232 if (in_array($field['field_type'], $contactTypes)) {
233 $fld = explode('-', $field['name']);
234 $contactReturnProperties[$field['name']] = $fld[0];
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);
245 CRM_Core_Resources::singleton()
246 ->addSetting(array('contact' => array(
247 'return' => implode(',', $contactReturnProperties),
248 'fieldmap' => array_flip($contactReturnProperties),
249 )));
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') {
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');
256 }
257 }
258
259 /**
260 * Form validations
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
273 if (!empty($params['_qf_Entry_upload_force'])) {
274 return TRUE;
275 }
276
277 $batchTotal = 0;
278 foreach ($params['field'] as $key => $value) {
279 $batchTotal += $value['total_amount'];
280
281 //validate for soft credit fields
282 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
283 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
284 }
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'])) {
286 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
287 }
288
289 //membership type is required for membership batch entry
290 if ( $self->_batchInfo['type_id'] == 2 ) {
291 if (empty($value['membership_type'][1])) {
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 /**
320 * Set default values for the form.
321 *
322 * @access public
323 *
324 * @return void
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');
337 $completeStatus = array_search( 'Completed', $allStatus );
338 $specialFields = array(
339 'join_date' => $currentDate,
340 'receive_date' => $currentDate,
341 'receive_date_time' => $currentTime,
342 'contribution_status_id' => $completeStatus
343 );
344
345 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
346 foreach ($specialFields as $key => $value ) {
347 $defaults['field'][$rowNumber][$key] = $value;
348 }
349 }
350 }
351 else {
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);
355 $defaults = $defaults['values'];
356 }
357
358 return $defaults;
359 }
360
361 /**
362 * Process the form after the input has been submitted and validated
363 *
364 * @access public
365 *
366 * @return void
367 */
368 public function postProcess() {
369 $params = $this->controller->exportValues($this->_name);
370 $params['actualBatchTotal'] = 0;
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']))) {
375 $this->processContribution($params);
376 }
377 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
378 $this->processMembership($params);
379 }
380
381 // update batch to close status
382 $paramValues = array(
383 'id' => $this->_batchId,
384 // close status
385 'status_id' => CRM_Core_OptionGroup::getValue('batch_status', 'Closed', 'name'),
386 'total' => $params['actualBatchTotal'],
387 );
388
389 CRM_Batch_BAO_Batch::create($paramValues);
390
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 /**
398 * Process contribution records
399 *
400 * @param array $params associated array of submitted values
401 *
402 * @access public
403 *
404 * @return void
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.
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));
417 $priceFieldID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldID($this->_priceSet);
418 $priceFieldValueID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldValueID($this->_priceSet);
419
420 if (isset($params['field'])) {
421 foreach ($params['field'] as $key => $value) {
422 // if contact is not selected we should skip the row
423 if (empty($params['primary_contact_id'][$key])) {
424 continue;
425 }
426
427 $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
428
429 // update contact information
430 $this->updateContactInfo($value);
431
432 //build soft credit params
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];
435 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
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 }
445 }
446
447 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
448 CRM_Core_DAO::$_nullObject,
449 NULL,
450 'Contribution'
451 );
452
453 foreach ($dates as $val) {
454 if (!empty($value[$val])) {
455 $value[$val] = CRM_Utils_Date::processDate( $value[$val], $value[$val . '_time'], TRUE );
456 }
457 }
458
459 if (!empty($value['send_receipt'])) {
460 $value['receipt_date'] = date('Y-m-d His');
461 }
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',
468
469 );
470 foreach ($fieldTranslations as $formField => $baoField) {
471 if (isset($value[$formField])) {
472 $value[$baoField] = $value[$formField];
473 }
474 unset($value[$formField]);
475 }
476
477 $params['actualBatchTotal'] += $value['total_amount'];
478 $value['batch_id'] = $this->_batchId;
479 $value['skipRecentView'] = TRUE;
480
481 // build line item params
482 $this->_priceSet['fields'][$priceFieldID]['options'][$priceFieldValueID ]['amount'] = $value['total_amount'];
483 $value['price_'. $priceFieldID] = 1;
484
485 $lineItem = array();
486 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
487
488 //unset amount level since we always use quick config price set
489 unset($value['amount_level']);
490
491 //CRM-11529 for back office transactions
492 //when financial_type_id is passed in form, update the
493 //line items with the financial type selected in form
494 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
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);
503 $pledgeId = $params['open_pledges'][$key];
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)) {
506 $adjustTotalAmount = FALSE;
507 if ($params['option_type'][$key] == 2) {
508 $adjustTotalAmount=TRUE;
509 }
510 $pledgeId = $params['open_pledges'][$key];
511 $result = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId);
512 $pledgePaymentId = 0;
513 foreach ($result as $key => $value ) {
514 if ($value['status'] != 'Completed') {
515 $pledgePaymentId = $value['id'];
516 break;
517 }
518 }
519 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id);
520 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId,
521 array($pledgePaymentId),
522 $contribution->contribution_status_id,
523 NULL,
524 $contribution->total_amount,
525 $adjustTotalAmount
526 );
527 }
528 //process premiums
529 if (!empty($value['product_name'])) {
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.
551 if ( $contribution->id && !empty($value['send_receipt'])) {
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 }
562 return TRUE;
563 }
564
565 /**
566 * Process membership records
567 *
568 * @param array $params associated array of submitted values
569 *
570 * @access public
571 *
572 * @return bool
573 */
574 private function processMembership(&$params) {
575 $dateTypes = array(
576 'join_date' => 'joinDate',
577 'membership_start_date' => 'startDate',
578 'membership_end_date' => 'endDate'
579 );
580
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
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));
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
596 if (empty($params['primary_contact_id'][$key])) {
597 continue;
598 }
599
600 $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
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
628 if (!empty($value['send_receipt'])) {
629 $value['receipt_date'] = date('Y-m-d His');
630 }
631
632 if (!empty($value['membership_source'])) {
633 $value['source'] = $value['membership_source'];
634 }
635
636 unset($value['membership_source']);
637
638 //Get the membership status
639 if (!empty($value['membership_status'])) {
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
663 if (!empty($value['financial_type'])) {
664 $value['financial_type_id'] = $value['financial_type'];
665 }
666
667 if (!empty($value['payment_instrument'])) {
668 $value['payment_instrument_id'] = $value['payment_instrument'];
669 }
670
671 // handle soft credit
672 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
673 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
674 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
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 }
684 }
685
686 if (!empty($value['receive_date'])) {
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
699
700 $editedFieldParams = array(
701 'price_set_id' => $priceSetId,
702 'name' => $value['membership_type'][0]
703 );
704
705 $editedResults = array();
706 CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
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();
719 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
720 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
721 if (!empty($value['total_amount'])) {
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
728 $lineItem = array();
729 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
730 $value, $lineItem[$priceSetId]
731 );
732
733 //CRM-11529 for backoffice transactions
734 //when financial_type_id is passed in form, update the
735 //lineitems with the financial type selected in form
736 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
737 foreach ($lineItem[$priceSetId] as &$values) {
738 $values['financial_type_id'] = $value['financial_type_id'];
739 }
740 }
741
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']);
750
751 $value['is_renew'] = false;
752 if (!empty($params['member_option']) && CRM_Utils_Array::value( $key, $params['member_option'] ) == 2 ) {
753 $this->_params = $params;
754 $value['is_renew'] = true;
755 $membership = CRM_Member_BAO_Membership::renewMembershipFormWrapper(
756 $value['contact_id'],
757 $value['membership_type_id'],
758 FALSE, $this, NULL, NULL,
759 $value['custom']
760 );
761
762 // make contribution entry
763 CRM_Member_BAO_Membership::recordMembershipContribution( array_merge($value, array('membership_id' => $membership->id)));
764 }
765 else {
766 $membership = CRM_Member_BAO_Membership::create($value, CRM_Core_DAO::$_nullArray);
767 }
768
769 //process premiums
770 if (!empty($value['product_name'])) {
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.
792 if ( $membership->id && !empty($value['send_receipt'])) {
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 }
804 return TRUE;
805 }
806
807 /**
808 * Update contact information
809 *
810 * @param array $value associated array of submitted values
811 *
812 * @access public
813 *
814 * @return void
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 }
826
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
831 *
832 * @param unknown_type $params
833 *
834 * @return bool
835 */
836 function testProcessMembership($params) {
837 return $this->processMembership($params);
838 }
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 }
852}
853