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