unrelated e-notice fix
[civicrm-core.git] / CRM / Batch / Form / Entry.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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 */
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 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;
8ef12e64 63
6a488035
TO
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
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
TO
88 /**
89 * build all the data structures needed to build the form
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()
1283a565 110 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js')
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 /**
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 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
196 CRM_Contact_Form_NewContact::buildQuickForm($this, $rowNumber, NULL, TRUE, 'primary_');
197
198 // special field specific to membership batch udpate
199 if ($this->_batchInfo['type_id'] == 2) {
200 $options = array(
201 1 => ts('Add Membership'),
202 2 => ts('Renew Membership'),
203 );
204 $this->add('select', "member_option[$rowNumber]", '', $options);
205 }
206
207 foreach ($this->_fields as $name => $field) {
208 if (in_array($field['field_type'], $contactTypes)) {
57465e2a 209 $fld = explode('-', $field['name']);
210 $contactReturnProperties[] = $fld[0];
211 $contactFieldMap[$fld[0]] = $field['name'];
6a488035
TO
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);
57465e2a 222 CRM_Core_Resources::singleton()
223 ->addSetting(array('contact' => array(
224 'return' => implode(',', $contactReturnProperties),
225 'fieldmap' => $contactFieldMap,
226 )));
6a488035
TO
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
5ee60152
RN
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 }
8ef12e64 262 if (CRM_Utils_Array::value($key, $params['soft_credit_amount'])
0689c15c 263 && CRM_Utils_Rule::cleanMoney(CRM_Utils_Array::value($key, $params['soft_credit_amount'])) > CRM_Utils_Rule::cleanMoney($value['total_amount'])) {
5ee60152
RN
264 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
265 }
8ef12e64 266
6a488035
TO
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
eeca4aa5
C
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
6a488035
TO
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');
8ef12e64 325 $completeStatus = array_search( 'Completed', $allStatus );
326 $specialFields = array(
6a488035
TO
327 'join_date' => $currentDate,
328 'receive_date' => $currentDate,
329 'receive_date_time' => $currentTime,
8ef12e64 330 'contribution_status_id' => $completeStatus
6a488035
TO
331 );
332
333 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
334 foreach ($specialFields as $key => $value ) {
8ef12e64 335 $defaults['field'][$rowNumber][$key] = $value;
6a488035 336 }
8ef12e64 337 }
6a488035
TO
338 }
339 else {
340 // get the existing batch values from cache table
341 $cacheKeyString = CRM_Batch_BAO_Batch::getCacheKeyForBatch($this->_batchId);
342 $defaults = CRM_Core_BAO_Cache::getItem('batch entry', $cacheKeyString);
343 }
344 return $defaults;
345 }
346
347 /**
348 * process the form after the input has been submitted and validated
349 *
350 * @access public
351 *
352 * @return None
353 */
354 public function postProcess() {
355 $params = $this->controller->exportValues($this->_name);
356
357 $params['actualBatchTotal'] = 0;
358
359 // get the profile information
360 if ($this->_batchInfo['type_id'] == 1) {
361 $this->processContribution($params);
362 }
363 else {
364 $this->processMembership($params);
365 }
366
367 // update batch to close status
368 $paramValues = array(
369 'id' => $this->_batchId,
370 // close status
371 'status_id' => 2,
372 'total' => $params['actualBatchTotal'],
373 );
374
375 CRM_Batch_BAO_Batch::create($paramValues);
376
377 // delete from cache table
378 $cacheKeyString = CRM_Batch_BAO_Batch::getCacheKeyForBatch($this->_batchId);
379 CRM_Core_BAO_Cache::deleteGroup('batch entry', $cacheKeyString, FALSE);
380
381 // set success status
382 CRM_Core_Session::setStatus("", ts("Batch Processed."), "success");
383
384 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
385 }
386
387 /**
388 * process contribution records
389 *
390 * @param array $params associated array of submitted values
391 *
392 * @access public
393 *
394 * @return None
395 */
396 private function processContribution(&$params) {
397 $dates = array(
398 'receive_date',
399 'receipt_date',
400 'thankyou_date',
401 'cancel_date',
402 );
403
404 // get the price set associated with offline contribution record.
9da8dc8c 405 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
406 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
6a488035
TO
407 $fieldID = key($this->_priceSet['fields']);
408
6a488035
TO
409 if (isset($params['field'])) {
410 foreach ($params['field'] as $key => $value) {
411 // if contact is not selected we should skip the row
412 if (!CRM_Utils_Array::value($key, $params['primary_contact_select_id'])) {
413 continue;
414 }
415
416 $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_select_id']);
417
418 // update contact information
419 $this->updateContactInfo($value);
420
5ee60152
RN
421 //build soft credit params
422 if (CRM_Utils_Array::value($key, $params['soft_credit_contact_select_id']) && CRM_Utils_Array::value($key, $params['soft_credit_amount'])) {
423 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_select_id'][$key];
0689c15c 424 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
6a488035
TO
425 }
426
427 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
428 CRM_Core_DAO::$_nullObject,
df1f662a 429 NULL,
6a488035
TO
430 'Contribution'
431 );
432
433 foreach ($dates as $val) {
434 if ( CRM_Utils_Array::value( $val, $value ) ) {
435 $value[$val] = CRM_Utils_Date::processDate( $value[$val], $value[$val . '_time'], TRUE );
436 }
437 }
438
439 if (CRM_Utils_Array::value('send_receipt', $value)) {
440 $value['receipt_date'] = date('Y-m-d His');
441 }
442
443 if ($value['financial_type']) {
444 $value['financial_type_id'] = $value['financial_type'];
445 }
446
447 if (CRM_Utils_Array::value('payment_instrument', $value)) {
448 $value['payment_instrument_id'] = $value['payment_instrument'];
449 }
450
451 if (CRM_Utils_Array::value('contribution_source', $value)) {
452 $value['source'] = $value['contribution_source'];
453 }
454
455 if (CRM_Utils_Array::value('contribution_note', $value)) {
456 $value['note'] = $value['contribution_note'];
457 }
458
459 $params['actualBatchTotal'] += $value['total_amount'];
460
461 unset($value['contribution_note']);
462 unset($value['financial_type']);
463 unset($value['contribution_source']);
464
465 $value['batch_id'] = $this->_batchId;
466 $value['skipRecentView'] = TRUE;
467
468 // build line item params
469 $this->_priceSet['fields'][$fieldID]['options'][$fieldID]['amount'] = $value['total_amount'];
470 $value['price_'.$fieldID] = 1;
471
472 $lineItem = array();
9da8dc8c 473 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
6a488035
TO
474
475 //unset amount level since we always use quick config price set
476 unset($value['amount_level']);
477
8ef12e64 478 //CRM-11529 for backoffice transactions
479 //when financial_type_id is passed in form, update the
6a488035
TO
480 //lineitems with the financial type selected in form
481 if (CRM_Utils_Array::value('financial_type_id', $value) && CRM_Utils_Array::value($priceSetId, $lineItem)) {
482 foreach ($lineItem[$priceSetId] as &$values) {
483 $values['financial_type_id'] = $value['financial_type_id'];
484 }
485 }
486 $value['line_item'] = $lineItem;
487
488 //finally call contribution create for all the magic
489 $contribution = CRM_Contribute_BAO_Contribution::create($value, CRM_Core_DAO::$_nullArray);
490
491 //process premiums
492 if (CRM_Utils_Array::value('product_name', $value)) {
493 if ($value['product_name'][0] > 0) {
494 list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
495
496 $value['hidden_Premium'] = 1;
497 $value['product_option'] = CRM_Utils_Array::value(
498 $value['product_name'][1],
499 $options[$value['product_name'][0]]
500 );
501
502 $premiumParams = array(
503 'product_id' => $value['product_name'][0],
504 'contribution_id' => $contribution->id,
505 'product_option' => $value['product_option'],
506 'quantity' => 1,
507 );
508 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
509 }
510 }
511 // end of premium
512
513 //send receipt mail.
514 if ( $contribution->id &&
515 CRM_Utils_Array::value( 'send_receipt', $value ) ) {
516 // add the domain email id
517 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
518 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
519
520 $value['from_email_address'] = $domainEmail;
521 $value['contribution_id'] = $contribution->id;
522 CRM_Contribute_Form_AdditionalInfo::emailReceipt( $this, $value );
523 }
524 }
525 }
526 }
527 //end of function
528
529 /**
530 * process membership records
531 *
532 * @param array $params associated array of submitted values
533 *
534 * @access public
535 *
536 * @return None
537 */
538 private function processMembership(&$params) {
539 $dateTypes = array(
540 'join_date' => 'joinDate',
541 'membership_start_date' => 'startDate',
542 'membership_end_date' => 'endDate'
543 );
8ef12e64 544
6a488035
TO
545 $dates = array(
546 'join_date',
547 'start_date',
548 'end_date',
549 'reminder_date'
550 );
551
552 // get the price set associated with offline memebership
9da8dc8c 553 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
554 $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
6a488035
TO
555
556 if (isset($params['field'])) {
557 $customFields = array();
558 foreach ($params['field'] as $key => $value) {
559 // if contact is not selected we should skip the row
560 if (!CRM_Utils_Array::value($key, $params['primary_contact_select_id'])) {
561 continue;
562 }
563
564 $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_select_id']);
565
566 // update contact information
567 $this->updateContactInfo($value);
568
569 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
570
571 foreach ($dateTypes as $dateField => $dateVariable) {
572 $$dateVariable = CRM_Utils_Date::processDate($value[$dateField]);
573 }
574
575 $calcDates = array();
576 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId,
577 $joinDate, $startDate, $endDate
578 );
579
580 foreach ($calcDates as $memType => $calcDate) {
581 foreach ($dates as $d) {
582 //first give priority to form values then calDates.
583 $date = CRM_Utils_Array::value($d, $value);
584 if (!$date) {
585 $date = CRM_Utils_Array::value($d, $calcDate);
586 }
587
588 $value[$d] = CRM_Utils_Date::processDate($date);
589 }
590 }
591
592 if (CRM_Utils_Array::value('send_receipt', $value)) {
593 $value['receipt_date'] = date('Y-m-d His');
594 }
595
596 if (CRM_Utils_Array::value('membership_source', $value)) {
597 $value['source'] = $value['membership_source'];
598 }
599
600 unset($value['membership_source']);
601
602 //Get the membership status
603 if ( CRM_Utils_Array::value('membership_status', $value) ) {
604 $value['status_id'] = $value['membership_status'];
605 unset($value['membership_status']);
606 }
607
608 if (empty($customFields)) {
609 // membership type custom data
610 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
611
612 $customFields = CRM_Utils_Array::crmArrayMerge($customFields,
613 CRM_Core_BAO_CustomField::getFields('Membership',
614 FALSE, FALSE, NULL, NULL, TRUE
615 )
616 );
617 }
618
619 //check for custom data
620 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key],
621 $customFields,
622 $key,
623 'Membership',
624 $membershipTypeId
625 );
626
627 if (CRM_Utils_Array::value('financial_type', $value)) {
628 $value['financial_type_id'] = $value['financial_type'];
629 }
630
631 if (CRM_Utils_Array::value('payment_instrument', $value)) {
632 $value['payment_instrument_id'] = $value['payment_instrument'];
633 }
634
635 // handle soft credit
afe349ef 636 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'])) {
5ee60152 637 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_select_id'][$key];
0689c15c 638 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
6a488035
TO
639 }
640
641 if ( CRM_Utils_Array::value('receive_date', $value) ) {
642 $value['receive_date'] = CRM_Utils_Date::processDate( $value['receive_date'], $value['receive_date_time'] , TRUE );
643 }
644
645 $params['actualBatchTotal'] += $value['total_amount'];
646
647 unset($value['financial_type']);
648 unset($value['payment_instrument']);
649
650 $value['batch_id'] = $this->_batchId;
651 $value['skipRecentView'] = TRUE;
652
653 // make entry in line item for contribution
8ef12e64 654
6a488035
TO
655 $editedFieldParams = array(
656 'price_set_id' => $priceSetId,
8ef12e64 657 'name' => $value['membership_type'][0]
6a488035
TO
658 );
659
660 $editedResults = array();
9da8dc8c 661 CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
6a488035
TO
662
663 if (!empty($editedResults)) {
664 unset($this->_priceSet['fields']);
665 $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
666 unset($this->_priceSet['fields'][$editedResults['id']]['options']);
667 $fid = $editedResults['id'];
668 $editedFieldParams = array(
669 'price_field_id' => $editedResults['id'],
670 'membership_type_id' => $value['membership_type_id']
671 );
672
673 $editedResults = array();
9da8dc8c 674 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
6a488035
TO
675 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
676 if (CRM_Utils_Array::value('total_amount', $value)) {
677 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
678 }
679
680 $fieldID = key($this->_priceSet['fields']);
681 $value['price_' . $fieldID] = $editedResults['id'];
682
8ef12e64 683 $lineItem = array();
9da8dc8c 684 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
6a488035
TO
685 $value, $lineItem[$priceSetId]
686 );
687
8ef12e64 688 //CRM-11529 for backoffice transactions
689 //when financial_type_id is passed in form, update the
6a488035
TO
690 //lineitems with the financial type selected in form
691 if (CRM_Utils_Array::value('financial_type_id', $value) && CRM_Utils_Array::value($priceSetId, $lineItem)) {
692 foreach ($lineItem[$priceSetId] as &$values) {
693 $values['financial_type_id'] = $value['financial_type_id'];
694 }
695 }
8ef12e64 696
6a488035
TO
697 $value['lineItems'] = $lineItem;
698 $value['processPriceSet'] = TRUE;
699 }
700 // end of contribution related section
701
702 unset($value['membership_type']);
703 unset($value['membership_start_date']);
704 unset($value['membership_end_date']);
8ef12e64 705
706 $value['is_renew'] = false;
6a488035
TO
707 if ( CRM_Utils_Array::value('member_option', $params) && CRM_Utils_Array::value( $key, $params['member_option'] ) == 2 ) {
708 $this->_params = $params;
8ef12e64 709 $value['is_renew'] = true;
710 $membership = CRM_Member_BAO_Membership::renewMembership(
6a488035
TO
711 $value['contact_id'],
712 $value['membership_type_id'],
713 FALSE, $this, NULL, NULL,
714 $value['custom']
715 );
716
717 // make contribution entry
718 CRM_Member_BAO_Membership::recordMembershipContribution( $value, CRM_Core_DAO::$_nullArray, $membership->id );
8ef12e64 719 }
6a488035
TO
720 else {
721 $membership = CRM_Member_BAO_Membership::create($value, CRM_Core_DAO::$_nullArray);
722 }
723
724 //process premiums
725 if (CRM_Utils_Array::value('product_name', $value)) {
726 if ($value['product_name'][0] > 0) {
727 list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
728
729 $value['hidden_Premium'] = 1;
730 $value['product_option'] = CRM_Utils_Array::value(
731 $value['product_name'][1],
732 $options[$value['product_name'][0]]
733 );
734
735 $premiumParams = array(
736 'product_id' => $value['product_name'][0],
737 'contribution_id' => $value['contribution_id'],
738 'product_option' => $value['product_option'],
739 'quantity' => 1,
740 );
741 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
742 }
743 }
744 // end of premium
745
746 //send receipt mail.
747 if ( $membership->id &&
748 CRM_Utils_Array::value( 'send_receipt', $value ) ) {
749
750 // add the domain email id
751 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
752 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
753
754 $value['from_email_address'] = $domainEmail;
755 $value['membership_id'] = $membership->id;
756 CRM_Member_Form_Membership::emailReceipt( $this, $value, $membership );
757 }
758 }
759 }
afe349ef 760 return TRUE;
6a488035
TO
761 }
762
763 /**
764 * update contact information
765 *
766 * @param array $value associated array of submitted values
767 *
768 * @access public
769 *
770 * @return None
771 */
772 private function updateContactInfo(&$value) {
773 $value['preserveDBName'] = $this->_preserveDefault;
774
775 //parse street address, CRM-7768
776 CRM_Contact_Form_Task_Batch::parseStreetAddress($value, $this);
777
778 CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields,
779 $value['contact_id']
780 );
781 }
afe349ef 782 /**
783 * Function exists purely for unit testing purposes. If you feel tempted to use this in live code
784 * then it probably means there is some functionality that needs to be moved
785 * out of the form layer
786 * @param unknown_type $params
787 */
788 function testProcessMembership($params) {
789 return $this->processMembership($params);
790 }
6a488035
TO
791}
792