Merge pull request #2910 from eileenmcnaughton/enotice2
[civicrm-core.git] / CRM / Batch / Form / Entry.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
32 * $Id$
33 *
34 */
35
36 /**
37 * This class provides the functionality for batch entry for contributions/memeberships
38 */
39 class 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 informtaion
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')
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
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 // get the profile information
132 if ($this->_batchInfo['type_id'] == 1) {
133 CRM_Utils_System::setTitle(ts('Batch Data Entry for Contributions'));
134 $customFields = CRM_Core_BAO_CustomField::getFields('Contribution');
135 }
136 else {
137 CRM_Utils_System::setTitle(ts('Batch Data Entry for Memberships'));
138 $customFields = CRM_Core_BAO_CustomField::getFields('Membership');
139 }
140
141 $this->_fields = array();
142 $this->_fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, CRM_Core_Action::VIEW);
143
144 // remove file type field and then limit fields
145 $suppressFields = FALSE;
146 $removehtmlTypes = array('File', 'Autocomplete-Select');
147 foreach ($this->_fields as $name => $field) {
148 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) &&
149 in_array($this->_fields[$name]['html_type'], $removehtmlTypes)
150 ) {
151 $suppressFields = TRUE;
152 unset($this->_fields[$name]);
153 }
154
155 //fix to reduce size as we are using this field in grid
156 if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) {
157 //shrink class to "form-text-medium"
158 $this->_fields[$name]['attributes']['size'] = 19;
159 }
160 }
161
162 $this->addFormRule(array('CRM_Batch_Form_Entry', 'formRule'), $this);
163
164 // add the force save button
165 $forceSave = $this->getButtonName('upload', 'force');
166
167 $this->addElement('submit',
168 $forceSave,
169 ts('Ignore Mismatch & Process the Batch?')
170 );
171
172 $this->addButtons(array(
173 array(
174 'type' => 'upload',
175 'name' => ts('Validate & Process the Batch'),
176 'isDefault' => TRUE
177 ),
178 array(
179 'type' => 'cancel',
180 'name' => ts('Save & Continue Later'),
181 )
182 )
183 );
184
185 $this->assign('rowCount', $this->_batchInfo['item_count'] + 1);
186
187 $fileFieldExists = FALSE;
188 $preserveDefaultsArray = array(
189 'first_name', 'last_name', 'middle_name',
190 'organization_name',
191 'household_name',
192 );
193
194 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
195 $contactReturnProperties = array();
196 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
197 CRM_Contact_Form_NewContact::buildQuickForm($this, $rowNumber, NULL, TRUE, 'primary_', ts('Contact'));
198
199 // special field specific to membership batch udpate
200 if ($this->_batchInfo['type_id'] == 2) {
201 $options = array(
202 1 => ts('Add Membership'),
203 2 => ts('Renew Membership'),
204 );
205 $this->add('select', "member_option[$rowNumber]", '', $options);
206 }
207
208 foreach ($this->_fields as $name => $field) {
209 if (in_array($field['field_type'], $contactTypes)) {
210 $fld = explode('-', $field['name']);
211 $contactReturnProperties[$field['name']] = $fld[0];
212 }
213 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
214
215 if (in_array($field['name'], $preserveDefaultsArray)) {
216 $this->_preserveDefault = FALSE;
217 }
218 }
219 }
220
221 $this->assign('fields', $this->_fields);
222 CRM_Core_Resources::singleton()
223 ->addSetting(array('contact' => array(
224 'return' => implode(',', $contactReturnProperties),
225 'fieldmap' => array_flip($contactReturnProperties),
226 )));
227
228 // don't set the status message when form is submitted.
229 $buttonName = $this->controller->getButtonName('submit');
230
231 if ($suppressFields && $buttonName != '_qf_Entry_next') {
232 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 have been excluded."), "info");
233 }
234 }
235
236 /**
237 * form validations
238 *
239 * @param array $params posted values of the form
240 * @param array $files list of errors to be posted back to the form
241 * @param array $self form object
242 *
243 * @return array list of errors to be posted back to the form
244 * @static
245 * @access public
246 */
247 static function formRule($params, $files, $self) {
248 $errors = array();
249
250 if (CRM_Utils_Array::value('_qf_Entry_upload_force', $params)) {
251 return TRUE;
252 }
253
254 $batchTotal = 0;
255 foreach ($params['field'] as $key => $value) {
256 $batchTotal += $value['total_amount'];
257
258 //validate for soft credit fields
259 if (CRM_Utils_Array::value($key, $params['soft_credit_contact_select_id']) && !CRM_Utils_Array::value($key, $params['soft_credit_amount'])) {
260 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
261 }
262 if (!empty($params['soft_credit_amount']) && CRM_Utils_Array::value($key, $params['soft_credit_amount'])
263 && CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value($key, $params['soft_credit_amount'])) > CRM_Utils_Rule::cleanMoney($value['total_amount'])) {
264 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
265 }
266
267 //membership type is required for membership batch entry
268 if ( $self->_batchInfo['type_id'] == 2 ) {
269 if ( !CRM_Utils_Array::value( 1, $value['membership_type'] ) ) {
270 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
271 }
272 }
273 }
274
275 // if contact name is set for a row using autocomplete widget then make sure contact id exists, CRM-13078
276 // I was not able to replicate this on my local but adding this check and hopefully it will fix the issue.
277 if (!empty($params['primary_contact'])) {
278 foreach($params['primary_contact'] as $rowIndex => $contactName) {
279 if (empty($params['primary_contact_select_id'][$rowIndex])) {
280 $errors['primary_contact['.$rowIndex.']'] = ts('Please select a valid contact.');
281 }
282 }
283 }
284
285 if ($batchTotal != $self->_batchInfo['total']) {
286 $self->assign('batchAmountMismatch', TRUE);
287 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
288 }
289
290 if (!empty($errors)) {
291 return $errors;
292 }
293
294 $self->assign('batchAmountMismatch', FALSE);
295 return TRUE;
296 }
297
298 /**
299 * Override default cancel action
300 */
301 function cancelAction() {
302 // redirect to batch listing
303 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
304 CRM_Utils_System::civiExit();
305 }
306
307 /**
308 * This function sets the default values for the form.
309 *
310 * @access public
311 *
312 * @return None
313 */
314 function setDefaultValues() {
315 if (empty($this->_fields)) {
316 return;
317 }
318
319 // for add mode set smart defaults
320 if ( $this->_action & CRM_Core_Action::ADD ) {
321 list( $currentDate, $currentTime ) = CRM_Utils_Date::setDateDefaults( NULL, 'activityDateTime' );
322
323 //get all status
324 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
325 $completeStatus = array_search( 'Completed', $allStatus );
326 $specialFields = array(
327 'join_date' => $currentDate,
328 'receive_date' => $currentDate,
329 'receive_date_time' => $currentTime,
330 'contribution_status_id' => $completeStatus
331 );
332
333 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
334 foreach ($specialFields as $key => $value ) {
335 $defaults['field'][$rowNumber][$key] = $value;
336 }
337 }
338 }
339 else {
340 // get the cached info from data column of civicrm_batch
341 $data = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId, 'data');
342 $defaults = json_decode($data, TRUE);
343 $defaults = $defaults['values'];
344 }
345
346 return $defaults;
347 }
348
349 /**
350 * process the form after the input has been submitted and validated
351 *
352 * @access public
353 *
354 * @return None
355 */
356 public function postProcess() {
357 $params = $this->controller->exportValues($this->_name);
358
359 $params['actualBatchTotal'] = 0;
360
361 // get the profile information
362 if ($this->_batchInfo['type_id'] == 1) {
363 $this->processContribution($params);
364 }
365 else {
366 $this->processMembership($params);
367 }
368
369 // update batch to close status
370 $paramValues = array(
371 'id' => $this->_batchId,
372 // close status
373 'status_id' => CRM_Core_OptionGroup::getValue('batch_status', 'Closed', 'name'),
374 'total' => $params['actualBatchTotal'],
375 );
376
377 CRM_Batch_BAO_Batch::create($paramValues);
378
379 // set success status
380 CRM_Core_Session::setStatus("", ts("Batch Processed."), "success");
381
382 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
383 }
384
385 /**
386 * process contribution records
387 *
388 * @param array $params associated array of submitted values
389 *
390 * @access public
391 *
392 * @return None
393 */
394 private function processContribution(&$params) {
395 $dates = array(
396 'receive_date',
397 'receipt_date',
398 'thankyou_date',
399 'cancel_date',
400 );
401
402 // get the price set associated with offline contribution record.
403 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
404 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
405 $fieldID = key($this->_priceSet['fields']);
406
407 if (isset($params['field'])) {
408 foreach ($params['field'] as $key => $value) {
409 // if contact is not selected we should skip the row
410 if (!CRM_Utils_Array::value($key, $params['primary_contact_select_id'])) {
411 continue;
412 }
413
414 $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_select_id']);
415
416 // update contact information
417 $this->updateContactInfo($value);
418
419 //build soft credit params
420 if (CRM_Utils_Array::value($key, $params['soft_credit_contact_select_id']) && CRM_Utils_Array::value($key, $params['soft_credit_amount'])) {
421 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_select_id'][$key];
422 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
423 }
424
425 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
426 CRM_Core_DAO::$_nullObject,
427 NULL,
428 'Contribution'
429 );
430
431 foreach ($dates as $val) {
432 if ( CRM_Utils_Array::value( $val, $value ) ) {
433 $value[$val] = CRM_Utils_Date::processDate( $value[$val], $value[$val . '_time'], TRUE );
434 }
435 }
436
437 if (CRM_Utils_Array::value('send_receipt', $value)) {
438 $value['receipt_date'] = date('Y-m-d His');
439 }
440
441 if ($value['financial_type']) {
442 $value['financial_type_id'] = $value['financial_type'];
443 }
444
445 if (CRM_Utils_Array::value('payment_instrument', $value)) {
446 $value['payment_instrument_id'] = $value['payment_instrument'];
447 }
448
449 if (CRM_Utils_Array::value('contribution_source', $value)) {
450 $value['source'] = $value['contribution_source'];
451 }
452
453 if (CRM_Utils_Array::value('contribution_note', $value)) {
454 $value['note'] = $value['contribution_note'];
455 }
456
457 $params['actualBatchTotal'] += $value['total_amount'];
458
459 unset($value['contribution_note']);
460 unset($value['financial_type']);
461 unset($value['contribution_source']);
462
463 $value['batch_id'] = $this->_batchId;
464 $value['skipRecentView'] = TRUE;
465
466 // build line item params
467 $this->_priceSet['fields'][$fieldID]['options'][$fieldID]['amount'] = $value['total_amount'];
468 $value['price_'.$fieldID] = 1;
469
470 $lineItem = array();
471 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
472
473 //unset amount level since we always use quick config price set
474 unset($value['amount_level']);
475
476 //CRM-11529 for backoffice transactions
477 //when financial_type_id is passed in form, update the
478 //lineitems with the financial type selected in form
479 if (CRM_Utils_Array::value('financial_type_id', $value) && CRM_Utils_Array::value($priceSetId, $lineItem)) {
480 foreach ($lineItem[$priceSetId] as &$values) {
481 $values['financial_type_id'] = $value['financial_type_id'];
482 }
483 }
484 $value['line_item'] = $lineItem;
485
486 //finally call contribution create for all the magic
487 $contribution = CRM_Contribute_BAO_Contribution::create($value, CRM_Core_DAO::$_nullArray);
488
489 //process premiums
490 if (CRM_Utils_Array::value('product_name', $value)) {
491 if ($value['product_name'][0] > 0) {
492 list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
493
494 $value['hidden_Premium'] = 1;
495 $value['product_option'] = CRM_Utils_Array::value(
496 $value['product_name'][1],
497 $options[$value['product_name'][0]]
498 );
499
500 $premiumParams = array(
501 'product_id' => $value['product_name'][0],
502 'contribution_id' => $contribution->id,
503 'product_option' => $value['product_option'],
504 'quantity' => 1,
505 );
506 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
507 }
508 }
509 // end of premium
510
511 //send receipt mail.
512 if ( $contribution->id &&
513 CRM_Utils_Array::value( 'send_receipt', $value ) ) {
514 // add the domain email id
515 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
516 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
517
518 $value['from_email_address'] = $domainEmail;
519 $value['contribution_id'] = $contribution->id;
520 CRM_Contribute_Form_AdditionalInfo::emailReceipt( $this, $value );
521 }
522 }
523 }
524 }
525 //end of function
526
527 /**
528 * process membership records
529 *
530 * @param array $params associated array of submitted values
531 *
532 * @access public
533 *
534 * @return None
535 */
536 private function processMembership(&$params) {
537 $dateTypes = array(
538 'join_date' => 'joinDate',
539 'membership_start_date' => 'startDate',
540 'membership_end_date' => 'endDate'
541 );
542
543 $dates = array(
544 'join_date',
545 'start_date',
546 'end_date',
547 'reminder_date'
548 );
549
550 // get the price set associated with offline memebership
551 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
552 $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
553
554 if (isset($params['field'])) {
555 $customFields = array();
556 foreach ($params['field'] as $key => $value) {
557 // if contact is not selected we should skip the row
558 if (!CRM_Utils_Array::value($key, $params['primary_contact_select_id'])) {
559 continue;
560 }
561
562 $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_select_id']);
563
564 // update contact information
565 $this->updateContactInfo($value);
566
567 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
568
569 foreach ($dateTypes as $dateField => $dateVariable) {
570 $$dateVariable = CRM_Utils_Date::processDate($value[$dateField]);
571 }
572
573 $calcDates = array();
574 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId,
575 $joinDate, $startDate, $endDate
576 );
577
578 foreach ($calcDates as $memType => $calcDate) {
579 foreach ($dates as $d) {
580 //first give priority to form values then calDates.
581 $date = CRM_Utils_Array::value($d, $value);
582 if (!$date) {
583 $date = CRM_Utils_Array::value($d, $calcDate);
584 }
585
586 $value[$d] = CRM_Utils_Date::processDate($date);
587 }
588 }
589
590 if (CRM_Utils_Array::value('send_receipt', $value)) {
591 $value['receipt_date'] = date('Y-m-d His');
592 }
593
594 if (CRM_Utils_Array::value('membership_source', $value)) {
595 $value['source'] = $value['membership_source'];
596 }
597
598 unset($value['membership_source']);
599
600 //Get the membership status
601 if ( CRM_Utils_Array::value('membership_status', $value) ) {
602 $value['status_id'] = $value['membership_status'];
603 unset($value['membership_status']);
604 }
605
606 if (empty($customFields)) {
607 // membership type custom data
608 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
609
610 $customFields = CRM_Utils_Array::crmArrayMerge($customFields,
611 CRM_Core_BAO_CustomField::getFields('Membership',
612 FALSE, FALSE, NULL, NULL, TRUE
613 )
614 );
615 }
616
617 //check for custom data
618 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key],
619 $customFields,
620 $key,
621 'Membership',
622 $membershipTypeId
623 );
624
625 if (CRM_Utils_Array::value('financial_type', $value)) {
626 $value['financial_type_id'] = $value['financial_type'];
627 }
628
629 if (CRM_Utils_Array::value('payment_instrument', $value)) {
630 $value['payment_instrument_id'] = $value['payment_instrument'];
631 }
632
633 // handle soft credit
634 if (is_array(CRM_Utils_Array::value('soft_credit_contact_select_id', $params)) && CRM_Utils_Array::value($key, $params['soft_credit_contact_select_id']) && CRM_Utils_Array::value($key, $params['soft_credit_amount'])) {
635 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_select_id'][$key];
636 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
637 }
638
639 if ( CRM_Utils_Array::value('receive_date', $value) ) {
640 $value['receive_date'] = CRM_Utils_Date::processDate( $value['receive_date'], $value['receive_date_time'] , TRUE );
641 }
642
643 $params['actualBatchTotal'] += $value['total_amount'];
644
645 unset($value['financial_type']);
646 unset($value['payment_instrument']);
647
648 $value['batch_id'] = $this->_batchId;
649 $value['skipRecentView'] = TRUE;
650
651 // make entry in line item for contribution
652
653 $editedFieldParams = array(
654 'price_set_id' => $priceSetId,
655 'name' => $value['membership_type'][0]
656 );
657
658 $editedResults = array();
659 CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
660
661 if (!empty($editedResults)) {
662 unset($this->_priceSet['fields']);
663 $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
664 unset($this->_priceSet['fields'][$editedResults['id']]['options']);
665 $fid = $editedResults['id'];
666 $editedFieldParams = array(
667 'price_field_id' => $editedResults['id'],
668 'membership_type_id' => $value['membership_type_id']
669 );
670
671 $editedResults = array();
672 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
673 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
674 if (CRM_Utils_Array::value('total_amount', $value)) {
675 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
676 }
677
678 $fieldID = key($this->_priceSet['fields']);
679 $value['price_' . $fieldID] = $editedResults['id'];
680
681 $lineItem = array();
682 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
683 $value, $lineItem[$priceSetId]
684 );
685
686 //CRM-11529 for backoffice transactions
687 //when financial_type_id is passed in form, update the
688 //lineitems with the financial type selected in form
689 if (CRM_Utils_Array::value('financial_type_id', $value) && CRM_Utils_Array::value($priceSetId, $lineItem)) {
690 foreach ($lineItem[$priceSetId] as &$values) {
691 $values['financial_type_id'] = $value['financial_type_id'];
692 }
693 }
694
695 $value['lineItems'] = $lineItem;
696 $value['processPriceSet'] = TRUE;
697 }
698 // end of contribution related section
699
700 unset($value['membership_type']);
701 unset($value['membership_start_date']);
702 unset($value['membership_end_date']);
703
704 $value['is_renew'] = false;
705 if ( CRM_Utils_Array::value('member_option', $params) && CRM_Utils_Array::value( $key, $params['member_option'] ) == 2 ) {
706 $this->_params = $params;
707 $value['is_renew'] = true;
708 $membership = CRM_Member_BAO_Membership::renewMembership(
709 $value['contact_id'],
710 $value['membership_type_id'],
711 FALSE, $this, NULL, NULL,
712 $value['custom']
713 );
714
715 // make contribution entry
716 CRM_Member_BAO_Membership::recordMembershipContribution( array_merge($value, array('membership_id' => $membership->id)));
717 }
718 else {
719 $membership = CRM_Member_BAO_Membership::create($value, CRM_Core_DAO::$_nullArray);
720 }
721
722 //process premiums
723 if (CRM_Utils_Array::value('product_name', $value)) {
724 if ($value['product_name'][0] > 0) {
725 list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
726
727 $value['hidden_Premium'] = 1;
728 $value['product_option'] = CRM_Utils_Array::value(
729 $value['product_name'][1],
730 $options[$value['product_name'][0]]
731 );
732
733 $premiumParams = array(
734 'product_id' => $value['product_name'][0],
735 'contribution_id' => $value['contribution_id'],
736 'product_option' => $value['product_option'],
737 'quantity' => 1,
738 );
739 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
740 }
741 }
742 // end of premium
743
744 //send receipt mail.
745 if ( $membership->id &&
746 CRM_Utils_Array::value( 'send_receipt', $value ) ) {
747
748 // add the domain email id
749 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
750 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
751
752 $value['from_email_address'] = $domainEmail;
753 $value['membership_id'] = $membership->id;
754 CRM_Member_Form_Membership::emailReceipt( $this, $value, $membership );
755 }
756 }
757 }
758 return TRUE;
759 }
760
761 /**
762 * update contact information
763 *
764 * @param array $value associated array of submitted values
765 *
766 * @access public
767 *
768 * @return None
769 */
770 private function updateContactInfo(&$value) {
771 $value['preserveDBName'] = $this->_preserveDefault;
772
773 //parse street address, CRM-7768
774 CRM_Contact_Form_Task_Batch::parseStreetAddress($value, $this);
775
776 CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields,
777 $value['contact_id']
778 );
779 }
780 /**
781 * Function exists purely for unit testing purposes. If you feel tempted to use this in live code
782 * then it probably means there is some functionality that needs to be moved
783 * out of the form layer
784 * @param unknown_type $params
785 */
786 function testProcessMembership($params) {
787 return $this->processMembership($params);
788 }
789 }
790