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