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