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