Merge pull request #11732 from twomice/CRM-21811_optimize_search_reciprocal_relations...
[civicrm-core.git] / CRM / Batch / Form / Entry.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
32 */
33
34 /**
35 * This class provides the functionality for batch entry for contributions/memberships.
36 */
37 class CRM_Batch_Form_Entry extends CRM_Core_Form {
38
39 /**
40 * Maximum profile fields that will be displayed.
41 */
42 protected $_rowCount = 1;
43
44 /**
45 * Batch id.
46 */
47 protected $_batchId;
48
49 /**
50 * Batch information.
51 */
52 protected $_batchInfo = array();
53
54 /**
55 * Store the profile id associated with the batch type.
56 */
57 protected $_profileId;
58
59 public $_action;
60
61 public $_mode;
62
63 public $_params;
64
65 /**
66 * When not to reset sort_name.
67 */
68 protected $_preserveDefault = TRUE;
69
70 /**
71 * Contact fields.
72 */
73 protected $_contactFields = array();
74
75 /**
76 * Fields array of fields in the batch profile.
77 * (based on the uf_field table data)
78 * (this can't be protected as it is passed into the CRM_Contact_Form_Task_Batch::parseStreetAddress function
79 * (although a future refactoring might hopefully change that so it uses the api & the function is not
80 * required
81 * @var array
82 */
83 public $_fields = array();
84
85 /**
86 * Monetary fields that may be submitted.
87 *
88 * These should get a standardised format in the beginPostProcess function.
89 *
90 * These fields are common to many forms. Some may override this.
91 */
92 protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount'];
93
94 /**
95 * Build all the data structures needed to build the form.
96 */
97 public function preProcess() {
98 $this->_batchId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
99
100 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
101
102 if (empty($this->_batchInfo)) {
103 $params = array('id' => $this->_batchId);
104 CRM_Batch_BAO_Batch::retrieve($params, $this->_batchInfo);
105
106 $this->assign('batchTotal', !empty($this->_batchInfo['total']) ? $this->_batchInfo['total'] : NULL);
107 $this->assign('batchType', $this->_batchInfo['type_id']);
108
109 // get the profile id associted with this batch type
110 $this->_profileId = CRM_Batch_BAO_Batch::getProfileId($this->_batchInfo['type_id']);
111 }
112 CRM_Core_Resources::singleton()
113 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
114 ->addSetting(array('batch' => array('type_id' => $this->_batchInfo['type_id'])))
115 ->addSetting(array('setting' => array('monetaryThousandSeparator' => CRM_Core_Config::singleton()->monetaryThousandSeparator)))
116 ->addSetting(array('setting' => array('monetaryDecimalPoint' => CRM_Core_Config::singleton()->monetaryDecimalPoint)));
117
118 }
119
120 /**
121 * Set Batch ID.
122 *
123 * @param int $id
124 */
125 public function setBatchID($id) {
126 $this->_batchId = $id;
127 }
128
129 /**
130 * Build the form object.
131 */
132 public function buildQuickForm() {
133 if (!$this->_profileId) {
134 CRM_Core_Error::fatal(ts('Profile for bulk data entry is missing.'));
135 }
136
137 $this->addElement('hidden', 'batch_id', $this->_batchId);
138
139 $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
140 // get the profile information
141 if ($this->_batchInfo['type_id'] == $batchTypes['Contribution']) {
142 CRM_Utils_System::setTitle(ts('Batch Data Entry for Contributions'));
143 $customFields = CRM_Core_BAO_CustomField::getFields('Contribution');
144 }
145 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
146 CRM_Utils_System::setTitle(ts('Batch Data Entry for Memberships'));
147 }
148 elseif ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
149 CRM_Utils_System::setTitle(ts('Batch Data Entry for Pledge Payments'));
150 }
151 $this->_fields = array();
152 $this->_fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, CRM_Core_Action::VIEW);
153
154 // remove file type field and then limit fields
155 $suppressFields = FALSE;
156 foreach ($this->_fields as $name => $field) {
157 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && $this->_fields[$name]['html_type'] == 'Autocomplete-Select') {
158 $suppressFields = TRUE;
159 unset($this->_fields[$name]);
160 }
161
162 //fix to reduce size as we are using this field in grid
163 if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) {
164 //shrink class to "form-text-medium"
165 $this->_fields[$name]['attributes']['size'] = 19;
166 }
167 }
168
169 $this->addFormRule(array('CRM_Batch_Form_Entry', 'formRule'), $this);
170
171 // add the force save button
172 $forceSave = $this->getButtonName('upload', 'force');
173
174 $this->addElement('submit',
175 $forceSave,
176 ts('Ignore Mismatch & Process the Batch?')
177 );
178
179 $this->addButtons(array(
180 array(
181 'type' => 'upload',
182 'name' => ts('Validate & Process the Batch'),
183 'isDefault' => TRUE,
184 ),
185 array(
186 'type' => 'cancel',
187 'name' => ts('Save & Continue Later'),
188 ),
189 )
190 );
191
192 $this->assign('rowCount', $this->_batchInfo['item_count'] + 1);
193
194 $preserveDefaultsArray = array(
195 'first_name',
196 'last_name',
197 'middle_name',
198 'organization_name',
199 'household_name',
200 );
201
202 $contactTypes = array('Contact', 'Individual', 'Household', 'Organization');
203 $contactReturnProperties = array();
204
205 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
206 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', array(
207 'create' => TRUE,
208 'placeholder' => ts('- select -'),
209 ));
210
211 // special field specific to membership batch udpate
212 if ($this->_batchInfo['type_id'] == 2) {
213 $options = array(
214 1 => ts('Add Membership'),
215 2 => ts('Renew Membership'),
216 );
217 $this->add('select', "member_option[$rowNumber]", '', $options);
218 }
219 if ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
220 $options = array('' => '-select-');
221 $optionTypes = array(
222 '1' => ts('Adjust Pledge Payment Schedule?'),
223 '2' => ts('Adjust Total Pledge Amount?'),
224 );
225 $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes);
226 if (!empty($this->_batchId) && !empty($this->_batchInfo['data']) && !empty($rowNumber)) {
227 $dataValues = json_decode($this->_batchInfo['data'], TRUE);
228 if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) {
229 $pledgeIDs = CRM_Pledge_BAO_Pledge::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]);
230 foreach ($pledgeIDs as $pledgeID) {
231 $pledgePayment = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeID);
232 $options += array($pledgeID => CRM_Utils_Date::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']);
233 }
234 }
235 }
236
237 $this->add('select', "open_pledges[$rowNumber]", '', $options);
238 }
239
240 foreach ($this->_fields as $name => $field) {
241 if (in_array($field['field_type'], $contactTypes)) {
242 $fld = explode('-', $field['name']);
243 $contactReturnProperties[$field['name']] = $fld[0];
244 }
245 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
246
247 if (in_array($field['name'], $preserveDefaultsArray)) {
248 $this->_preserveDefault = FALSE;
249 }
250 }
251 }
252
253 // CRM-19477: Display Error for Batch Sizes Exceeding php.ini max_input_vars
254 // Notes: $this->_elementIndex gives an approximate count of the variables being sent
255 // An offset value is set to deal with additional vars that are likely passed.
256 // There may be a more accurate way to do this...
257 $offset = 50; // set an offset to account for other vars we are not counting
258 if ((count($this->_elementIndex) + $offset) > ini_get("max_input_vars")) {
259 CRM_Core_Error::fatal(ts('Batch size is too large. Increase value of php.ini setting "max_input_vars" (current val = ' . ini_get("max_input_vars") . ')'));
260 }
261
262 $this->assign('fields', $this->_fields);
263 CRM_Core_Resources::singleton()
264 ->addSetting(array(
265 'contact' => array(
266 'return' => implode(',', $contactReturnProperties),
267 'fieldmap' => array_flip($contactReturnProperties),
268 ),
269 ));
270
271 // don't set the status message when form is submitted.
272 $buttonName = $this->controller->getButtonName('submit');
273
274 if ($suppressFields && $buttonName != '_qf_Entry_next') {
275 CRM_Core_Session::setStatus(ts("File type field(s) in the selected profile are not supported for Update multiple records."), ts('Some Fields Excluded'), 'info');
276 }
277 }
278
279 /**
280 * Form validations.
281 *
282 * @param array $params
283 * Posted values of the form.
284 * @param array $files
285 * List of errors to be posted back to the form.
286 * @param \CRM_Batch_Form_Entry $self
287 * Form object.
288 *
289 * @return array
290 * list of errors to be posted back to the form
291 */
292 public static function formRule($params, $files, $self) {
293 $errors = array();
294 $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
295 $fields = array(
296 'total_amount' => ts('Amount'),
297 'financial_type' => ts('Financial Type'),
298 'payment_instrument' => ts('Payment Method'),
299 );
300
301 //CRM-16480 if contact is selected, validate financial type and amount field.
302 foreach ($params['field'] as $key => $value) {
303 if (isset($value['trxn_id'])) {
304 if (0 < CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', array(1 => array($value['trxn_id'], 'String')))) {
305 $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database');
306 }
307 }
308 foreach ($fields as $field => $label) {
309 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
310 $errors["field[$key][$field]"] = ts('%1 is a required field.', array(1 => $label));
311 }
312 }
313 }
314
315 if (!empty($params['_qf_Entry_upload_force'])) {
316 if (!empty($errors)) {
317 return $errors;
318 }
319 return TRUE;
320 }
321
322 $batchTotal = 0;
323 foreach ($params['field'] as $key => $value) {
324 $batchTotal += $value['total_amount'];
325
326 //validate for soft credit fields
327 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
328 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
329 }
330 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'])) {
331 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
332 }
333
334 //membership type is required for membership batch entry
335 if ($self->_batchInfo['type_id'] == $batchTypes['Membership']) {
336 if (empty($value['membership_type'][1])) {
337 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
338 }
339 }
340 }
341 if ($self->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
342 foreach (array_unique($params["open_pledges"]) as $value) {
343 if (!empty($value)) {
344 $duplicateRows = array_keys($params["open_pledges"], $value);
345 }
346 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
347 foreach ($duplicateRows as $key) {
348 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
349 }
350 }
351 }
352 }
353 if ((string) $batchTotal != $self->_batchInfo['total']) {
354 $self->assign('batchAmountMismatch', TRUE);
355 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
356 }
357
358 if (!empty($errors)) {
359 return $errors;
360 }
361
362 $self->assign('batchAmountMismatch', FALSE);
363 return TRUE;
364 }
365
366 /**
367 * Override default cancel action.
368 */
369 public function cancelAction() {
370 // redirect to batch listing
371 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
372 CRM_Utils_System::civiExit();
373 }
374
375 /**
376 * Set default values for the form.
377 */
378 public function setDefaultValues() {
379 if (empty($this->_fields)) {
380 return;
381 }
382
383 // for add mode set smart defaults
384 if ($this->_action & CRM_Core_Action::ADD) {
385 $currentDate = date('Y-m-d H-i-s');
386
387 $completeStatus = CRM_Contribute_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
388 $specialFields = array(
389 'join_date' => date('Y-m-d'),
390 'receive_date' => $currentDate,
391 'contribution_status_id' => $completeStatus,
392 );
393
394 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
395 foreach ($specialFields as $key => $value) {
396 $defaults['field'][$rowNumber][$key] = $value;
397 }
398 }
399 }
400 else {
401 // get the cached info from data column of civicrm_batch
402 $data = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId, 'data');
403 $defaults = json_decode($data, TRUE);
404 $defaults = $defaults['values'];
405 }
406
407 return $defaults;
408 }
409
410 /**
411 * Process the form after the input has been submitted and validated.
412 */
413 public function postProcess() {
414 $params = $this->controller->exportValues($this->_name);
415 $params['actualBatchTotal'] = 0;
416
417 // get the profile information
418 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
419 if (in_array($this->_batchInfo['type_id'], array($batchTypes['Pledge Payment'], $batchTypes['Contribution']))) {
420 $this->processContribution($params);
421 }
422 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
423 $this->processMembership($params);
424 }
425
426 // update batch to close status
427 $paramValues = array(
428 'id' => $this->_batchId,
429 // close status
430 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'),
431 'total' => $params['actualBatchTotal'],
432 );
433
434 CRM_Batch_BAO_Batch::create($paramValues);
435
436 // set success status
437 CRM_Core_Session::setStatus("", ts("Batch Processed."), "success");
438
439 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
440 }
441
442 /**
443 * Process contribution records.
444 *
445 * @param array $params
446 * Associated array of submitted values.
447 *
448 * @return bool
449 */
450 private function processContribution(&$params) {
451
452 foreach ($this->submittableMoneyFields as $moneyField) {
453 foreach ($params['field'] as $index => $fieldValues) {
454 if (isset($fieldValues[$moneyField])) {
455 $params['field'][$index][$moneyField] = CRM_Utils_Rule::cleanMoney($params['field'][$index][$moneyField]);
456 }
457 }
458 }
459 $params['actualBatchTotal'] = CRM_Utils_Rule::cleanMoney($params['actualBatchTotal']);
460 // get the price set associated with offline contribution record.
461 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
462 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
463 $priceFieldID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldID($this->_priceSet);
464 $priceFieldValueID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldValueID($this->_priceSet);
465
466 if (isset($params['field'])) {
467 foreach ($params['field'] as $key => $value) {
468 // if contact is not selected we should skip the row
469 if (empty($params['primary_contact_id'][$key])) {
470 continue;
471 }
472
473 $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
474
475 // update contact information
476 $this->updateContactInfo($value);
477
478 //build soft credit params
479 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
480 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
481 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
482
483 //CRM-15350: if soft-credit-type profile field is disabled or removed then
484 //we choose configured SCT default value
485 if (!empty($params['soft_credit_type'][$key])) {
486 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
487 }
488 else {
489 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup::getDefaultValue("soft_credit_type");
490 }
491 }
492
493 // Build PCP params
494 if (!empty($params['pcp_made_through_id'][$key])) {
495 $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key];
496 $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]);
497 if (!empty($params['pcp_roll_nickname'][$key])) {
498 $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key];
499 }
500 if (!empty($params['pcp_personal_note'][$key])) {
501 $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key];
502 }
503 }
504
505 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
506 NULL,
507 'Contribution'
508 );
509
510 if (!empty($value['send_receipt'])) {
511 $value['receipt_date'] = date('Y-m-d His');
512 }
513 // these translations & date handling are required because we are calling BAO directly rather than the api
514 $fieldTranslations = array(
515 'financial_type' => 'financial_type_id',
516 'payment_instrument' => 'payment_instrument_id',
517 'contribution_source' => 'source',
518 'contribution_note' => 'note',
519
520 );
521 foreach ($fieldTranslations as $formField => $baoField) {
522 if (isset($value[$formField])) {
523 $value[$baoField] = $value[$formField];
524 }
525 unset($value[$formField]);
526 }
527
528 $params['actualBatchTotal'] += $value['total_amount'];
529 $value['batch_id'] = $this->_batchId;
530 $value['skipRecentView'] = TRUE;
531
532 // build line item params
533 $this->_priceSet['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
534 $value['price_' . $priceFieldID] = 1;
535
536 $lineItem = array();
537 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
538
539 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
540 // function to get correct amount level consistently. Remove setting of the amount level in
541 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
542 // to cover all variants.
543 unset($value['amount_level']);
544
545 //CRM-11529 for back office transactions
546 //when financial_type_id is passed in form, update the
547 //line items with the financial type selected in form
548 // @todo - create a price set or price field per financial type & simply choose the appropriate
549 // price field rather than working around the fact that each price_field is supposed to have a financial
550 // type & we are allowing that to be overridden.
551 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
552 foreach ($lineItem[$priceSetId] as &$values) {
553 $values['financial_type_id'] = $value['financial_type_id'];
554 }
555 }
556 $value['line_item'] = $lineItem;
557 $value['skipCleanMoney'] = TRUE;
558 //finally call contribution create for all the magic
559 $contribution = CRM_Contribute_BAO_Contribution::create($value);
560 $batchTypes = CRM_Core_Pseudoconstant::get('CRM_Batch_DAO_Batch', 'type_id', array('flip' => 1), 'validate');
561 if (!empty($this->_batchInfo['type_id']) && ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment'])) {
562 $adjustTotalAmount = FALSE;
563 if (isset($params['option_type'][$key])) {
564 if ($params['option_type'][$key] == 2) {
565 $adjustTotalAmount = TRUE;
566 }
567 }
568 $pledgeId = $params['open_pledges'][$key];
569 if (is_numeric($pledgeId)) {
570 $result = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId);
571 $pledgePaymentId = 0;
572 foreach ($result as $key => $values) {
573 if ($values['status'] != 'Completed') {
574 $pledgePaymentId = $values['id'];
575 break;
576 }
577 }
578 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id);
579 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId,
580 array($pledgePaymentId),
581 $contribution->contribution_status_id,
582 NULL,
583 $contribution->total_amount,
584 $adjustTotalAmount
585 );
586 }
587 }
588
589 //process premiums
590 if (!empty($value['product_name'])) {
591 if ($value['product_name'][0] > 0) {
592 list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
593
594 $value['hidden_Premium'] = 1;
595 $value['product_option'] = CRM_Utils_Array::value(
596 $value['product_name'][1],
597 $options[$value['product_name'][0]]
598 );
599
600 $premiumParams = array(
601 'product_id' => $value['product_name'][0],
602 'contribution_id' => $contribution->id,
603 'product_option' => $value['product_option'],
604 'quantity' => 1,
605 );
606 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
607 }
608 }
609 // end of premium
610
611 //send receipt mail.
612 if ($contribution->id && !empty($value['send_receipt'])) {
613 // add the domain email id
614 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
615 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
616 $value['from_email_address'] = $domainEmail;
617 $value['contribution_id'] = $contribution->id;
618 if (!empty($value['soft_credit'])) {
619 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id));
620 }
621 CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $value);
622 }
623 }
624 }
625 return TRUE;
626 }
627
628 /**
629 * Process membership records.
630 *
631 * @param array $params
632 * Associated array of submitted values.
633 *
634 *
635 * @return bool
636 */
637 private function processMembership(&$params) {
638
639 // get the price set associated with offline membership
640 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
641 $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
642
643 if (isset($params['field'])) {
644 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
645 $customFields = array();
646 foreach ($params['field'] as $key => $value) {
647 foreach ($value as $fieldKey => $fieldValue) {
648 if (isset($this->_fields[$fieldKey]) && $this->_fields[$fieldKey]['data_type'] === 'Money') {
649 $value[$fieldKey] = CRM_Utils_Rule::cleanMoney($fieldValue);
650 }
651 }
652 // if contact is not selected we should skip the row
653 if (empty($params['primary_contact_id'][$key])) {
654 continue;
655 }
656
657 $value['contact_id'] = CRM_Utils_Array::value($key, $params['primary_contact_id']);
658
659 // update contact information
660 $this->updateContactInfo($value);
661
662 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
663
664 if (!empty($value['send_receipt'])) {
665 $value['receipt_date'] = date('Y-m-d His');
666 }
667
668 if (!empty($value['membership_source'])) {
669 $value['source'] = $value['membership_source'];
670 }
671
672 unset($value['membership_source']);
673
674 //Get the membership status
675 if (!empty($value['membership_status'])) {
676 $value['status_id'] = $value['membership_status'];
677 unset($value['membership_status']);
678 }
679
680 if (empty($customFields)) {
681 // membership type custom data
682 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
683
684 $customFields = CRM_Utils_Array::crmArrayMerge($customFields,
685 CRM_Core_BAO_CustomField::getFields('Membership',
686 FALSE, FALSE, NULL, NULL, TRUE
687 )
688 );
689 }
690
691 //check for custom data
692 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key],
693 $key,
694 'Membership',
695 $membershipTypeId
696 );
697
698 if (!empty($value['financial_type'])) {
699 $value['financial_type_id'] = $value['financial_type'];
700 }
701
702 if (!empty($value['payment_instrument'])) {
703 $value['payment_instrument_id'] = $value['payment_instrument'];
704 }
705
706 // handle soft credit
707 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
708 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
709 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
710
711 //CRM-15350: if soft-credit-type profile field is disabled or removed then
712 //we choose Gift as default value as per Gift Membership rule
713 if (!empty($params['soft_credit_type'][$key])) {
714 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
715 }
716 else {
717 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
718 }
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
780 $value['is_renew'] = FALSE;
781 if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
782
783 // The following parameter setting may be obsolete.
784 $this->_params = $params;
785 $value['is_renew'] = TRUE;
786 $isPayLater = CRM_Utils_Array::value('is_pay_later', $params);
787 $campaignId = NULL;
788 if (isset($this->_values) && is_array($this->_values) && !empty($this->_values)) {
789 $campaignId = CRM_Utils_Array::value('campaign_id', $this->_params);
790 if (!array_key_exists('campaign_id', $this->_params)) {
791 $campaignId = CRM_Utils_Array::value('campaign_id', $this->_values);
792 }
793 }
794
795 $formDates = array(
796 'end_date' => CRM_Utils_Array::value('membership_end_date', $value),
797 'start_date' => CRM_Utils_Array::value('membership_start_date', $value),
798 );
799 $membershipSource = CRM_Utils_Array::value('source', $value);
800 list($membership) = CRM_Member_BAO_Membership::processMembership(
801 $value['contact_id'], $value['membership_type_id'], FALSE,
802 //$numTerms should be default to 1.
803 NULL, NULL, $value['custom'], 1, NULL, FALSE,
804 NULL, $membershipSource, $isPayLater, $campaignId, $formDates
805 );
806
807 // make contribution entry
808 $contrbutionParams = array_merge($value, array('membership_id' => $membership->id));
809 $contrbutionParams['skipCleanMoney'] = TRUE;
810 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
811 // This form should set the correct params & not call this fn directly.
812 CRM_Member_BAO_Membership::recordMembershipContribution($contrbutionParams);
813 }
814 else {
815 $dateTypes = array(
816 'join_date' => 'joinDate',
817 'membership_start_date' => 'startDate',
818 'membership_end_date' => 'endDate',
819 );
820
821 $dates = array(
822 'join_date',
823 'start_date',
824 'end_date',
825 'reminder_date',
826 );
827 foreach ($dateTypes as $dateField => $dateVariable) {
828 $$dateVariable = CRM_Utils_Date::processDate($value[$dateField]);
829 $fDate[$dateField] = CRM_Utils_Array::value($dateField, $value);
830 }
831
832 $calcDates = array();
833 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId,
834 $joinDate, $startDate, $endDate
835 );
836
837 foreach ($calcDates as $memType => $calcDate) {
838 foreach ($dates as $d) {
839 //first give priority to form values then calDates.
840 $date = CRM_Utils_Array::value($d, $value);
841 if (!$date) {
842 $date = CRM_Utils_Array::value($d, $calcDate);
843 }
844
845 $value[$d] = CRM_Utils_Date::processDate($date);
846 }
847 }
848
849 unset($value['membership_start_date']);
850 unset($value['membership_end_date']);
851 $ids = array();
852 $membership = CRM_Member_BAO_Membership::create($value, $ids);
853 }
854
855 //process premiums
856 if (!empty($value['product_name'])) {
857 if ($value['product_name'][0] > 0) {
858 list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
859
860 $value['hidden_Premium'] = 1;
861 $value['product_option'] = CRM_Utils_Array::value(
862 $value['product_name'][1],
863 $options[$value['product_name'][0]]
864 );
865
866 $premiumParams = array(
867 'product_id' => $value['product_name'][0],
868 'contribution_id' => CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id'),
869 'product_option' => $value['product_option'],
870 'quantity' => 1,
871 );
872 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
873 }
874 }
875 // end of premium
876
877 //send receipt mail.
878 if ($membership->id && !empty($value['send_receipt'])) {
879
880 // add the domain email id
881 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
882 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
883
884 $value['from_email_address'] = $domainEmail;
885 $value['membership_id'] = $membership->id;
886 $value['contribution_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id');
887 CRM_Member_Form_Membership::emailReceipt($this, $value, $membership);
888 }
889 }
890 }
891 return TRUE;
892 }
893
894 /**
895 * Update contact information.
896 *
897 * @param array $value
898 * Associated array of submitted values.
899 */
900 private function updateContactInfo(&$value) {
901 $value['preserveDBName'] = $this->_preserveDefault;
902
903 //parse street address, CRM-7768
904 CRM_Contact_Form_Task_Batch::parseStreetAddress($value, $this);
905
906 CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields,
907 $value['contact_id']
908 );
909 }
910
911 /**
912 * Function exists purely for unit testing purposes.
913 *
914 * If you feel tempted to use this in live code then it probably means there is some functionality
915 * that needs to be moved out of the form layer
916 *
917 * @param array $params
918 *
919 * @return bool
920 */
921 public function testProcessMembership($params) {
922 return $this->processMembership($params);
923 }
924
925 /**
926 * Function exists purely for unit testing purposes.
927 *
928 * If you feel tempted to use this in live code then it probably means there is some functionality
929 * that needs to be moved out of the form layer.
930 *
931 * @param array $params
932 *
933 * @return bool
934 */
935 public function testProcessContribution($params) {
936 return $this->processContribution($params);
937 }
938
939 }