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