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