Merge pull request #20935 from eileenmcnaughton/hhhh
[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 use Civi\Api4\Contribution;
19
20 /**
21 * This class provides the functionality for batch entry for contributions/memberships.
22 */
23 class CRM_Batch_Form_Entry extends CRM_Core_Form {
24
25 /**
26 * Maximum profile fields that will be displayed.
27 *
28 * @var int
29 */
30 protected $_rowCount = 1;
31
32 /**
33 * Batch id.
34 *
35 * @var int
36 */
37 protected $_batchId;
38
39 /**
40 * Batch information.
41 *
42 * @var array
43 */
44 protected $_batchInfo = [];
45
46 /**
47 * Store the profile id associated with the batch type.
48 * @var int
49 */
50 protected $_profileId;
51
52 public $_action;
53
54 public $_mode;
55
56 public $_params;
57
58 /**
59 * When not to reset sort_name.
60 *
61 * @var bool
62 */
63 protected $_preserveDefault = TRUE;
64
65 /**
66 * Renew option for current row.
67 *
68 * This is as set on the form.
69 *
70 * @var int
71 */
72 protected $currentRowIsRenewOption;
73
74 /**
75 * Contact fields.
76 *
77 * @var array
78 */
79 protected $_contactFields = [];
80
81 /**
82 * Fields array of fields in the batch profile.
83 *
84 * (based on the uf_field table data)
85 * (this can't be protected as it is passed into the CRM_Contact_Form_Task_Batch::parseStreetAddress function
86 * (although a future refactoring might hopefully change that so it uses the api & the function is not
87 * required
88 *
89 * @var array
90 */
91 public $_fields = [];
92
93 /**
94 * @var int
95 */
96 protected $currentRowContributionID;
97
98 /**
99 * Row being processed.
100 *
101 * @var array
102 */
103 protected $currentRow = [];
104
105 /**
106 * @var array
107 */
108 protected $currentRowExistingMembership;
109
110 /**
111 * Get the contribution id for the current row.
112 *
113 * @return int
114 * @throws \CRM_Core_Exception
115 */
116 public function getCurrentRowContributionID(): int {
117 if (!isset($this->currentRowContributionID)) {
118 $this->currentRowContributionID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $this->getCurrentRowMembershipID(), 'contribution_id', 'membership_id');
119 }
120 return $this->currentRowContributionID;
121 }
122
123 /**
124 * Set the contribution ID for the current row.
125 *
126 * @param int $currentRowContributionID
127 */
128 public function setCurrentRowContributionID(int $currentRowContributionID): void {
129 $this->currentRowContributionID = $currentRowContributionID;
130 }
131
132 /**
133 * @return mixed
134 */
135 public function getCurrentRowMembershipID() {
136 return $this->currentRowMembershipID;
137 }
138
139 /**
140 * Get the contact ID for the current row.
141 *
142 * @return int
143 */
144 public function getCurrentRowContactID(): int {
145 return $this->currentRow['contact_id'];
146 }
147
148 /**
149 * Get the membership type ID for the current row.
150 *
151 * @return int
152 */
153 public function getCurrentRowMembershipTypeID(): int {
154 return $this->currentRow['membership_type_id'];
155 }
156
157 /**
158 * Set the membership id for the current row.
159 *
160 * @param int $currentRowMembershipID
161 */
162 public function setCurrentRowMembershipID(int $currentRowMembershipID): void {
163 $this->currentRowMembershipID = $currentRowMembershipID;
164 }
165
166 /**
167 * @var int
168 */
169 protected $currentRowMembershipID;
170
171 /**
172 * Monetary fields that may be submitted.
173 *
174 * These should get a standardised format in the beginPostProcess function.
175 *
176 * These fields are common to many forms. Some may override this.
177 * @var array
178 */
179 protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount'];
180
181 /**
182 * Build all the data structures needed to build the form.
183 *
184 * @throws \CRM_Core_Exception
185 */
186 public function preProcess() {
187 $this->_batchId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
188
189 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
190
191 if (empty($this->_batchInfo)) {
192 $params = ['id' => $this->_batchId];
193 CRM_Batch_BAO_Batch::retrieve($params, $this->_batchInfo);
194
195 $this->assign('batchTotal', !empty($this->_batchInfo['total']) ? $this->_batchInfo['total'] : NULL);
196 $this->assign('batchType', $this->_batchInfo['type_id']);
197
198 // get the profile id associted with this batch type
199 $this->_profileId = CRM_Batch_BAO_Batch::getProfileId($this->_batchInfo['type_id']);
200 }
201 CRM_Core_Resources::singleton()
202 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
203 ->addSetting(['batch' => ['type_id' => $this->_batchInfo['type_id']]])
204 ->addSetting(['setting' => ['monetaryThousandSeparator' => CRM_Core_Config::singleton()->monetaryThousandSeparator]])
205 ->addSetting(['setting' => ['monetaryDecimalPoint' => CRM_Core_Config::singleton()->monetaryDecimalPoint]]);
206
207 $this->assign('defaultCurrencySymbol', CRM_Core_BAO_Country::defaultCurrencySymbol());
208 }
209
210 /**
211 * Set Batch ID.
212 *
213 * @param int $id
214 */
215 public function setBatchID($id) {
216 $this->_batchId = $id;
217 }
218
219 /**
220 * Build the form object.
221 *
222 * @throws \CRM_Core_Exception
223 */
224 public function buildQuickForm() {
225 if (!$this->_profileId) {
226 CRM_Core_Error::statusBounce(ts('Profile for bulk data entry is missing.'));
227 }
228
229 $this->addElement('hidden', 'batch_id', $this->_batchId);
230
231 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
232 // get the profile information
233 if ($this->_batchInfo['type_id'] == $batchTypes['Contribution']) {
234 $this->setTitle(ts('Batch Data Entry for Contributions'));
235 }
236 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
237 $this->setTitle(ts('Batch Data Entry for Memberships'));
238 }
239 elseif ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
240 $this->setTitle(ts('Batch Data Entry for Pledge Payments'));
241 }
242
243 $this->_fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, CRM_Core_Action::VIEW);
244
245 // remove file type field and then limit fields
246 $suppressFields = FALSE;
247 foreach ($this->_fields as $name => $field) {
248 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && $this->_fields[$name]['html_type'] == 'Autocomplete-Select') {
249 $suppressFields = TRUE;
250 unset($this->_fields[$name]);
251 }
252
253 //fix to reduce size as we are using this field in grid
254 if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) {
255 //shrink class to "form-text-medium"
256 $this->_fields[$name]['attributes']['size'] = 19;
257 }
258 }
259
260 $this->addFormRule(['CRM_Batch_Form_Entry', 'formRule'], $this);
261
262 // add the force save button
263 $forceSave = $this->getButtonName('upload', 'force');
264
265 $this->addElement('xbutton',
266 $forceSave,
267 ts('Ignore Mismatch & Process the Batch?'),
268 [
269 'type' => 'submit',
270 'value' => 1,
271 'class' => 'crm-button crm-button_qf_Entry_upload_force-save',
272 ]
273 );
274
275 $this->addButtons([
276 [
277 'type' => 'upload',
278 'name' => ts('Validate & Process the Batch'),
279 'isDefault' => TRUE,
280 ],
281 [
282 'type' => 'cancel',
283 'name' => ts('Save & Continue Later'),
284 ],
285 ]);
286
287 $this->assign('rowCount', $this->_batchInfo['item_count'] + 1);
288
289 $preserveDefaultsArray = [
290 'first_name',
291 'last_name',
292 'middle_name',
293 'organization_name',
294 'household_name',
295 ];
296
297 $contactTypes = ['Contact', 'Individual', 'Household', 'Organization'];
298 $contactReturnProperties = [];
299
300 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
301 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', [
302 'create' => TRUE,
303 'placeholder' => ts('- select -'),
304 ]);
305
306 // special field specific to membership batch udpate
307 if ($this->_batchInfo['type_id'] == 2) {
308 $options = [
309 1 => ts('Add Membership'),
310 2 => ts('Renew Membership'),
311 ];
312 $this->add('select', "member_option[$rowNumber]", '', $options);
313 }
314 if ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
315 $options = ['' => '-select-'];
316 $optionTypes = [
317 '1' => ts('Adjust Pledge Payment Schedule?'),
318 '2' => ts('Adjust Total Pledge Amount?'),
319 ];
320 $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes);
321 if (!empty($this->_batchId) && !empty($this->_batchInfo['data']) && !empty($rowNumber)) {
322 $dataValues = json_decode($this->_batchInfo['data'], TRUE);
323 if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) {
324 $pledgeIDs = CRM_Pledge_BAO_Pledge::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]);
325 foreach ($pledgeIDs as $pledgeID) {
326 $pledgePayment = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeID);
327 $options += [$pledgeID => CRM_Utils_Date::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']];
328 }
329 }
330 }
331
332 $this->add('select', "open_pledges[$rowNumber]", '', $options);
333 }
334
335 foreach ($this->_fields as $name => $field) {
336 if (in_array($field['field_type'], $contactTypes)) {
337 $fld = explode('-', $field['name']);
338 $contactReturnProperties[$field['name']] = $fld[0];
339 }
340 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
341
342 if (in_array($field['name'], $preserveDefaultsArray)) {
343 $this->_preserveDefault = FALSE;
344 }
345 }
346 }
347
348 // CRM-19477: Display Error for Batch Sizes Exceeding php.ini max_input_vars
349 // Notes: $this->_elementIndex gives an approximate count of the variables being sent
350 // An offset value is set to deal with additional vars that are likely passed.
351 // There may be a more accurate way to do this...
352 // set an offset to account for other vars we are not counting
353 $offset = 50;
354 if ((count($this->_elementIndex) + $offset) > ini_get("max_input_vars")) {
355 // Avoiding 'ts' for obscure messages.
356 CRM_Core_Error::statusBounce(ts('Batch size is too large. Increase value of php.ini setting "max_input_vars" (current val = %1)', [1 => ini_get("max_input_vars")]));
357 }
358
359 $this->assign('fields', $this->_fields);
360 CRM_Core_Resources::singleton()
361 ->addSetting([
362 'contact' => [
363 'return' => implode(',', $contactReturnProperties),
364 'fieldmap' => array_flip($contactReturnProperties),
365 ],
366 ]);
367
368 // don't set the status message when form is submitted.
369 $buttonName = $this->controller->getButtonName('submit');
370
371 if ($suppressFields && $buttonName != '_qf_Entry_next') {
372 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');
373 }
374 }
375
376 /**
377 * Form validations.
378 *
379 * @param array $params
380 * Posted values of the form.
381 * @param array $files
382 * List of errors to be posted back to the form.
383 * @param \CRM_Batch_Form_Entry $self
384 * Form object.
385 *
386 * @return array
387 * list of errors to be posted back to the form
388 */
389 public static function formRule($params, $files, $self) {
390 $errors = [];
391 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
392 $fields = [
393 'total_amount' => ts('Amount'),
394 'financial_type' => ts('Financial Type'),
395 'payment_instrument' => ts('Payment Method'),
396 ];
397
398 //CRM-16480 if contact is selected, validate financial type and amount field.
399 foreach ($params['field'] as $key => $value) {
400 if (isset($value['trxn_id'])) {
401 if (0 < CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', [1 => [$value['trxn_id'], 'String']])) {
402 $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database');
403 }
404 }
405 foreach ($fields as $field => $label) {
406 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
407 $errors["field[$key][$field]"] = ts('%1 is a required field.', [1 => $label]);
408 }
409 }
410 }
411
412 if (!empty($params['_qf_Entry_upload_force'])) {
413 if (!empty($errors)) {
414 return $errors;
415 }
416 return TRUE;
417 }
418
419 $batchTotal = 0;
420 foreach ($params['field'] as $key => $value) {
421 $batchTotal += $value['total_amount'];
422
423 //validate for soft credit fields
424 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
425 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
426 }
427 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'])) {
428 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
429 }
430
431 //membership type is required for membership batch entry
432 if ($self->_batchInfo['type_id'] == $batchTypes['Membership']) {
433 if (empty($value['membership_type'][1])) {
434 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
435 }
436 }
437 }
438 if ($self->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
439 foreach (array_unique($params["open_pledges"]) as $value) {
440 if (!empty($value)) {
441 $duplicateRows = array_keys($params["open_pledges"], $value);
442 }
443 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
444 foreach ($duplicateRows as $key) {
445 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
446 }
447 }
448 }
449 }
450 if ((string) $batchTotal != $self->_batchInfo['total']) {
451 $self->assign('batchAmountMismatch', TRUE);
452 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
453 }
454
455 if (!empty($errors)) {
456 return $errors;
457 }
458
459 $self->assign('batchAmountMismatch', FALSE);
460 return TRUE;
461 }
462
463 /**
464 * Override default cancel action.
465 */
466 public function cancelAction() {
467 // redirect to batch listing
468 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
469 CRM_Utils_System::civiExit();
470 }
471
472 /**
473 * Set default values for the form.
474 *
475 * @throws \CRM_Core_Exception
476 */
477 public function setDefaultValues() {
478 if (empty($this->_fields)) {
479 return;
480 }
481
482 // for add mode set smart defaults
483 if ($this->_action & CRM_Core_Action::ADD) {
484 $currentDate = date('Y-m-d H-i-s');
485
486 $completeStatus = CRM_Contribute_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
487 $specialFields = [
488 'membership_join_date' => date('Y-m-d'),
489 'receive_date' => $currentDate,
490 'contribution_status_id' => $completeStatus,
491 ];
492
493 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
494 foreach ($specialFields as $key => $value) {
495 $defaults['field'][$rowNumber][$key] = $value;
496 }
497 }
498 }
499 else {
500 // get the cached info from data column of civicrm_batch
501 $data = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId, 'data');
502 $defaults = json_decode($data, TRUE);
503 $defaults = $defaults['values'];
504 }
505
506 return $defaults;
507 }
508
509 /**
510 * Process the form after the input has been submitted and validated.
511 *
512 * @throws \CRM_Core_Exception
513 * @throws \CiviCRM_API3_Exception
514 */
515 public function postProcess() {
516 $params = $this->controller->exportValues($this->_name);
517 $params['actualBatchTotal'] = 0;
518
519 // get the profile information
520 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
521 if (in_array($this->_batchInfo['type_id'], [$batchTypes['Pledge Payment'], $batchTypes['Contribution']])) {
522 $this->processContribution($params);
523 }
524 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
525 $params['actualBatchTotal'] = $this->processMembership($params);
526 }
527
528 // update batch to close status
529 $paramValues = [
530 'id' => $this->_batchId,
531 // close status
532 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'),
533 'total' => $params['actualBatchTotal'],
534 ];
535
536 CRM_Batch_BAO_Batch::create($paramValues);
537
538 // set success status
539 CRM_Core_Session::setStatus("", ts("Batch Processed."), "success");
540
541 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
542 }
543
544 /**
545 * Process contribution records.
546 *
547 * @param array $params
548 * Associated array of submitted values.
549 *
550 * @return bool
551 *
552 * @throws \CRM_Core_Exception
553 * @throws \CiviCRM_API3_Exception
554 */
555 private function processContribution(&$params) {
556
557 foreach ($this->submittableMoneyFields as $moneyField) {
558 foreach ($params['field'] as $index => $fieldValues) {
559 if (isset($fieldValues[$moneyField])) {
560 $params['field'][$index][$moneyField] = CRM_Utils_Rule::cleanMoney($params['field'][$index][$moneyField]);
561 }
562 }
563 }
564 $params['actualBatchTotal'] = CRM_Utils_Rule::cleanMoney($params['actualBatchTotal']);
565 // get the price set associated with offline contribution record.
566 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
567 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
568 $priceFieldID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldID($this->_priceSet);
569 $priceFieldValueID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldValueID($this->_priceSet);
570
571 if (isset($params['field'])) {
572 foreach ($params['field'] as $key => $value) {
573 // if contact is not selected we should skip the row
574 if (empty($params['primary_contact_id'][$key])) {
575 continue;
576 }
577
578 $value['contact_id'] = $params['primary_contact_id'][$key] ?? NULL;
579
580 // update contact information
581 $this->updateContactInfo($value);
582
583 //build soft credit params
584 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
585 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
586 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
587
588 //CRM-15350: if soft-credit-type profile field is disabled or removed then
589 //we choose configured SCT default value
590 if (!empty($params['soft_credit_type'][$key])) {
591 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
592 }
593 else {
594 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup::getDefaultValue("soft_credit_type");
595 }
596 }
597
598 // Build PCP params
599 if (!empty($params['pcp_made_through_id'][$key])) {
600 $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key];
601 $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]);
602 if (!empty($params['pcp_roll_nickname'][$key])) {
603 $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key];
604 }
605 if (!empty($params['pcp_personal_note'][$key])) {
606 $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key];
607 }
608 }
609
610 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
611 NULL,
612 'Contribution'
613 );
614
615 if (!empty($value['send_receipt'])) {
616 $value['receipt_date'] = date('Y-m-d His');
617 }
618 // these translations & date handling are required because we are calling BAO directly rather than the api
619 $fieldTranslations = [
620 'financial_type' => 'financial_type_id',
621 'payment_instrument' => 'payment_instrument_id',
622 'contribution_source' => 'source',
623 'contribution_note' => 'note',
624 'contribution_check_number' => 'check_number',
625 ];
626 foreach ($fieldTranslations as $formField => $baoField) {
627 if (isset($value[$formField])) {
628 $value[$baoField] = $value[$formField];
629 }
630 unset($value[$formField]);
631 }
632
633 $params['actualBatchTotal'] += $value['total_amount'];
634 $value['batch_id'] = $this->_batchId;
635 $value['skipRecentView'] = TRUE;
636
637 // build line item params
638 $this->_priceSet['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
639 $value['price_' . $priceFieldID] = 1;
640
641 $lineItem = [];
642 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
643
644 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
645 // function to get correct amount level consistently. Remove setting of the amount level in
646 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
647 // to cover all variants.
648 unset($value['amount_level']);
649
650 //CRM-11529 for back office transactions
651 //when financial_type_id is passed in form, update the
652 //line items with the financial type selected in form
653 // @todo - create a price set or price field per financial type & simply choose the appropriate
654 // price field rather than working around the fact that each price_field is supposed to have a financial
655 // type & we are allowing that to be overridden.
656 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
657 foreach ($lineItem[$priceSetId] as &$values) {
658 $values['financial_type_id'] = $value['financial_type_id'];
659 }
660 }
661 $value['line_item'] = $lineItem;
662
663 //finally call contribution create for all the magic
664 $contribution = CRM_Contribute_BAO_Contribution::create($value);
665 // This code to retrieve the contribution has been moved here from the contribution create
666 // api. It may not be required.
667 $titleFields = [
668 'contact_id',
669 'total_amount',
670 'currency',
671 'financial_type_id',
672 ];
673 $retrieveRequired = 0;
674 foreach ($titleFields as $titleField) {
675 if (!isset($contribution->$titleField)) {
676 $retrieveRequired = 1;
677 break;
678 }
679 }
680 if ($retrieveRequired == 1) {
681 $contribution->find(TRUE);
682 }
683 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
684 if (!empty($this->_batchInfo['type_id']) && ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment'])) {
685 $adjustTotalAmount = FALSE;
686 if (isset($params['option_type'][$key])) {
687 if ($params['option_type'][$key] == 2) {
688 $adjustTotalAmount = TRUE;
689 }
690 }
691 $pledgeId = $params['open_pledges'][$key];
692 if (is_numeric($pledgeId)) {
693 $result = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId);
694 $pledgePaymentId = 0;
695 foreach ($result as $key => $values) {
696 if ($values['status'] != 'Completed') {
697 $pledgePaymentId = $values['id'];
698 break;
699 }
700 }
701 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id);
702 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId,
703 [$pledgePaymentId],
704 $contribution->contribution_status_id,
705 NULL,
706 $contribution->total_amount,
707 $adjustTotalAmount
708 );
709 }
710 }
711
712 //process premiums
713 if (!empty($value['product_name'])) {
714 if ($value['product_name'][0] > 0) {
715 [$products, $options] = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
716
717 $value['hidden_Premium'] = 1;
718 $value['product_option'] = CRM_Utils_Array::value(
719 $value['product_name'][1],
720 $options[$value['product_name'][0]]
721 );
722
723 $premiumParams = [
724 'product_id' => $value['product_name'][0],
725 'contribution_id' => $contribution->id,
726 'product_option' => $value['product_option'],
727 'quantity' => 1,
728 ];
729 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
730 }
731 }
732 // end of premium
733
734 //send receipt mail.
735 if ($contribution->id && !empty($value['send_receipt'])) {
736 $value['from_email_address'] = $this->getFromEmailAddress();
737 $value['contribution_id'] = $contribution->id;
738 if (!empty($value['soft_credit'])) {
739 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id));
740 }
741 CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $value);
742 }
743 }
744 }
745 return TRUE;
746 }
747
748 /**
749 * Process membership records.
750 *
751 * @param array $params
752 * Array of submitted values.
753 *
754 * @return float
755 * batch total monetary amount.
756 *
757 * @throws \CRM_Core_Exception
758 * @throws \CiviCRM_API3_Exception
759 * @throws \API_Exception
760 */
761 private function processMembership(array $params) {
762 $batchTotal = 0;
763 // get the price set associated with offline membership
764 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
765 $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
766
767 if (isset($params['field'])) {
768 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
769 foreach ($params['field'] as $key => $value) {
770 // if contact is not selected we should skip the row
771 if (empty($params['primary_contact_id'][$key])) {
772 continue;
773 }
774 $value['contact_id'] = $params['primary_contact_id'][$key];
775 $value = $this->standardiseRow($value);
776 $this->currentRow = $value;
777 $this->currentRowExistingMembership = NULL;
778 $this->currentRowIsRenewOption = (int) ($params['member_option'][$key] ?? 1);
779
780 // update contact information
781 $this->updateContactInfo($value);
782
783 //check for custom data
784 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key],
785 $key,
786 'Membership',
787 $value['membership_type_id']
788 );
789
790 // handle soft credit
791 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
792 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
793 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
794
795 //CRM-15350: if soft-credit-type profile field is disabled or removed then
796 //we choose Gift as default value as per Gift Membership rule
797 if (!empty($params['soft_credit_type'][$key])) {
798 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
799 }
800 else {
801 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
802 }
803 }
804 $batchTotal += $value['total_amount'];
805 $value['batch_id'] = $this->_batchId;
806 $value['skipRecentView'] = TRUE;
807
808 $order = new CRM_Financial_BAO_Order();
809 // We use the override total amount because we are dealing with a
810 // possibly tax_inclusive total, which is assumed for the override total.
811 $order->setOverrideTotalAmount((float) $value['total_amount']);
812 $order->setLineItem([
813 'membership_type_id' => $value['membership_type_id'],
814 'financial_type_id' => $value['financial_type_id'],
815 ], $key);
816
817 if (!empty($order->getLineItems())) {
818 $value['lineItems'] = [$order->getPriceSetID() => $order->getPriceFieldIndexedLineItems()];
819 $value['processPriceSet'] = TRUE;
820 }
821 // end of contribution related section
822
823 $membershipParams = $this->getMembershipParams();
824
825 if ($this->currentRowIsRenew()) {
826 // The following parameter setting may be obsolete.
827 $this->_params = $params;
828
829 $formDates = [
830 'end_date' => $value['membership_end_date'] ?? NULL,
831 'start_date' => $value['membership_start_date'] ?? NULL,
832 ];
833 $membershipSource = $value['source'] ?? NULL;
834 $membership = $this->legacyProcessMembership($value['membership_type_id'],
835 $value['custom'], $membershipSource, ['campaign_id' => $value['member_campaign_id'] ?? NULL], $formDates
836 );
837
838 // make contribution entry
839 $contrbutionParams = array_merge($value, ['membership_id' => $membership->id]);
840 $contrbutionParams['skipCleanMoney'] = TRUE;
841 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
842 // This form should set the correct params & not call this fn directly.
843 CRM_Member_BAO_Membership::recordMembershipContribution($contrbutionParams);
844 $this->setCurrentRowMembershipID($membership->id);
845 }
846 else {
847 // @todo - specify the relevant fields - don't copy all over
848 $membershipParams = array_merge($value, $membershipParams);
849 $membership = CRM_Member_BAO_Membership::create($membershipParams);
850 }
851
852 //process premiums
853 if (!empty($value['product_name'])) {
854 if ($value['product_name'][0] > 0) {
855 [$products, $options] = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
856
857 $value['hidden_Premium'] = 1;
858 $value['product_option'] = CRM_Utils_Array::value(
859 $value['product_name'][1],
860 $options[$value['product_name'][0]]
861 );
862
863 $premiumParams = [
864 'product_id' => $value['product_name'][0],
865 'contribution_id' => $this->getCurrentRowContributionID(),
866 'product_option' => $value['product_option'],
867 'quantity' => 1,
868 ];
869 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
870 }
871 }
872 // end of premium
873
874 //send receipt mail.
875 if ($membership->id && !empty($value['send_receipt'])) {
876 $value['membership_id'] = $membership->id;
877 $this->emailReceipt($this, $value, $membership);
878 }
879 }
880 }
881 return $batchTotal;
882 }
883
884 /**
885 * Send email receipt.
886 *
887 * @param CRM_Core_Form $form
888 * Form object.
889 * @param array $formValues
890 * @param object $membership
891 * Object.
892 *
893 * @return bool
894 * true if mail was sent successfully
895 * @throws \CRM_Core_Exception|\API_Exception
896 *
897 */
898 protected function emailReceipt($form, &$formValues, $membership): bool {
899 // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
900 if (!empty($formValues['payment_instrument_id'])) {
901 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
902 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
903 }
904
905 $form->assign('module', 'Membership');
906 $form->assign('contactID', $formValues['contact_id']);
907
908 $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues)));
909 $this->assign('contributionID', $this->getCurrentRowContributionID());
910
911 if (!empty($formValues['contribution_status_id'])) {
912 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
913 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name'));
914 }
915
916 $form->assign('receiptType', $this->currentRowIsRenew() ? 'membership renewal' : 'membership signup');
917 $form->assign('receive_date', CRM_Utils_Array::value('receive_date', $formValues));
918 $form->assign('formValues', $formValues);
919
920 $form->assign('mem_start_date', CRM_Utils_Date::formatDateOnlyLong($membership->start_date));
921 if (!CRM_Utils_System::isNull($membership->end_date)) {
922 $form->assign('mem_end_date', CRM_Utils_Date::formatDateOnlyLong($membership->end_date));
923 }
924 $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id));
925
926 [$form->_contributorDisplayName, $form->_contributorEmail]
927 = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']);
928 $form->_receiptContactId = $formValues['contact_id'];
929
930 CRM_Core_BAO_MessageTemplate::sendTemplate(
931 [
932 'groupName' => 'msg_tpl_workflow_membership',
933 'valueName' => 'membership_offline_receipt',
934 'contactId' => $form->_receiptContactId,
935 'from' => $this->getFromEmailAddress(),
936 'toName' => $form->_contributorDisplayName,
937 'toEmail' => $form->_contributorEmail,
938 'PDFFilename' => ts('receipt') . '.pdf',
939 'isEmailPdf' => Civi::settings()->get('invoice_is_email_pdf'),
940 'contributionId' => $this->getCurrentRowContributionID(),
941 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW),
942 ]
943 );
944
945 Contribution::update(FALSE)
946 ->addWhere('id', '=', $this->getCurrentRowContributionID())
947 ->setValues(['receipt_date', 'now'])
948 ->execute();
949
950 return TRUE;
951 }
952
953 /**
954 * Update contact information.
955 *
956 * @param array $value
957 * Associated array of submitted values.
958 */
959 private function updateContactInfo(array &$value) {
960 $value['preserveDBName'] = $this->_preserveDefault;
961
962 //parse street address, CRM-7768
963 CRM_Contact_Form_Task_Batch::parseStreetAddress($value, $this);
964
965 CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields,
966 $value['contact_id']
967 );
968 }
969
970 /**
971 * Function exists purely for unit testing purposes.
972 *
973 * If you feel tempted to use this in live code then it probably means there is some functionality
974 * that needs to be moved out of the form layer
975 *
976 * @param array $params
977 *
978 * @return bool
979 */
980 public function testProcessMembership($params) {
981 return $this->processMembership($params);
982 }
983
984 /**
985 * Function exists purely for unit testing purposes.
986 *
987 * If you feel tempted to use this in live code then it probably means there is some functionality
988 * that needs to be moved out of the form layer.
989 *
990 * @param array $params
991 *
992 * @return bool
993 *
994 * @throws \CRM_Core_Exception
995 * @throws \CiviCRM_API3_Exception
996 */
997 public function testProcessContribution($params) {
998 return $this->processContribution($params);
999 }
1000
1001 /**
1002 * @param int $membershipTypeID
1003 * @param $customFieldsFormatted
1004 * @param $membershipSource
1005 * @param $isPayLater
1006 * @param array $memParams
1007 * @param array $formDates
1008 *
1009 * @return CRM_Member_BAO_Membership
1010 *
1011 * @throws \CRM_Core_Exception
1012 * @throws \CiviCRM_API3_Exception
1013 */
1014 protected function legacyProcessMembership($membershipTypeID, $customFieldsFormatted, $membershipSource, $memParams = [], $formDates = []): CRM_Member_DAO_Membership {
1015 $updateStatusId = FALSE;
1016 $changeToday = NULL;
1017 $is_test = FALSE;
1018 $numRenewTerms = 1;
1019 $format = '%Y%m%d';
1020 $ids = [];
1021 $isPayLater = NULL;
1022 $currentMembership = $this->getCurrentMembership();
1023 // @todo - remove this if - still here for now to leave whitespace change out of commit.
1024 if (1) {
1025 // Now Renew the membership
1026 if (!$currentMembership['is_current_member']) {
1027 // membership is not CURRENT
1028
1029 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1030 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'],
1031 $changeToday,
1032 $membershipTypeID,
1033 $numRenewTerms
1034 );
1035
1036 $currentMembership['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1037 foreach (['start_date', 'end_date'] as $dateType) {
1038 $currentMembership[$dateType] = $formDates[$dateType] ?? NULL;
1039 if (empty($currentMembership[$dateType])) {
1040 $currentMembership[$dateType] = $dates[$dateType] ?? NULL;
1041 }
1042 }
1043 $currentMembership['is_test'] = $is_test;
1044
1045 if (!empty($membershipSource)) {
1046 $currentMembership['source'] = $membershipSource;
1047 }
1048
1049 if (!empty($currentMembership['id'])) {
1050 $ids['membership'] = $currentMembership['id'];
1051 }
1052 $memParams = array_merge($currentMembership, $memParams);
1053 $memParams['membership_type_id'] = $membershipTypeID;
1054
1055 //set the log start date.
1056 $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
1057 }
1058 else {
1059
1060 // CURRENT Membership
1061 $membership = new CRM_Member_DAO_Membership();
1062 $membership->id = $currentMembership['id'];
1063 $membership->find(TRUE);
1064 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1065 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id,
1066 $changeToday,
1067 $membershipTypeID,
1068 $numRenewTerms
1069 );
1070
1071 // Insert renewed dates for CURRENT membership
1072 $memParams['join_date'] = CRM_Utils_Date::isoToMysql($membership->join_date);
1073 $memParams['start_date'] = $formDates['start_date'] ?? CRM_Utils_Date::isoToMysql($membership->start_date);
1074 $memParams['end_date'] = $formDates['end_date'] ?? NULL;
1075 if (empty($memParams['end_date'])) {
1076 $memParams['end_date'] = $dates['end_date'] ?? NULL;
1077 }
1078 $memParams['membership_type_id'] = $membershipTypeID;
1079
1080 //set the log start date.
1081 $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
1082
1083 //CRM-18067
1084 if (!empty($membershipSource)) {
1085 $memParams['source'] = $membershipSource;
1086 }
1087 elseif (empty($membership->source)) {
1088 $memParams['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
1089 $currentMembership['id'],
1090 'source'
1091 );
1092 }
1093
1094 if (!empty($currentMembership['id'])) {
1095 $ids['membership'] = $currentMembership['id'];
1096 }
1097 $memParams['membership_activity_status'] = $isPayLater ? 'Scheduled' : 'Completed';
1098 }
1099 }
1100
1101 //CRM-4555
1102 //if we decided status here and want to skip status
1103 //calculation in create( ); then need to pass 'skipStatusCal'.
1104 if ($updateStatusId) {
1105 $memParams['status_id'] = $updateStatusId;
1106 $memParams['skipStatusCal'] = TRUE;
1107 }
1108
1109 //since we are renewing,
1110 //make status override false.
1111 $memParams['is_override'] = FALSE;
1112 $memParams['custom'] = $customFieldsFormatted;
1113 // Load all line items & process all in membership. Don't do in contribution.
1114 // Relevant tests in api_v3_ContributionPageTest.
1115 // @todo stop passing $ids (membership and userId may be set by this point)
1116 $membership = CRM_Member_BAO_Membership::create($memParams, $ids);
1117
1118 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1119 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
1120 $membership->find(TRUE);
1121
1122 return $membership;
1123 }
1124
1125 /**
1126 * @return string
1127 * @throws \CRM_Core_Exception
1128 */
1129 private function getFromEmailAddress(): string {
1130 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
1131 return "$domainEmail[0] <$domainEmail[1]>";
1132 }
1133
1134 /**
1135 * Standardise the values in the row from profile-weirdness to civi-standard.
1136 *
1137 * The row uses odd field names such as financial_type rather than financial
1138 * type id. We standardise at this point.
1139 *
1140 * @param array $row
1141 *
1142 * @return array
1143 */
1144 private function standardiseRow(array $row): array {
1145 foreach ($row as $fieldKey => $fieldValue) {
1146 if (isset($this->_fields[$fieldKey]) && $this->_fields[$fieldKey]['data_type'] === 'Money') {
1147 $row[$fieldKey] = CRM_Utils_Rule::cleanMoney($fieldValue);
1148 }
1149 }
1150 $renameFieldMapping = [
1151 'financial_type' => 'financial_type_id',
1152 'payment_instrument' => 'payment_instrument_id',
1153 'membership_source' => 'source',
1154 'membership_status' => 'status_id',
1155 ];
1156 foreach ($renameFieldMapping as $weirdProfileName => $betterName) {
1157 // Check if isset as some like payment instrument and source are optional.
1158 if (isset($row[$weirdProfileName]) && empty($row[$betterName])) {
1159 $row[$betterName] = $row[$weirdProfileName];
1160 unset($row[$weirdProfileName]);
1161 }
1162 }
1163
1164 // The latter format would be normal here - it's unclear if it is sometimes in the former format.
1165 $row['membership_type_id'] = $row['membership_type_id'] ?? $row['membership_type'][1];
1166 unset($row['membership_type']);
1167 // total_amount is required.
1168 $row['total_amount'] = (float) $row['total_amount'];
1169 return $row;
1170 }
1171
1172 /**
1173 * Is the current row a renewal.
1174 *
1175 * @return bool
1176 *
1177 * @throws \CRM_Core_Exception
1178 * @throws \CiviCRM_API3_Exception
1179 */
1180 private function currentRowIsRenew(): bool {
1181 return $this->currentRowIsRenewOption === 2 && $this->getCurrentMembership();
1182 }
1183
1184 /**
1185 * Get any current membership for the current row contact, for the same member organization.
1186 *
1187 * @return array|bool
1188 *
1189 * @throws \CiviCRM_API3_Exception
1190 * @throws \CRM_Core_Exception
1191 */
1192 protected function getCurrentMembership() {
1193 if (!isset($this->currentRowExistingMembership)) {
1194 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1195 // is the same as the parent org of an existing membership of the contact
1196 $this->currentRowExistingMembership = CRM_Member_BAO_Membership::getContactMembership($this->getCurrentRowContactID(), $this->getCurrentRowMembershipTypeID(),
1197 FALSE, NULL, TRUE
1198 );
1199 // Check and fix the membership if it is STALE
1200 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($this->currentRowExistingMembership);
1201 }
1202 return $this->currentRowExistingMembership;
1203 }
1204
1205 /**
1206 * Get the params as related to the membership entity.
1207 *
1208 * @return array
1209 */
1210 private function getMembershipParams(): array {
1211 return [
1212 'start_date' => $this->currentRow['membership_start_date'] ?? NULL,
1213 'end_date' => $this->currentRow['membership_end_date'] ?? NULL,
1214 'join_date' => $this->currentRow['membership_join_date'] ?? NULL,
1215 'campaign_id' => $this->currentRow['member_campaign_id'] ?? NULL,
1216 ];
1217 }
1218
1219 }