[REF] Move membership date calc from v3 api to BAO
[civicrm-core.git] / CRM / Batch / Form / Entry.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035
TO
9 +--------------------------------------------------------------------+
10 */
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
9b161ac5
EM
18use Civi\Api4\Contribution;
19
6a488035 20/**
ce064e4f 21 * This class provides the functionality for batch entry for contributions/memberships.
6a488035
TO
22 */
23class CRM_Batch_Form_Entry extends CRM_Core_Form {
24
25 /**
eceb18cc 26 * Maximum profile fields that will be displayed.
abd76e0d 27 *
62d3ee27 28 * @var int
6a488035
TO
29 */
30 protected $_rowCount = 1;
31
32 /**
eceb18cc 33 * Batch id.
abd76e0d 34 *
62d3ee27 35 * @var int
6a488035
TO
36 */
37 protected $_batchId;
38
39 /**
eceb18cc 40 * Batch information.
abd76e0d 41 *
62d3ee27 42 * @var array
6a488035 43 */
be2fb01f 44 protected $_batchInfo = [];
6a488035
TO
45
46 /**
eceb18cc 47 * Store the profile id associated with the batch type.
62d3ee27 48 * @var int
6a488035
TO
49 */
50 protected $_profileId;
51
52 public $_action;
8ef12e64 53
6a488035
TO
54 public $_mode;
55
56 public $_params;
57
6a488035 58 /**
fe482240 59 * When not to reset sort_name.
abd76e0d 60 *
62d3ee27 61 * @var bool
6a488035
TO
62 */
63 protected $_preserveDefault = TRUE;
64
65 /**
0880a9d0 66 * Contact fields.
abd76e0d 67 *
62d3ee27 68 * @var array
6a488035 69 */
be2fb01f 70 protected $_contactFields = [];
6a488035 71
afe349ef 72 /**
0880a9d0 73 * Fields array of fields in the batch profile.
abd76e0d 74 *
afe349ef 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
abd76e0d 79 *
afe349ef 80 * @var array
81 */
be2fb01f 82 public $_fields = [];
353ffa53 83
9b161ac5
EM
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
cdd71d6b 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.
62d3ee27 138 * @var array
cdd71d6b 139 */
140 protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount'];
141
6a488035 142 /**
eceb18cc 143 * Build all the data structures needed to build the form.
abd76e0d 144 *
145 * @throws \CRM_Core_Exception
8ef12e64 146 */
00be9182 147 public function preProcess() {
6a488035
TO
148 $this->_batchId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
149
150 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
8ef12e64 151
6a488035 152 if (empty($this->_batchInfo)) {
be2fb01f 153 $params = ['id' => $this->_batchId];
6a488035
TO
154 CRM_Batch_BAO_Batch::retrieve($params, $this->_batchInfo);
155
57465e2a 156 $this->assign('batchTotal', !empty($this->_batchInfo['total']) ? $this->_batchInfo['total'] : NULL);
6a488035
TO
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 }
aefb0b79 162 CRM_Core_Resources::singleton()
353ffa53 163 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
be2fb01f
CW
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]]);
111f65f4 167
a5dfa653 168 $this->assign('defaultCurrencySymbol', CRM_Core_BAO_Country::defaultCurrencySymbol());
6a488035
TO
169 }
170
cbd44e94 171 /**
bf48aa29 172 * Set Batch ID.
173 *
174 * @param int $id
cbd44e94 175 */
123fe8fe 176 public function setBatchID($id) {
177 $this->_batchId = $id;
178 }
179
6a488035 180 /**
eceb18cc 181 * Build the form object.
abd76e0d 182 *
183 * @throws \CRM_Core_Exception
6a488035 184 */
00be9182 185 public function buildQuickForm() {
6a488035 186 if (!$this->_profileId) {
e22ec653 187 CRM_Core_Error::statusBounce(ts('Profile for bulk data entry is missing.'));
6a488035
TO
188 }
189
190 $this->addElement('hidden', 'batch_id', $this->_batchId);
191
4a413eb6 192 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
6a488035 193 // get the profile information
d556e751 194 if ($this->_batchInfo['type_id'] == $batchTypes['Contribution']) {
6a488035 195 CRM_Utils_System::setTitle(ts('Batch Data Entry for Contributions'));
6a488035 196 }
691df66d 197 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
6a488035 198 CRM_Utils_System::setTitle(ts('Batch Data Entry for Memberships'));
6a488035 199 }
691df66d
TO
200 elseif ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
201 CRM_Utils_System::setTitle(ts('Batch Data Entry for Pledge Payments'));
691df66d 202 }
abd76e0d 203
6a488035
TO
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;
6a488035 208 foreach ($this->_fields as $name => $field) {
6454484c 209 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && $this->_fields[$name]['html_type'] == 'Autocomplete-Select') {
6a488035
TO
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
be2fb01f 221 $this->addFormRule(['CRM_Batch_Form_Entry', 'formRule'], $this);
6a488035
TO
222
223 // add the force save button
224 $forceSave = $this->getButtonName('upload', 'force');
225
cbd83dde 226 $this->addElement('xbutton',
6a488035 227 $forceSave,
cbd83dde 228 ts('Ignore Mismatch & Process the Batch?'),
f7083334
AH
229 [
230 'type' => 'submit',
231 'value' => 1,
57c59c34 232 'class' => 'crm-button crm-button_qf_Entry_upload_force-save',
f7083334 233 ]
6a488035
TO
234 );
235
be2fb01f 236 $this->addButtons([
5d4fcf54
TO
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 ]);
6a488035
TO
247
248 $this->assign('rowCount', $this->_batchInfo['item_count'] + 1);
249
be2fb01f 250 $preserveDefaultsArray = [
353ffa53
TO
251 'first_name',
252 'last_name',
253 'middle_name',
6a488035
TO
254 'organization_name',
255 'household_name',
be2fb01f 256 ];
6a488035 257
be2fb01f
CW
258 $contactTypes = ['Contact', 'Individual', 'Household', 'Organization'];
259 $contactReturnProperties = [];
5056dc8e 260
6a488035 261 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
be2fb01f 262 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', [
5d4fcf54
TO
263 'create' => TRUE,
264 'placeholder' => ts('- select -'),
265 ]);
6a488035
TO
266
267 // special field specific to membership batch udpate
268 if ($this->_batchInfo['type_id'] == 2) {
be2fb01f 269 $options = [
6a488035
TO
270 1 => ts('Add Membership'),
271 2 => ts('Renew Membership'),
be2fb01f 272 ];
6a488035
TO
273 $this->add('select', "member_option[$rowNumber]", '', $options);
274 }
00f6e1a8 275 if ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
be2fb01f
CW
276 $options = ['' => '-select-'];
277 $optionTypes = [
04e6444d 278 '1' => ts('Adjust Pledge Payment Schedule?'),
279 '2' => ts('Adjust Total Pledge Amount?'),
be2fb01f 280 ];
8e2b1206 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);
5542b7c2 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);
be2fb01f 288 $options += [$pledgeID => CRM_Utils_Date::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']];
5542b7c2 289 }
8e2b1206 290 }
291 }
5056dc8e 292
b8e805eb 293 $this->add('select', "open_pledges[$rowNumber]", '', $options);
691df66d 294 }
8e2b1206 295
6a488035
TO
296 foreach ($this->_fields as $name => $field) {
297 if (in_array($field['field_type'], $contactTypes)) {
57465e2a 298 $fld = explode('-', $field['name']);
5b1666f7 299 $contactReturnProperties[$field['name']] = $fld[0];
6a488035
TO
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 }
75140351 308
3f8a2e90 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
75140351 311 // An offset value is set to deal with additional vars that are likely passed.
3f8a2e90 312 // There may be a more accurate way to do this...
5d4fcf54
TO
313 // set an offset to account for other vars we are not counting
314 $offset = 50;
75140351 315 if ((count($this->_elementIndex) + $offset) > ini_get("max_input_vars")) {
6dabf459 316 // Avoiding 'ts' for obscure messages.
e22ec653 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") . ')');
49accad3 318 }
75140351 319
6a488035 320 $this->assign('fields', $this->_fields);
57465e2a 321 CRM_Core_Resources::singleton()
be2fb01f
CW
322 ->addSetting([
323 'contact' => [
353ffa53
TO
324 'return' => implode(',', $contactReturnProperties),
325 'fieldmap' => array_flip($contactReturnProperties),
be2fb01f
CW
326 ],
327 ]);
6a488035
TO
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') {
8f878cd3 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');
6a488035
TO
334 }
335 }
336
337 /**
eceb18cc 338 * Form validations.
6a488035 339 *
82d480a5
TO
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.
1620f0bc 344 * @param \CRM_Batch_Form_Entry $self
82d480a5 345 * Form object.
6a488035 346 *
a6c01b45
CW
347 * @return array
348 * list of errors to be posted back to the form
6a488035 349 */
00be9182 350 public static function formRule($params, $files, $self) {
be2fb01f 351 $errors = [];
4a413eb6 352 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
be2fb01f 353 $fields = [
4db803dd
CW
354 'total_amount' => ts('Amount'),
355 'financial_type' => ts('Financial Type'),
356 'payment_instrument' => ts('Payment Method'),
be2fb01f 357 ];
6a488035 358
0576b84b
SB
359 //CRM-16480 if contact is selected, validate financial type and amount field.
360 foreach ($params['field'] as $key => $value) {
47087bdc 361 if (isset($value['trxn_id'])) {
be2fb01f 362 if (0 < CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', [1 => [$value['trxn_id'], 'String']])) {
47087bdc 363 $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database');
364 }
365 }
61f45887 366 foreach ($fields as $field => $label) {
dddb4c8c 367 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
be2fb01f 368 $errors["field[$key][$field]"] = ts('%1 is a required field.', [1 => $label]);
dddb4c8c 369 }
0576b84b
SB
370 }
371 }
372
a7488080 373 if (!empty($params['_qf_Entry_upload_force'])) {
0576b84b
SB
374 if (!empty($errors)) {
375 return $errors;
376 }
6a488035
TO
377 return TRUE;
378 }
379
380 $batchTotal = 0;
381 foreach ($params['field'] as $key => $value) {
382 $batchTotal += $value['total_amount'];
383
5ee60152 384 //validate for soft credit fields
ccec9d6b 385 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
d1401e86 386 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
5ee60152 387 }
8cc574cf 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'])) {
5ee60152
RN
389 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
390 }
8ef12e64 391
6a488035 392 //membership type is required for membership batch entry
5056dc8e 393 if ($self->_batchInfo['type_id'] == $batchTypes['Membership']) {
a7488080 394 if (empty($value['membership_type'][1])) {
6a488035
TO
395 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
396 }
397 }
398 }
b8e805eb 399 if ($self->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
5056dc8e 400 foreach (array_unique($params["open_pledges"]) as $value) {
42724136 401 if (!empty($value)) {
402 $duplicateRows = array_keys($params["open_pledges"], $value);
403 }
404 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
5056dc8e 405 foreach ($duplicateRows as $key) {
7f6a92ef 406 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
5056dc8e 407 }
408 }
409 }
410 }
28e8aa1b 411 if ((string) $batchTotal != $self->_batchInfo['total']) {
6a488035
TO
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 /**
eceb18cc 425 * Override default cancel action.
6a488035 426 */
00be9182 427 public function cancelAction() {
6a488035
TO
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 /**
c490a46a 434 * Set default values for the form.
abd76e0d 435 *
436 * @throws \CRM_Core_Exception
6a488035 437 */
00be9182 438 public function setDefaultValues() {
6a488035
TO
439 if (empty($this->_fields)) {
440 return;
441 }
442
443 // for add mode set smart defaults
481a74f4 444 if ($this->_action & CRM_Core_Action::ADD) {
3d927ee7 445 $currentDate = date('Y-m-d H-i-s');
6a488035 446
363544d7 447 $completeStatus = CRM_Contribute_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
be2fb01f 448 $specialFields = [
b2c9a0e3 449 'membership_join_date' => date('Y-m-d'),
6a488035 450 'receive_date' => $currentDate,
21dfd5f5 451 'contribution_status_id' => $completeStatus,
be2fb01f 452 ];
6a488035
TO
453
454 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
481a74f4 455 foreach ($specialFields as $key => $value) {
8ef12e64 456 $defaults['field'][$rowNumber][$key] = $value;
6a488035 457 }
8ef12e64 458 }
6a488035
TO
459 }
460 else {
6c97864e 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);
c0d307ec 464 $defaults = $defaults['values'];
6a488035 465 }
6c97864e 466
6a488035
TO
467 return $defaults;
468 }
469
470 /**
eceb18cc 471 * Process the form after the input has been submitted and validated.
abd76e0d 472 *
473 * @throws \CRM_Core_Exception
474 * @throws \CiviCRM_API3_Exception
6a488035
TO
475 */
476 public function postProcess() {
477 $params = $this->controller->exportValues($this->_name);
6a488035 478 $params['actualBatchTotal'] = 0;
d556e751 479
480 // get the profile information
be2fb01f
CW
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']])) {
6a488035
TO
483 $this->processContribution($params);
484 }
d556e751 485 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
818f20f0 486 $params['actualBatchTotal'] = $this->processMembership($params);
6a488035 487 }
d556e751 488
6a488035 489 // update batch to close status
be2fb01f 490 $paramValues = [
6a488035
TO
491 'id' => $this->_batchId,
492 // close status
1a453756 493 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'),
6a488035 494 'total' => $params['actualBatchTotal'],
be2fb01f 495 ];
6a488035
TO
496
497 CRM_Batch_BAO_Batch::create($paramValues);
498
6a488035
TO
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 /**
eceb18cc 506 * Process contribution records.
6a488035 507 *
82d480a5
TO
508 * @param array $params
509 * Associated array of submitted values.
6a488035 510 *
ce064e4f 511 * @return bool
abd76e0d 512 *
513 * @throws \CRM_Core_Exception
514 * @throws \CiviCRM_API3_Exception
6a488035
TO
515 */
516 private function processContribution(&$params) {
6a488035 517
cdd71d6b 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']);
6a488035 526 // get the price set associated with offline contribution record.
9da8dc8c 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));
85020e43
EM
529 $priceFieldID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldID($this->_priceSet);
530 $priceFieldValueID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldValueID($this->_priceSet);
6a488035 531
6a488035
TO
532 if (isset($params['field'])) {
533 foreach ($params['field'] as $key => $value) {
534 // if contact is not selected we should skip the row
ccec9d6b 535 if (empty($params['primary_contact_id'][$key])) {
6a488035
TO
536 continue;
537 }
538
9c1bc317 539 $value['contact_id'] = $params['primary_contact_id'][$key] ?? NULL;
6a488035
TO
540
541 // update contact information
542 $this->updateContactInfo($value);
543
5ee60152 544 //build soft credit params
ccec9d6b
CW
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];
0689c15c 547 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
9e1854a1 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 }
6a488035
TO
557 }
558
b7714c80
AH
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
6a488035 571 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
df1f662a 572 NULL,
6a488035
TO
573 'Contribution'
574 );
575
a7488080 576 if (!empty($value['send_receipt'])) {
6a488035
TO
577 $value['receipt_date'] = date('Y-m-d His');
578 }
2e4a81d5 579 // these translations & date handling are required because we are calling BAO directly rather than the api
be2fb01f 580 $fieldTranslations = [
2e4a81d5
EM
581 'financial_type' => 'financial_type_id',
582 'payment_instrument' => 'payment_instrument_id',
583 'contribution_source' => 'source',
584 'contribution_note' => 'note',
80a67e92 585 'contribution_check_number' => 'check_number',
be2fb01f 586 ];
2e4a81d5 587 foreach ($fieldTranslations as $formField => $baoField) {
5542b7c2 588 if (isset($value[$formField])) {
2e4a81d5
EM
589 $value[$baoField] = $value[$formField];
590 }
591 unset($value[$formField]);
6a488035
TO
592 }
593
594 $params['actualBatchTotal'] += $value['total_amount'];
6a488035
TO
595 $value['batch_id'] = $this->_batchId;
596 $value['skipRecentView'] = TRUE;
597
598 // build line item params
691df66d 599 $this->_priceSet['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
86bfa4f6 600 $value['price_' . $priceFieldID] = 1;
6a488035 601
be2fb01f 602 $lineItem = [];
9da8dc8c 603 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
6a488035 604
c039f658 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.
6a488035
TO
609 unset($value['amount_level']);
610
2e4a81d5 611 //CRM-11529 for back office transactions
8ef12e64 612 //when financial_type_id is passed in form, update the
2e4a81d5 613 //line items with the financial type selected in form
c039f658 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.
8cc574cf 617 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
6a488035
TO
618 foreach ($lineItem[$priceSetId] as &$values) {
619 $values['financial_type_id'] = $value['financial_type_id'];
620 }
621 }
622 $value['line_item'] = $lineItem;
2f8a402e 623
6a488035 624 //finally call contribution create for all the magic
1273d77c 625 $contribution = CRM_Contribute_BAO_Contribution::create($value);
2f8a402e 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 }
4a413eb6 644 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
34b568c4 645 if (!empty($this->_batchInfo['type_id']) && ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment'])) {
04e6444d 646 $adjustTotalAmount = FALSE;
5056dc8e 647 if (isset($params['option_type'][$key])) {
648 if ($params['option_type'][$key] == 2) {
649 $adjustTotalAmount = TRUE;
650 }
04e6444d 651 }
ce70f330 652 $pledgeId = $params['open_pledges'][$key];
5056dc8e 653 if (is_numeric($pledgeId)) {
654 $result = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId);
655 $pledgePaymentId = 0;
481a74f4 656 foreach ($result as $key => $values) {
5056dc8e 657 if ($values['status'] != 'Completed') {
658 $pledgePaymentId = $values['id'];
659 break;
660 }
04e6444d 661 }
5056dc8e 662 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id);
663 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId,
be2fb01f 664 [$pledgePaymentId],
5056dc8e 665 $contribution->contribution_status_id,
666 NULL,
667 $contribution->total_amount,
668 $adjustTotalAmount
669 );
04e6444d 670 }
04e6444d 671 }
5056dc8e 672
6a488035 673 //process premiums
a7488080 674 if (!empty($value['product_name'])) {
6a488035 675 if ($value['product_name'][0] > 0) {
818f20f0 676 [$products, $options] = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
6a488035
TO
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
be2fb01f 684 $premiumParams = [
6a488035
TO
685 'product_id' => $value['product_name'][0],
686 'contribution_id' => $contribution->id,
687 'product_option' => $value['product_option'],
688 'quantity' => 1,
be2fb01f 689 ];
6a488035
TO
690 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
691 }
692 }
693 // end of premium
694
695 //send receipt mail.
5056dc8e 696 if ($contribution->id && !empty($value['send_receipt'])) {
ac4760c5 697 $value['from_email_address'] = $this->getFromEmailAddress();
691df66d 698 $value['contribution_id'] = $contribution->id;
43f77a2c 699 if (!empty($value['soft_credit'])) {
700 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id));
701 }
481a74f4 702 CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $value);
6a488035
TO
703 }
704 }
705 }
2e4a81d5 706 return TRUE;
6a488035 707 }
6a488035
TO
708
709 /**
eceb18cc 710 * Process membership records.
6a488035 711 *
82d480a5 712 * @param array $params
818f20f0 713 * Array of submitted values.
6a488035 714 *
818f20f0 715 * @return float
716 * batch total monetary amount.
6a488035 717 *
818f20f0 718 * @throws \CRM_Core_Exception
719 * @throws \CiviCRM_API3_Exception
6a488035 720 */
818f20f0 721 private function processMembership(array $params) {
722 $batchTotal = 0;
fd4b9293 723 // get the price set associated with offline membership
9da8dc8c 724 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
725 $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
6a488035
TO
726
727 if (isset($params['field'])) {
04b40eab 728 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
6a488035 729 foreach ($params['field'] as $key => $value) {
9b161ac5
EM
730 // if contact is not selected we should skip the row
731 if (empty($params['primary_contact_id'][$key])) {
732 continue;
733 }
734 $value['contact_id'] = $params['primary_contact_id'][$key];
5471eacc 735 foreach ($value as $fieldKey => $fieldValue) {
736 if (isset($this->_fields[$fieldKey]) && $this->_fields[$fieldKey]['data_type'] === 'Money') {
737 $value[$fieldKey] = CRM_Utils_Rule::cleanMoney($fieldValue);
738 }
739 }
6a488035
TO
740
741 // update contact information
742 $this->updateContactInfo($value);
743
744 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
745
a7488080 746 if (!empty($value['membership_source'])) {
6a488035
TO
747 $value['source'] = $value['membership_source'];
748 }
749
750 unset($value['membership_source']);
751
752 //Get the membership status
a7488080 753 if (!empty($value['membership_status'])) {
6a488035
TO
754 $value['status_id'] = $value['membership_status'];
755 unset($value['membership_status']);
756 }
757
6a488035
TO
758 //check for custom data
759 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key],
6a488035
TO
760 $key,
761 'Membership',
762 $membershipTypeId
763 );
764
a7488080 765 if (!empty($value['financial_type'])) {
6a488035
TO
766 $value['financial_type_id'] = $value['financial_type'];
767 }
768
a7488080 769 if (!empty($value['payment_instrument'])) {
6a488035
TO
770 $value['payment_instrument_id'] = $value['payment_instrument'];
771 }
772
773 // handle soft credit
9e1854a1 774 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
ccec9d6b 775 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
0689c15c 776 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
9e1854a1 777
778 //CRM-15350: if soft-credit-type profile field is disabled or removed then
779 //we choose Gift as default value as per Gift Membership rule
780 if (!empty($params['soft_credit_type'][$key])) {
781 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
782 }
783 else {
1a453756 784 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
9e1854a1 785 }
6a488035 786 }
42bcf2d6
SL
787 if (!empty($value['total_amount'])) {
788 $value['total_amount'] = (float) $value['total_amount'];
789 }
6a488035 790
818f20f0 791 $batchTotal += $value['total_amount'];
6a488035
TO
792
793 unset($value['financial_type']);
794 unset($value['payment_instrument']);
795
796 $value['batch_id'] = $this->_batchId;
797 $value['skipRecentView'] = TRUE;
798
799 // make entry in line item for contribution
8ef12e64 800
be2fb01f 801 $editedFieldParams = [
6a488035 802 'price_set_id' => $priceSetId,
21dfd5f5 803 'name' => $value['membership_type'][0],
be2fb01f 804 ];
6a488035 805
be2fb01f 806 $editedResults = [];
9da8dc8c 807 CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
6a488035
TO
808
809 if (!empty($editedResults)) {
810 unset($this->_priceSet['fields']);
811 $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
812 unset($this->_priceSet['fields'][$editedResults['id']]['options']);
813 $fid = $editedResults['id'];
be2fb01f 814 $editedFieldParams = [
6a488035 815 'price_field_id' => $editedResults['id'],
21dfd5f5 816 'membership_type_id' => $value['membership_type_id'],
be2fb01f 817 ];
6a488035 818
be2fb01f 819 $editedResults = [];
9da8dc8c 820 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
6a488035 821 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
a7488080 822 if (!empty($value['total_amount'])) {
6a488035
TO
823 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
824 }
825
826 $fieldID = key($this->_priceSet['fields']);
827 $value['price_' . $fieldID] = $editedResults['id'];
828
be2fb01f 829 $lineItem = [];
9da8dc8c 830 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
6a488035
TO
831 $value, $lineItem[$priceSetId]
832 );
833
8ef12e64 834 //CRM-11529 for backoffice transactions
835 //when financial_type_id is passed in form, update the
6a488035 836 //lineitems with the financial type selected in form
8cc574cf 837 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
6a488035
TO
838 foreach ($lineItem[$priceSetId] as &$values) {
839 $values['financial_type_id'] = $value['financial_type_id'];
840 }
841 }
8ef12e64 842
6a488035
TO
843 $value['lineItems'] = $lineItem;
844 $value['processPriceSet'] = TRUE;
845 }
846 // end of contribution related section
847
848 unset($value['membership_type']);
7670664e
EM
849 $membershipParams = [
850 'start_date' => $value['membership_start_date'] ?? NULL,
851 'end_date' => $value['membership_end_date'] ?? NULL,
852 'join_date' => $value['membership_join_date'] ?? NULL,
853 'campaign_id' => $value['member_campaign_id'] ?? NULL,
854 ];
691df66d 855 $value['is_renew'] = FALSE;
481a74f4 856 if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
61767a1d
EM
857
858 // The following parameter setting may be obsolete.
6a488035 859 $this->_params = $params;
691df66d 860 $value['is_renew'] = TRUE;
04b40eab 861
be2fb01f 862 $formDates = [
6b409353
CW
863 'end_date' => $value['membership_end_date'] ?? NULL,
864 'start_date' => $value['membership_start_date'] ?? NULL,
be2fb01f 865 ];
9c1bc317 866 $membershipSource = $value['source'] ?? NULL;
ec40ee4a
EM
867 $membership = $this->legacyProcessMembership(
868 $value['contact_id'], $value['membership_type_id'],
95588dd4 869 $value['custom'], $membershipSource, ['campaign_id' => $value['member_campaign_id'] ?? NULL], $formDates
6a488035
TO
870 );
871
872 // make contribution entry
be2fb01f 873 $contrbutionParams = array_merge($value, ['membership_id' => $membership->id]);
5471eacc 874 $contrbutionParams['skipCleanMoney'] = TRUE;
3febe800 875 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
876 // This form should set the correct params & not call this fn directly.
28cc62fc 877 CRM_Member_BAO_Membership::recordMembershipContribution($contrbutionParams);
9b161ac5 878 $this->setCurrentRowMembershipID($membership->id);
8ef12e64 879 }
6a488035 880 else {
7670664e
EM
881 // @todo - specify the relevant fields - don't copy all over
882 $membershipParams = array_merge($value, $membershipParams);
883 $membership = CRM_Member_BAO_Membership::create($membershipParams);
6a488035
TO
884 }
885
886 //process premiums
a7488080 887 if (!empty($value['product_name'])) {
6a488035 888 if ($value['product_name'][0] > 0) {
7ec3caf3 889 [$products, $options] = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
6a488035
TO
890
891 $value['hidden_Premium'] = 1;
892 $value['product_option'] = CRM_Utils_Array::value(
893 $value['product_name'][1],
894 $options[$value['product_name'][0]]
895 );
896
be2fb01f 897 $premiumParams = [
6a488035 898 'product_id' => $value['product_name'][0],
9b161ac5 899 'contribution_id' => $this->getCurrentRowContributionID(),
6a488035
TO
900 'product_option' => $value['product_option'],
901 'quantity' => 1,
be2fb01f 902 ];
6a488035
TO
903 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
904 }
905 }
906 // end of premium
907
908 //send receipt mail.
481a74f4 909 if ($membership->id && !empty($value['send_receipt'])) {
353ffa53 910 $value['membership_id'] = $membership->id;
7ec3caf3 911 $this->emailReceipt($this, $value, $membership);
6a488035
TO
912 }
913 }
914 }
818f20f0 915 return $batchTotal;
6a488035
TO
916 }
917
7ec3caf3 918 /**
919 * Send email receipt.
920 *
921 * @param CRM_Core_Form $form
922 * Form object.
923 * @param array $formValues
924 * @param object $membership
925 * Object.
926 *
927 * @return bool
928 * true if mail was sent successfully
ac4760c5 929 * @throws \CRM_Core_Exception|\API_Exception
7ec3caf3 930 *
931 * @deprecated
932 * This function is shared with Batch_Entry which has limited overlap
933 * & needs rationalising.
934 *
935 */
ac4760c5 936 protected function emailReceipt($form, &$formValues, $membership): bool {
7ec3caf3 937 // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
938 if (!empty($formValues['payment_instrument_id'])) {
939 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
940 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
941 }
942
943 $form->assign('module', 'Membership');
944 $form->assign('contactID', $formValues['contact_id']);
945
946 $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues)));
9b161ac5 947 $this->assign('contributionID', $this->getCurrentRowContributionID());
7ec3caf3 948
949 if (!empty($formValues['contribution_status_id'])) {
950 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
951 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name'));
952 }
953
954 if (!empty($formValues['is_renew'])) {
955 $form->assign('receiptType', 'membership renewal');
956 }
957 else {
958 $form->assign('receiptType', 'membership signup');
959 }
960 $form->assign('receive_date', CRM_Utils_Array::value('receive_date', $formValues));
961 $form->assign('formValues', $formValues);
962
963 $form->assign('mem_start_date', CRM_Utils_Date::formatDateOnlyLong($membership->start_date));
964 if (!CRM_Utils_System::isNull($membership->end_date)) {
965 $form->assign('mem_end_date', CRM_Utils_Date::formatDateOnlyLong($membership->end_date));
966 }
967 $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id));
968
969 [$form->_contributorDisplayName, $form->_contributorEmail]
970 = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']);
971 $form->_receiptContactId = $formValues['contact_id'];
972
973 CRM_Core_BAO_MessageTemplate::sendTemplate(
974 [
975 'groupName' => 'msg_tpl_workflow_membership',
976 'valueName' => 'membership_offline_receipt',
977 'contactId' => $form->_receiptContactId,
ac4760c5 978 'from' => $this->getFromEmailAddress(),
7ec3caf3 979 'toName' => $form->_contributorDisplayName,
980 'toEmail' => $form->_contributorEmail,
981 'PDFFilename' => ts('receipt') . '.pdf',
982 'isEmailPdf' => Civi::settings()->get('invoicing') && Civi::settings()->get('invoice_is_email_pdf'),
9b161ac5 983 'contributionId' => $this->getCurrentRowContributionID(),
7ec3caf3 984 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW),
985 ]
986 );
987
9b161ac5
EM
988 Contribution::update(FALSE)
989 ->addWhere('id', '=', $this->getCurrentRowContributionID())
990 ->setValues(['receipt_date', 'now'])
991 ->execute();
992
7ec3caf3 993 return TRUE;
994 }
995
6a488035 996 /**
eceb18cc 997 * Update contact information.
6a488035 998 *
82d480a5
TO
999 * @param array $value
1000 * Associated array of submitted values.
6a488035 1001 */
7ec3caf3 1002 private function updateContactInfo(array &$value) {
6a488035
TO
1003 $value['preserveDBName'] = $this->_preserveDefault;
1004
1005 //parse street address, CRM-7768
1006 CRM_Contact_Form_Task_Batch::parseStreetAddress($value, $this);
1007
1008 CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields,
1009 $value['contact_id']
1010 );
1011 }
cab024d4 1012
afe349ef 1013 /**
ce064e4f 1014 * Function exists purely for unit testing purposes.
1015 *
1016 * If you feel tempted to use this in live code then it probably means there is some functionality
1017 * that needs to be moved out of the form layer
cab024d4 1018 *
4c16123d 1019 * @param array $params
cab024d4
EM
1020 *
1021 * @return bool
afe349ef 1022 */
00be9182 1023 public function testProcessMembership($params) {
afe349ef 1024 return $this->processMembership($params);
1025 }
cab024d4
EM
1026
1027 /**
ce064e4f 1028 * Function exists purely for unit testing purposes.
1029 *
1030 * If you feel tempted to use this in live code then it probably means there is some functionality
1031 * that needs to be moved out of the form layer.
cab024d4
EM
1032 *
1033 * @param array $params
1034 *
1035 * @return bool
abd76e0d 1036 *
1037 * @throws \CRM_Core_Exception
1038 * @throws \CiviCRM_API3_Exception
cab024d4 1039 */
00be9182 1040 public function testProcessContribution($params) {
cab024d4
EM
1041 return $this->processContribution($params);
1042 }
96025800 1043
a1a9cf1f
EM
1044 /**
1045 * @param int $contactID
1046 * @param int $membershipTypeID
a1a9cf1f 1047 * @param $customFieldsFormatted
a1a9cf1f
EM
1048 * @param $membershipSource
1049 * @param $isPayLater
1050 * @param array $memParams
1051 * @param array $formDates
a1a9cf1f 1052 *
c92325a8
EM
1053 * @return CRM_Member_BAO_Membership
1054 *
a1a9cf1f
EM
1055 * @throws \CRM_Core_Exception
1056 * @throws \CiviCRM_API3_Exception
1057 */
95588dd4 1058 protected function legacyProcessMembership($contactID, $membershipTypeID, $customFieldsFormatted, $membershipSource, $memParams = [], $formDates = []): CRM_Member_BAO_Membership {
c92325a8 1059 $updateStatusId = FALSE;
ec40ee4a
EM
1060 $changeToday = NULL;
1061 $is_test = FALSE;
1062 $modifiedID = NULL;
1063 $numRenewTerms = 1;
1064 $membershipID = NULL;
1065 $pending = FALSE;
1066 $contributionRecurID = NULL;
a1a9cf1f
EM
1067 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
1068 $format = '%Y%m%d';
1069 $statusFormat = '%Y-%m-%d';
1070 $membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipType($membershipTypeID);
a1a9cf1f 1071 $ids = [];
95588dd4 1072 $isPayLater = NULL;
a1a9cf1f
EM
1073
1074 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1075 // is the same as the parent org of an existing membership of the contact
1076 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($contactID, $membershipTypeID,
1077 $is_test, $membershipID, TRUE
1078 );
1079 if ($currentMembership) {
a1a9cf1f
EM
1080
1081 // Do NOT do anything.
1082 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1083 //2. Paylater/IPN renew. CRM-4556.
1084 if ($pending || in_array($currentMembership['status_id'], [
1085 array_search('Pending', $allStatus),
1086 // CRM-15475
1087 array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1088 ])) {
1089
1090 $memParams = array_merge([
1091 'id' => $currentMembership['id'],
a1a9cf1f
EM
1092 'status_id' => $currentMembership['status_id'],
1093 'start_date' => $currentMembership['start_date'],
1094 'end_date' => $currentMembership['end_date'],
a1a9cf1f
EM
1095 'join_date' => $currentMembership['join_date'],
1096 'membership_type_id' => $membershipTypeID,
1097 'max_related' => !empty($membershipTypeDetails['max_related']) ? $membershipTypeDetails['max_related'] : NULL,
1098 'membership_activity_status' => ($pending || $isPayLater) ? 'Scheduled' : 'Completed',
1099 ], $memParams);
1100 if ($contributionRecurID) {
1101 $memParams['contribution_recur_id'] = $contributionRecurID;
1102 }
1103
c92325a8 1104 return CRM_Member_BAO_Membership::create($memParams);
a1a9cf1f
EM
1105 }
1106
1107 // Check and fix the membership if it is STALE
1108 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1109
1110 // Now Renew the membership
1111 if (!$currentMembership['is_current_member']) {
1112 // membership is not CURRENT
1113
1114 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1115 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'],
1116 $changeToday,
1117 $membershipTypeID,
1118 $numRenewTerms
1119 );
1120
1121 $currentMembership['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1122 foreach (['start_date', 'end_date'] as $dateType) {
1123 $currentMembership[$dateType] = $formDates[$dateType] ?? NULL;
1124 if (empty($currentMembership[$dateType])) {
1125 $currentMembership[$dateType] = $dates[$dateType] ?? NULL;
1126 }
1127 }
1128 $currentMembership['is_test'] = $is_test;
1129
1130 if (!empty($membershipSource)) {
1131 $currentMembership['source'] = $membershipSource;
1132 }
1133
1134 if (!empty($currentMembership['id'])) {
1135 $ids['membership'] = $currentMembership['id'];
1136 }
1137 $memParams = array_merge($currentMembership, $memParams);
1138 $memParams['membership_type_id'] = $membershipTypeID;
1139
1140 //set the log start date.
1141 $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
1142 }
1143 else {
1144
1145 // CURRENT Membership
1146 $membership = new CRM_Member_DAO_Membership();
1147 $membership->id = $currentMembership['id'];
1148 $membership->find(TRUE);
1149 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1150 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id,
1151 $changeToday,
1152 $membershipTypeID,
1153 $numRenewTerms
1154 );
1155
1156 // Insert renewed dates for CURRENT membership
1157 $memParams['join_date'] = CRM_Utils_Date::isoToMysql($membership->join_date);
1158 $memParams['start_date'] = $formDates['start_date'] ?? CRM_Utils_Date::isoToMysql($membership->start_date);
1159 $memParams['end_date'] = $formDates['end_date'] ?? NULL;
1160 if (empty($memParams['end_date'])) {
1161 $memParams['end_date'] = $dates['end_date'] ?? NULL;
1162 }
1163 $memParams['membership_type_id'] = $membershipTypeID;
1164
1165 //set the log start date.
1166 $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
1167
1168 //CRM-18067
1169 if (!empty($membershipSource)) {
1170 $memParams['source'] = $membershipSource;
1171 }
1172 elseif (empty($membership->source)) {
1173 $memParams['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
1174 $currentMembership['id'],
1175 'source'
1176 );
1177 }
1178
1179 if (!empty($currentMembership['id'])) {
1180 $ids['membership'] = $currentMembership['id'];
1181 }
1182 $memParams['membership_activity_status'] = ($pending || $isPayLater) ? 'Scheduled' : 'Completed';
1183 }
1184 }
1185 else {
1186 // NEW Membership
1187 $memParams = array_merge([
1188 'contact_id' => $contactID,
1189 'membership_type_id' => $membershipTypeID,
1190 ], $memParams);
1191
1192 if (!$pending) {
1193 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1194
1195 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
1196 $memParams[$dateType] = $formDates[$dateType] ?? NULL;
1197 if (empty($memParams[$dateType])) {
1198 $memParams[$dateType] = $dates[$dateType] ?? NULL;
1199 }
1200 }
1201
1202 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(CRM_Utils_Date::customFormat($dates['start_date'],
1203 $statusFormat
1204 ),
1205 CRM_Utils_Date::customFormat($dates['end_date'],
1206 $statusFormat
1207 ),
1208 CRM_Utils_Date::customFormat($dates['join_date'],
1209 $statusFormat
1210 ),
1211 'now',
1212 TRUE,
1213 $membershipTypeID,
1214 $memParams
1215 );
1216 $updateStatusId = $status['id'] ?? NULL;
1217 }
1218 else {
1219 // if IPN/Pay-Later set status to: PENDING
1220 $updateStatusId = array_search('Pending', $allStatus);
1221 }
1222
1223 if (!empty($membershipSource)) {
1224 $memParams['source'] = $membershipSource;
1225 }
1226 $memParams['is_test'] = $is_test;
1227 $memParams['is_pay_later'] = $isPayLater;
1228 }
1229 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
1230 // perhaps shouldn't be?
1231 if ($contributionRecurID) {
1232 $memParams['contribution_recur_id'] = $contributionRecurID;
1233 }
1234 //CRM-4555
1235 //if we decided status here and want to skip status
1236 //calculation in create( ); then need to pass 'skipStatusCal'.
1237 if ($updateStatusId) {
1238 $memParams['status_id'] = $updateStatusId;
1239 $memParams['skipStatusCal'] = TRUE;
1240 }
1241
1242 //since we are renewing,
1243 //make status override false.
1244 $memParams['is_override'] = FALSE;
1245
1246 //CRM-4027, create log w/ individual contact.
1247 if ($modifiedID) {
1248 // @todo this param is likely unused now.
1249 $memParams['is_for_organization'] = TRUE;
1250 }
1251 $params['modified_id'] = $modifiedID ?? $contactID;
1252
a1a9cf1f
EM
1253 $memParams['custom'] = $customFieldsFormatted;
1254 // Load all line items & process all in membership. Don't do in contribution.
1255 // Relevant tests in api_v3_ContributionPageTest.
a1a9cf1f
EM
1256 // @todo stop passing $ids (membership and userId may be set by this point)
1257 $membership = CRM_Member_BAO_Membership::create($memParams, $ids);
1258
1259 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1260 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
1261 $membership->find(TRUE);
1262
c92325a8 1263 return $membership;
a1a9cf1f
EM
1264 }
1265
ac4760c5
EM
1266 /**
1267 * @return string
1268 * @throws \CRM_Core_Exception
1269 */
1270 private function getFromEmailAddress(): string {
1271 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
1272 return "$domainEmail[0] <$domainEmail[1]>";
1273 }
1274
6a488035 1275}