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