6357f3ed4626a9b163a7fc3b3c443a08e7165509
[civicrm-core.git] / CRM / Batch / Form / Entry.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 protected $_rowCount = 1;
45
46 /**
47 * Batch id.
48 */
49 protected $_batchId;
50
51 /**
52 * Batch information.
53 */
54 protected $_batchInfo = array();
55
56 /**
57 * Store the profile id associated with the batch type.
58 */
59 protected $_profileId;
60
61 public $_action;
62
63 public $_mode;
64
65 public $_params;
66
67 public $_membershipId = NULL;
68 /**
69 * When not to reset sort_name.
70 */
71 protected $_preserveDefault = TRUE;
72
73 /**
74 * Contact fields.
75 */
76 protected $_contactFields = array();
77
78 /**
79 * Fields array of fields in the batch profile.
80 * (based on the uf_field table data)
81 * (this can't be protected as it is passed into the CRM_Contact_Form_Task_Batch::parseStreetAddress function
82 * (although a future refactoring might hopefully change that so it uses the api & the function is not
83 * required
84 * @var array
85 */
86 public $_fields = array();
87
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',
192 'last_name',
193 'middle_name',
194 'organization_name',
195 'household_name',
196 );
197
198 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
199 $contactReturnProperties = array();
200 $config = CRM_Core_Config::singleton();
201
202 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
203 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', array(
204 'create' => TRUE,
205 'placeholder' => ts('- select -'),
206 ));
207
208 // special field specific to membership batch udpate
209 if ($this->_batchInfo['type_id'] == 2) {
210 $options = array(
211 1 => ts('Add Membership'),
212 2 => ts('Renew Membership'),
213 );
214 $this->add('select', "member_option[$rowNumber]", '', $options);
215 }
216 if ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
217 $options = array('' => '-select-');
218 $optionTypes = array(
219 '1' => ts('Adjust Pledge Payment Schedule?'),
220 '2' => ts('Adjust Total Pledge Amount?'),
221 );
222 $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes);
223 if (!empty($this->_batchId) && !empty($this->_batchInfo['data']) && !empty($rowNumber)) {
224 $dataValues = json_decode($this->_batchInfo['data'], TRUE);
225 if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) {
226 $pledgeIDs = CRM_Pledge_BAO_Pledge::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]);
227 foreach ($pledgeIDs as $pledgeID) {
228 $pledgePayment = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeID);
229 $options += array($pledgeID => CRM_Utils_Date::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']);
230 }
231 }
232 }
233
234 $this->add('select', "open_pledges[$rowNumber]", '', $options);
235 }
236
237 foreach ($this->_fields as $name => $field) {
238 if (in_array($field['field_type'], $contactTypes)) {
239 $fld = explode('-', $field['name']);
240 $contactReturnProperties[$field['name']] = $fld[0];
241 }
242 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
243
244 if (in_array($field['name'], $preserveDefaultsArray)) {
245 $this->_preserveDefault = FALSE;
246 }
247 }
248 }
249
250 $this->assign('fields', $this->_fields);
251 CRM_Core_Resources::singleton()
252 ->addSetting(array(
253 'contact' => array(
254 'return' => implode(',', $contactReturnProperties),
255 'fieldmap' => array_flip($contactReturnProperties),
256 ),
257 ));
258
259 // don't set the status message when form is submitted.
260 $buttonName = $this->controller->getButtonName('submit');
261
262 if ($suppressFields && $buttonName != '_qf_Entry_next') {
263 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');
264 }
265 }
266
267 /**
268 * Form validations.
269 *
270 * @param array $params
271 * Posted values of the form.
272 * @param array $files
273 * List of errors to be posted back to the form.
274 * @param array $self
275 * Form object.
276 *
277 * @return array
278 * list of errors to be posted back to the form
279 */
280 public static function formRule($params, $files, $self) {
281 $errors = array();
282 $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
283 $fields = array(
284 'total_amount' => 'Amount',
285 'financial_type' => 'Financial Type',
286 'payment_instrument' => 'Paid By',
287 );
288
289 //CRM-16480 if contact is selected, validate financial type and amount field.
290 foreach ($params['field'] as $key => $value) {
291 foreach ($fields as $field => $label) {
292 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
293 $errors["field[$key][$field]"] = ts('%1 is a required field.', array(1 => $label));
294 }
295 }
296 }
297
298 if (!empty($params['_qf_Entry_upload_force'])) {
299 if (!empty($errors)) {
300 return $errors;
301 }
302 return TRUE;
303 }
304
305 $batchTotal = 0;
306 foreach ($params['field'] as $key => $value) {
307 $batchTotal += $value['total_amount'];
308
309 //validate for soft credit fields
310 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
311 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
312 }
313 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'])) {
314 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
315 }
316
317 //membership type is required for membership batch entry
318 if ($self->_batchInfo['type_id'] == $batchTypes['Membership']) {
319 if (empty($value['membership_type'][1])) {
320 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
321 }
322 }
323 }
324 if ($self->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
325 foreach (array_unique($params["open_pledges"]) as $value) {
326 if (!empty($value)) {
327 $duplicateRows = array_keys($params["open_pledges"], $value);
328 }
329 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
330 foreach ($duplicateRows as $key) {
331 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
332 }
333 }
334 }
335 }
336 if ((string) $batchTotal != $self->_batchInfo['total']) {
337 $self->assign('batchAmountMismatch', TRUE);
338 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
339 }
340
341 if (!empty($errors)) {
342 return $errors;
343 }
344
345 $self->assign('batchAmountMismatch', FALSE);
346 return TRUE;
347 }
348
349 /**
350 * Override default cancel action.
351 */
352 public function cancelAction() {
353 // redirect to batch listing
354 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
355 CRM_Utils_System::civiExit();
356 }
357
358 /**
359 * Set default values for the form.
360 *
361 *
362 * @return void
363 */
364 public function setDefaultValues() {
365 if (empty($this->_fields)) {
366 return;
367 }
368
369 // for add mode set smart defaults
370 if ($this->_action & CRM_Core_Action::ADD) {
371 list($currentDate, $currentTime) = CRM_Utils_Date::setDateDefaults(NULL, 'activityDateTime');
372
373 //get all status
374 $allStatus = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
375 $completeStatus = array_search('Completed', $allStatus);
376 $specialFields = array(
377 'join_date' => $currentDate,
378 'receive_date' => $currentDate,
379 'receive_date_time' => $currentTime,
380 'contribution_status_id' => $completeStatus,
381 );
382
383 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
384 foreach ($specialFields as $key => $value) {
385 $defaults['field'][$rowNumber][$key] = $value;
386 }
387 }
388 }
389 else {
390 // get the cached info from data column of civicrm_batch
391 $data = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId, 'data');
392 $defaults = json_decode($data, TRUE);
393 $defaults = $defaults['values'];
394 }
395
396 return $defaults;
397 }
398
399 /**
400 * Process the form after the input has been submitted and validated.
401 *
402 *
403 * @return void
404 */
405 public function postProcess() {
406 $params = $this->controller->exportValues($this->_name);
407 $params['actualBatchTotal'] = 0;
408
409 // get the profile information
410 $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
411 if (in_array($this->_batchInfo['type_id'], array($batchTypes['Pledge Payment'], $batchTypes['Contribution']))) {
412 $this->processContribution($params);
413 }
414 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
415 $this->processMembership($params);
416 }
417
418 // update batch to close status
419 $paramValues = array(
420 'id' => $this->_batchId,
421 // close status
422 'status_id' => CRM_Core_OptionGroup::getValue('batch_status', 'Closed', 'name'),
423 'total' => $params['actualBatchTotal'],
424 );
425
426 CRM_Batch_BAO_Batch::create($paramValues);
427
428 // set success status
429 CRM_Core_Session::setStatus("", ts("Batch Processed."), "success");
430
431 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
432 }
433
434 /**
435 * Process contribution records.
436 *
437 * @param array $params
438 * Associated array of submitted values.
439 *
440 *
441 * @return void
442 */
443 private function processContribution(&$params) {
444 $dates = array(
445 'receive_date',
446 'receipt_date',
447 'thankyou_date',
448 'cancel_date',
449 );
450
451 // get the price set associated with offline contribution record.
452 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
453 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
454 $priceFieldID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldID($this->_priceSet);
455 $priceFieldValueID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldValueID($this->_priceSet);
456
457 if (isset($params['field'])) {
458 foreach ($params['field'] as $key => $value) {
459 // if contact is not selected we should skip the row
460 if (empty($params['primary_contact_id'][$key])) {
461 continue;
462 }
463
464 $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
465
466 // update contact information
467 $this->updateContactInfo($value);
468
469 //build soft credit params
470 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
471 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
472 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
473
474 //CRM-15350: if soft-credit-type profile field is disabled or removed then
475 //we choose configured SCT default value
476 if (!empty($params['soft_credit_type'][$key])) {
477 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
478 }
479 else {
480 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup::getDefaultValue("soft_credit_type");
481 }
482 }
483
484 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
485 CRM_Core_DAO::$_nullObject,
486 NULL,
487 'Contribution'
488 );
489
490 foreach ($dates as $val) {
491 if (!empty($value[$val])) {
492 $value[$val] = CRM_Utils_Date::processDate($value[$val], $value[$val . '_time'], TRUE);
493 }
494 }
495
496 if (!empty($value['send_receipt'])) {
497 $value['receipt_date'] = date('Y-m-d His');
498 }
499 // these translations & date handling are required because we are calling BAO directly rather than the api
500 $fieldTranslations = array(
501 'financial_type' => 'financial_type_id',
502 'payment_instrument' => 'payment_instrument_id',
503 'contribution_source' => 'source',
504 'contribution_note' => 'note',
505
506 );
507 foreach ($fieldTranslations as $formField => $baoField) {
508 if (isset($value[$formField])) {
509 $value[$baoField] = $value[$formField];
510 }
511 unset($value[$formField]);
512 }
513
514 $params['actualBatchTotal'] += $value['total_amount'];
515 $value['batch_id'] = $this->_batchId;
516 $value['skipRecentView'] = TRUE;
517
518 // build line item params
519 $this->_priceSet['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
520 $value['price_' . $priceFieldID] = 1;
521
522 $lineItem = array();
523 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
524
525 //unset amount level since we always use quick config price set
526 unset($value['amount_level']);
527
528 //CRM-11529 for back office transactions
529 //when financial_type_id is passed in form, update the
530 //line items with the financial type selected in form
531 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
532 foreach ($lineItem[$priceSetId] as &$values) {
533 $values['financial_type_id'] = $value['financial_type_id'];
534 }
535 }
536 $value['line_item'] = $lineItem;
537 //finally call contribution create for all the magic
538 $contribution = CRM_Contribute_BAO_Contribution::create($value, CRM_Core_DAO::$_nullArray);
539 $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
540 if (!empty($this->_batchInfo['type_id']) && ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment'])) {
541 $adjustTotalAmount = FALSE;
542 if (isset($params['option_type'][$key])) {
543 if ($params['option_type'][$key] == 2) {
544 $adjustTotalAmount = TRUE;
545 }
546 }
547 $pledgeId = $params['open_pledges'][$key];
548 if (is_numeric($pledgeId)) {
549 $result = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId);
550 $pledgePaymentId = 0;
551 foreach ($result as $key => $values) {
552 if ($values['status'] != 'Completed') {
553 $pledgePaymentId = $values['id'];
554 break;
555 }
556 }
557 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id);
558 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId,
559 array($pledgePaymentId),
560 $contribution->contribution_status_id,
561 NULL,
562 $contribution->total_amount,
563 $adjustTotalAmount
564 );
565 }
566 }
567
568 //process premiums
569 if (!empty($value['product_name'])) {
570 if ($value['product_name'][0] > 0) {
571 list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
572
573 $value['hidden_Premium'] = 1;
574 $value['product_option'] = CRM_Utils_Array::value(
575 $value['product_name'][1],
576 $options[$value['product_name'][0]]
577 );
578
579 $premiumParams = array(
580 'product_id' => $value['product_name'][0],
581 'contribution_id' => $contribution->id,
582 'product_option' => $value['product_option'],
583 'quantity' => 1,
584 );
585 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
586 }
587 }
588 // end of premium
589
590 //send receipt mail.
591 if ($contribution->id && !empty($value['send_receipt'])) {
592 // add the domain email id
593 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
594 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
595 $value['from_email_address'] = $domainEmail;
596 $value['contribution_id'] = $contribution->id;
597 CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $value);
598 }
599 }
600 }
601 return TRUE;
602 }
603
604 /**
605 * Process membership records.
606 *
607 * @param array $params
608 * Associated array of submitted values.
609 *
610 *
611 * @return bool
612 */
613 private function processMembership(&$params) {
614 $dateTypes = array(
615 'join_date' => 'joinDate',
616 'membership_start_date' => 'startDate',
617 'membership_end_date' => 'endDate',
618 );
619
620 $dates = array(
621 'join_date',
622 'start_date',
623 'end_date',
624 'reminder_date',
625 );
626
627 // get the price set associated with offline memebership
628 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
629 $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
630
631 if (isset($params['field'])) {
632 $customFields = array();
633 foreach ($params['field'] as $key => $value) {
634 // if contact is not selected we should skip the row
635 if (empty($params['primary_contact_id'][$key])) {
636 continue;
637 }
638
639 $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
640
641 // update contact information
642 $this->updateContactInfo($value);
643
644 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
645
646 foreach ($dateTypes as $dateField => $dateVariable) {
647 $$dateVariable = CRM_Utils_Date::processDate($value[$dateField]);
648 }
649
650 $calcDates = array();
651 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId,
652 $joinDate, $startDate, $endDate
653 );
654
655 foreach ($calcDates as $memType => $calcDate) {
656 foreach ($dates as $d) {
657 //first give priority to form values then calDates.
658 $date = CRM_Utils_Array::value($d, $value);
659 if (!$date) {
660 $date = CRM_Utils_Array::value($d, $calcDate);
661 }
662
663 $value[$d] = CRM_Utils_Date::processDate($date);
664 }
665 }
666
667 if (!empty($value['send_receipt'])) {
668 $value['receipt_date'] = date('Y-m-d His');
669 }
670
671 if (!empty($value['membership_source'])) {
672 $value['source'] = $value['membership_source'];
673 }
674
675 unset($value['membership_source']);
676
677 //Get the membership status
678 if (!empty($value['membership_status'])) {
679 $value['status_id'] = $value['membership_status'];
680 unset($value['membership_status']);
681 }
682
683 if (empty($customFields)) {
684 // membership type custom data
685 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
686
687 $customFields = CRM_Utils_Array::crmArrayMerge($customFields,
688 CRM_Core_BAO_CustomField::getFields('Membership',
689 FALSE, FALSE, NULL, NULL, TRUE
690 )
691 );
692 }
693
694 //check for custom data
695 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key],
696 $customFields,
697 $key,
698 'Membership',
699 $membershipTypeId
700 );
701
702 if (!empty($value['financial_type'])) {
703 $value['financial_type_id'] = $value['financial_type'];
704 }
705
706 if (!empty($value['payment_instrument'])) {
707 $value['payment_instrument_id'] = $value['payment_instrument'];
708 }
709
710 // handle soft credit
711 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
712 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
713 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
714
715 //CRM-15350: if soft-credit-type profile field is disabled or removed then
716 //we choose Gift as default value as per Gift Membership rule
717 if (!empty($params['soft_credit_type'][$key])) {
718 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
719 }
720 else {
721 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup::getValue('soft_credit_type', 'Gift', 'name');
722 }
723 }
724
725 if (!empty($value['receive_date'])) {
726 $value['receive_date'] = CRM_Utils_Date::processDate($value['receive_date'], $value['receive_date_time'], TRUE);
727 }
728
729 $params['actualBatchTotal'] += $value['total_amount'];
730
731 unset($value['financial_type']);
732 unset($value['payment_instrument']);
733
734 $value['batch_id'] = $this->_batchId;
735 $value['skipRecentView'] = TRUE;
736
737 // make entry in line item for contribution
738
739 $editedFieldParams = array(
740 'price_set_id' => $priceSetId,
741 'name' => $value['membership_type'][0],
742 );
743
744 $editedResults = array();
745 CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
746
747 if (!empty($editedResults)) {
748 unset($this->_priceSet['fields']);
749 $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
750 unset($this->_priceSet['fields'][$editedResults['id']]['options']);
751 $fid = $editedResults['id'];
752 $editedFieldParams = array(
753 'price_field_id' => $editedResults['id'],
754 'membership_type_id' => $value['membership_type_id'],
755 );
756
757 $editedResults = array();
758 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
759 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
760 if (!empty($value['total_amount'])) {
761 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
762 }
763
764 $fieldID = key($this->_priceSet['fields']);
765 $value['price_' . $fieldID] = $editedResults['id'];
766
767 $lineItem = array();
768 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
769 $value, $lineItem[$priceSetId]
770 );
771
772 //CRM-11529 for backoffice transactions
773 //when financial_type_id is passed in form, update the
774 //lineitems with the financial type selected in form
775 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
776 foreach ($lineItem[$priceSetId] as &$values) {
777 $values['financial_type_id'] = $value['financial_type_id'];
778 }
779 }
780
781 $value['lineItems'] = $lineItem;
782 $value['processPriceSet'] = TRUE;
783 }
784 // end of contribution related section
785
786 unset($value['membership_type']);
787 unset($value['membership_start_date']);
788 unset($value['membership_end_date']);
789
790 $value['is_renew'] = FALSE;
791 if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
792 $this->_params = $params;
793 $value['is_renew'] = TRUE;
794 $membership = CRM_Member_BAO_Membership::renewMembershipFormWrapper(
795 $value['contact_id'],
796 $value['membership_type_id'],
797 FALSE, $this, NULL, NULL,
798 $value['custom']
799 );
800
801 // make contribution entry
802 $contrbutionParams = array_merge($value, array('membership_id' => $membership->id));
803 CRM_Member_BAO_Membership::recordMembershipContribution($contrbutionParams);
804 }
805 else {
806 $membership = CRM_Member_BAO_Membership::create($value, CRM_Core_DAO::$_nullArray);
807 }
808
809 //process premiums
810 if (!empty($value['product_name'])) {
811 if ($value['product_name'][0] > 0) {
812 list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
813
814 $value['hidden_Premium'] = 1;
815 $value['product_option'] = CRM_Utils_Array::value(
816 $value['product_name'][1],
817 $options[$value['product_name'][0]]
818 );
819
820 $premiumParams = array(
821 'product_id' => $value['product_name'][0],
822 'contribution_id' => CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id'),
823 'product_option' => $value['product_option'],
824 'quantity' => 1,
825 );
826 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
827 }
828 }
829 // end of premium
830
831 //send receipt mail.
832 if ($membership->id && !empty($value['send_receipt'])) {
833
834 // add the domain email id
835 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
836 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
837
838 $value['from_email_address'] = $domainEmail;
839 $value['membership_id'] = $membership->id;
840 $value['contribution_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id');
841 CRM_Member_Form_Membership::emailReceipt($this, $value, $membership);
842 }
843 }
844 }
845 return TRUE;
846 }
847
848 /**
849 * Update contact information.
850 *
851 * @param array $value
852 * Associated array of submitted values.
853 *
854 *
855 * @return void
856 */
857 private function updateContactInfo(&$value) {
858 $value['preserveDBName'] = $this->_preserveDefault;
859
860 //parse street address, CRM-7768
861 CRM_Contact_Form_Task_Batch::parseStreetAddress($value, $this);
862
863 CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields,
864 $value['contact_id']
865 );
866 }
867
868 /**
869 * Function exists purely for unit testing purposes. If you feel tempted to use this in live code
870 * then it probably means there is some functionality that needs to be moved
871 * out of the form layer
872 *
873 * @param array $params
874 *
875 * @return bool
876 */
877 public function testProcessMembership($params) {
878 return $this->processMembership($params);
879 }
880
881 /**
882 * Function exists purely for unit testing purposes. If you feel tempted to use this in live code
883 * then it probably means there is some functionality that needs to be moved
884 * out of the form layer
885 *
886 * @param array $params
887 *
888 * @return bool
889 */
890 public function testProcessContribution($params) {
891 return $this->processContribution($params);
892 }
893
894 }