Merge pull request #20779 from eileenmcnaughton/batch2
[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
77274636 720 * @throws \API_Exception
6a488035 721 */
818f20f0 722 private function processMembership(array $params) {
723 $batchTotal = 0;
fd4b9293 724 // get the price set associated with offline membership
9da8dc8c 725 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
726 $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
6a488035
TO
727
728 if (isset($params['field'])) {
04b40eab 729 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
6a488035 730 foreach ($params['field'] as $key => $value) {
9b161ac5
EM
731 // if contact is not selected we should skip the row
732 if (empty($params['primary_contact_id'][$key])) {
733 continue;
734 }
735 $value['contact_id'] = $params['primary_contact_id'][$key];
5471eacc 736 foreach ($value as $fieldKey => $fieldValue) {
737 if (isset($this->_fields[$fieldKey]) && $this->_fields[$fieldKey]['data_type'] === 'Money') {
738 $value[$fieldKey] = CRM_Utils_Rule::cleanMoney($fieldValue);
739 }
740 }
d2fc4c00 741 $value = $this->standardiseRow($value);
6a488035
TO
742
743 // update contact information
744 $this->updateContactInfo($value);
745
6a488035
TO
746 //check for custom data
747 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key],
6a488035
TO
748 $key,
749 'Membership',
d2fc4c00 750 $value['membership_type_id']
6a488035
TO
751 );
752
6a488035 753 // handle soft credit
9e1854a1 754 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
ccec9d6b 755 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
0689c15c 756 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
9e1854a1 757
758 //CRM-15350: if soft-credit-type profile field is disabled or removed then
759 //we choose Gift as default value as per Gift Membership rule
760 if (!empty($params['soft_credit_type'][$key])) {
761 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
762 }
763 else {
1a453756 764 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
9e1854a1 765 }
6a488035 766 }
818f20f0 767 $batchTotal += $value['total_amount'];
6a488035
TO
768 $value['batch_id'] = $this->_batchId;
769 $value['skipRecentView'] = TRUE;
770
77274636
EM
771 $order = new CRM_Financial_BAO_Order();
772 // We use the override total amount because we are dealing with a
773 // possibly tax_inclusive total, which is assumed for the override total.
774 $order->setOverrideTotalAmount($value['total_amount']);
775 $order->setLineItem([
776 'membership_type_id' => $value['membership_type_id'],
777 'financial_type_id' => $value['financial_type_id'],
778 ], $key);
779
780 if (!empty($order->getLineItems())) {
781 $value['lineItems'] = [$order->getPriceSetID() => $order->getPriceFieldIndexedLineItems()];
6a488035
TO
782 $value['processPriceSet'] = TRUE;
783 }
784 // end of contribution related section
785
7670664e
EM
786 $membershipParams = [
787 'start_date' => $value['membership_start_date'] ?? NULL,
788 'end_date' => $value['membership_end_date'] ?? NULL,
789 'join_date' => $value['membership_join_date'] ?? NULL,
790 'campaign_id' => $value['member_campaign_id'] ?? NULL,
791 ];
691df66d 792 $value['is_renew'] = FALSE;
481a74f4 793 if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
61767a1d
EM
794
795 // The following parameter setting may be obsolete.
6a488035 796 $this->_params = $params;
691df66d 797 $value['is_renew'] = TRUE;
04b40eab 798
be2fb01f 799 $formDates = [
6b409353
CW
800 'end_date' => $value['membership_end_date'] ?? NULL,
801 'start_date' => $value['membership_start_date'] ?? NULL,
be2fb01f 802 ];
9c1bc317 803 $membershipSource = $value['source'] ?? NULL;
ec40ee4a
EM
804 $membership = $this->legacyProcessMembership(
805 $value['contact_id'], $value['membership_type_id'],
95588dd4 806 $value['custom'], $membershipSource, ['campaign_id' => $value['member_campaign_id'] ?? NULL], $formDates
6a488035
TO
807 );
808
809 // make contribution entry
be2fb01f 810 $contrbutionParams = array_merge($value, ['membership_id' => $membership->id]);
5471eacc 811 $contrbutionParams['skipCleanMoney'] = TRUE;
3febe800 812 // @todo - calling this from here is pretty hacky since it is called from membership.create anyway
813 // This form should set the correct params & not call this fn directly.
28cc62fc 814 CRM_Member_BAO_Membership::recordMembershipContribution($contrbutionParams);
9b161ac5 815 $this->setCurrentRowMembershipID($membership->id);
8ef12e64 816 }
6a488035 817 else {
7670664e
EM
818 // @todo - specify the relevant fields - don't copy all over
819 $membershipParams = array_merge($value, $membershipParams);
820 $membership = CRM_Member_BAO_Membership::create($membershipParams);
6a488035
TO
821 }
822
823 //process premiums
a7488080 824 if (!empty($value['product_name'])) {
6a488035 825 if ($value['product_name'][0] > 0) {
7ec3caf3 826 [$products, $options] = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
6a488035
TO
827
828 $value['hidden_Premium'] = 1;
829 $value['product_option'] = CRM_Utils_Array::value(
830 $value['product_name'][1],
831 $options[$value['product_name'][0]]
832 );
833
be2fb01f 834 $premiumParams = [
6a488035 835 'product_id' => $value['product_name'][0],
9b161ac5 836 'contribution_id' => $this->getCurrentRowContributionID(),
6a488035
TO
837 'product_option' => $value['product_option'],
838 'quantity' => 1,
be2fb01f 839 ];
6a488035
TO
840 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
841 }
842 }
843 // end of premium
844
845 //send receipt mail.
481a74f4 846 if ($membership->id && !empty($value['send_receipt'])) {
353ffa53 847 $value['membership_id'] = $membership->id;
7ec3caf3 848 $this->emailReceipt($this, $value, $membership);
6a488035
TO
849 }
850 }
851 }
818f20f0 852 return $batchTotal;
6a488035
TO
853 }
854
7ec3caf3 855 /**
856 * Send email receipt.
857 *
858 * @param CRM_Core_Form $form
859 * Form object.
860 * @param array $formValues
861 * @param object $membership
862 * Object.
863 *
864 * @return bool
865 * true if mail was sent successfully
ac4760c5 866 * @throws \CRM_Core_Exception|\API_Exception
7ec3caf3 867 *
868 * @deprecated
869 * This function is shared with Batch_Entry which has limited overlap
870 * & needs rationalising.
871 *
872 */
ac4760c5 873 protected function emailReceipt($form, &$formValues, $membership): bool {
7ec3caf3 874 // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
875 if (!empty($formValues['payment_instrument_id'])) {
876 $paymentInstrument = CRM_Contribute_PseudoConstant::paymentInstrument();
877 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
878 }
879
880 $form->assign('module', 'Membership');
881 $form->assign('contactID', $formValues['contact_id']);
882
883 $form->assign('membershipID', CRM_Utils_Array::value('membership_id', $form->_params, CRM_Utils_Array::value('membership_id', $form->_defaultValues)));
9b161ac5 884 $this->assign('contributionID', $this->getCurrentRowContributionID());
7ec3caf3 885
886 if (!empty($formValues['contribution_status_id'])) {
887 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
888 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant::contributionStatus($formValues['contribution_status_id'], 'name'));
889 }
890
891 if (!empty($formValues['is_renew'])) {
892 $form->assign('receiptType', 'membership renewal');
893 }
894 else {
895 $form->assign('receiptType', 'membership signup');
896 }
897 $form->assign('receive_date', CRM_Utils_Array::value('receive_date', $formValues));
898 $form->assign('formValues', $formValues);
899
900 $form->assign('mem_start_date', CRM_Utils_Date::formatDateOnlyLong($membership->start_date));
901 if (!CRM_Utils_System::isNull($membership->end_date)) {
902 $form->assign('mem_end_date', CRM_Utils_Date::formatDateOnlyLong($membership->end_date));
903 }
904 $form->assign('membership_name', CRM_Member_PseudoConstant::membershipType($membership->membership_type_id));
905
906 [$form->_contributorDisplayName, $form->_contributorEmail]
907 = CRM_Contact_BAO_Contact_Location::getEmailDetails($formValues['contact_id']);
908 $form->_receiptContactId = $formValues['contact_id'];
909
910 CRM_Core_BAO_MessageTemplate::sendTemplate(
911 [
912 'groupName' => 'msg_tpl_workflow_membership',
913 'valueName' => 'membership_offline_receipt',
914 'contactId' => $form->_receiptContactId,
ac4760c5 915 'from' => $this->getFromEmailAddress(),
7ec3caf3 916 'toName' => $form->_contributorDisplayName,
917 'toEmail' => $form->_contributorEmail,
918 'PDFFilename' => ts('receipt') . '.pdf',
919 'isEmailPdf' => Civi::settings()->get('invoicing') && Civi::settings()->get('invoice_is_email_pdf'),
9b161ac5 920 'contributionId' => $this->getCurrentRowContributionID(),
7ec3caf3 921 'isTest' => (bool) ($form->_action & CRM_Core_Action::PREVIEW),
922 ]
923 );
924
9b161ac5
EM
925 Contribution::update(FALSE)
926 ->addWhere('id', '=', $this->getCurrentRowContributionID())
927 ->setValues(['receipt_date', 'now'])
928 ->execute();
929
7ec3caf3 930 return TRUE;
931 }
932
6a488035 933 /**
eceb18cc 934 * Update contact information.
6a488035 935 *
82d480a5
TO
936 * @param array $value
937 * Associated array of submitted values.
6a488035 938 */
7ec3caf3 939 private function updateContactInfo(array &$value) {
6a488035
TO
940 $value['preserveDBName'] = $this->_preserveDefault;
941
942 //parse street address, CRM-7768
943 CRM_Contact_Form_Task_Batch::parseStreetAddress($value, $this);
944
945 CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields,
946 $value['contact_id']
947 );
948 }
cab024d4 949
afe349ef 950 /**
ce064e4f 951 * Function exists purely for unit testing purposes.
952 *
953 * If you feel tempted to use this in live code then it probably means there is some functionality
954 * that needs to be moved out of the form layer
cab024d4 955 *
4c16123d 956 * @param array $params
cab024d4
EM
957 *
958 * @return bool
afe349ef 959 */
00be9182 960 public function testProcessMembership($params) {
afe349ef 961 return $this->processMembership($params);
962 }
cab024d4
EM
963
964 /**
ce064e4f 965 * Function exists purely for unit testing purposes.
966 *
967 * If you feel tempted to use this in live code then it probably means there is some functionality
968 * that needs to be moved out of the form layer.
cab024d4
EM
969 *
970 * @param array $params
971 *
972 * @return bool
abd76e0d 973 *
974 * @throws \CRM_Core_Exception
975 * @throws \CiviCRM_API3_Exception
cab024d4 976 */
00be9182 977 public function testProcessContribution($params) {
cab024d4
EM
978 return $this->processContribution($params);
979 }
96025800 980
a1a9cf1f
EM
981 /**
982 * @param int $contactID
983 * @param int $membershipTypeID
a1a9cf1f 984 * @param $customFieldsFormatted
a1a9cf1f
EM
985 * @param $membershipSource
986 * @param $isPayLater
987 * @param array $memParams
988 * @param array $formDates
a1a9cf1f 989 *
c92325a8
EM
990 * @return CRM_Member_BAO_Membership
991 *
a1a9cf1f
EM
992 * @throws \CRM_Core_Exception
993 * @throws \CiviCRM_API3_Exception
994 */
95588dd4 995 protected function legacyProcessMembership($contactID, $membershipTypeID, $customFieldsFormatted, $membershipSource, $memParams = [], $formDates = []): CRM_Member_BAO_Membership {
c92325a8 996 $updateStatusId = FALSE;
ec40ee4a
EM
997 $changeToday = NULL;
998 $is_test = FALSE;
999 $modifiedID = NULL;
1000 $numRenewTerms = 1;
1001 $membershipID = NULL;
1002 $pending = FALSE;
1003 $contributionRecurID = NULL;
a1a9cf1f
EM
1004 $allStatus = CRM_Member_PseudoConstant::membershipStatus();
1005 $format = '%Y%m%d';
1006 $statusFormat = '%Y-%m-%d';
1007 $membershipTypeDetails = CRM_Member_BAO_MembershipType::getMembershipType($membershipTypeID);
a1a9cf1f 1008 $ids = [];
95588dd4 1009 $isPayLater = NULL;
a1a9cf1f
EM
1010
1011 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1012 // is the same as the parent org of an existing membership of the contact
1013 $currentMembership = CRM_Member_BAO_Membership::getContactMembership($contactID, $membershipTypeID,
1014 $is_test, $membershipID, TRUE
1015 );
1016 if ($currentMembership) {
a1a9cf1f
EM
1017
1018 // Do NOT do anything.
1019 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1020 //2. Paylater/IPN renew. CRM-4556.
1021 if ($pending || in_array($currentMembership['status_id'], [
1022 array_search('Pending', $allStatus),
1023 // CRM-15475
1024 array_search('Cancelled', CRM_Member_PseudoConstant::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1025 ])) {
1026
1027 $memParams = array_merge([
1028 'id' => $currentMembership['id'],
a1a9cf1f
EM
1029 'status_id' => $currentMembership['status_id'],
1030 'start_date' => $currentMembership['start_date'],
1031 'end_date' => $currentMembership['end_date'],
a1a9cf1f
EM
1032 'join_date' => $currentMembership['join_date'],
1033 'membership_type_id' => $membershipTypeID,
1034 'max_related' => !empty($membershipTypeDetails['max_related']) ? $membershipTypeDetails['max_related'] : NULL,
1035 'membership_activity_status' => ($pending || $isPayLater) ? 'Scheduled' : 'Completed',
1036 ], $memParams);
1037 if ($contributionRecurID) {
1038 $memParams['contribution_recur_id'] = $contributionRecurID;
1039 }
1040
c92325a8 1041 return CRM_Member_BAO_Membership::create($memParams);
a1a9cf1f
EM
1042 }
1043
1044 // Check and fix the membership if it is STALE
1045 CRM_Member_BAO_Membership::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1046
1047 // Now Renew the membership
1048 if (!$currentMembership['is_current_member']) {
1049 // membership is not CURRENT
1050
1051 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1052 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($currentMembership['id'],
1053 $changeToday,
1054 $membershipTypeID,
1055 $numRenewTerms
1056 );
1057
1058 $currentMembership['join_date'] = CRM_Utils_Date::customFormat($currentMembership['join_date'], $format);
1059 foreach (['start_date', 'end_date'] as $dateType) {
1060 $currentMembership[$dateType] = $formDates[$dateType] ?? NULL;
1061 if (empty($currentMembership[$dateType])) {
1062 $currentMembership[$dateType] = $dates[$dateType] ?? NULL;
1063 }
1064 }
1065 $currentMembership['is_test'] = $is_test;
1066
1067 if (!empty($membershipSource)) {
1068 $currentMembership['source'] = $membershipSource;
1069 }
1070
1071 if (!empty($currentMembership['id'])) {
1072 $ids['membership'] = $currentMembership['id'];
1073 }
1074 $memParams = array_merge($currentMembership, $memParams);
1075 $memParams['membership_type_id'] = $membershipTypeID;
1076
1077 //set the log start date.
1078 $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
1079 }
1080 else {
1081
1082 // CURRENT Membership
1083 $membership = new CRM_Member_DAO_Membership();
1084 $membership->id = $currentMembership['id'];
1085 $membership->find(TRUE);
1086 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1087 $dates = CRM_Member_BAO_MembershipType::getRenewalDatesForMembershipType($membership->id,
1088 $changeToday,
1089 $membershipTypeID,
1090 $numRenewTerms
1091 );
1092
1093 // Insert renewed dates for CURRENT membership
1094 $memParams['join_date'] = CRM_Utils_Date::isoToMysql($membership->join_date);
1095 $memParams['start_date'] = $formDates['start_date'] ?? CRM_Utils_Date::isoToMysql($membership->start_date);
1096 $memParams['end_date'] = $formDates['end_date'] ?? NULL;
1097 if (empty($memParams['end_date'])) {
1098 $memParams['end_date'] = $dates['end_date'] ?? NULL;
1099 }
1100 $memParams['membership_type_id'] = $membershipTypeID;
1101
1102 //set the log start date.
1103 $memParams['log_start_date'] = CRM_Utils_Date::customFormat($dates['log_start_date'], $format);
1104
1105 //CRM-18067
1106 if (!empty($membershipSource)) {
1107 $memParams['source'] = $membershipSource;
1108 }
1109 elseif (empty($membership->source)) {
1110 $memParams['source'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
1111 $currentMembership['id'],
1112 'source'
1113 );
1114 }
1115
1116 if (!empty($currentMembership['id'])) {
1117 $ids['membership'] = $currentMembership['id'];
1118 }
1119 $memParams['membership_activity_status'] = ($pending || $isPayLater) ? 'Scheduled' : 'Completed';
1120 }
1121 }
1122 else {
1123 // NEW Membership
1124 $memParams = array_merge([
1125 'contact_id' => $contactID,
1126 'membership_type_id' => $membershipTypeID,
1127 ], $memParams);
1128
1129 if (!$pending) {
1130 $dates = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1131
1132 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
1133 $memParams[$dateType] = $formDates[$dateType] ?? NULL;
1134 if (empty($memParams[$dateType])) {
1135 $memParams[$dateType] = $dates[$dateType] ?? NULL;
1136 }
1137 }
1138
1139 $status = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate(CRM_Utils_Date::customFormat($dates['start_date'],
1140 $statusFormat
1141 ),
1142 CRM_Utils_Date::customFormat($dates['end_date'],
1143 $statusFormat
1144 ),
1145 CRM_Utils_Date::customFormat($dates['join_date'],
1146 $statusFormat
1147 ),
1148 'now',
1149 TRUE,
1150 $membershipTypeID,
1151 $memParams
1152 );
1153 $updateStatusId = $status['id'] ?? NULL;
1154 }
1155 else {
1156 // if IPN/Pay-Later set status to: PENDING
1157 $updateStatusId = array_search('Pending', $allStatus);
1158 }
1159
1160 if (!empty($membershipSource)) {
1161 $memParams['source'] = $membershipSource;
1162 }
1163 $memParams['is_test'] = $is_test;
1164 $memParams['is_pay_later'] = $isPayLater;
1165 }
1166 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
1167 // perhaps shouldn't be?
1168 if ($contributionRecurID) {
1169 $memParams['contribution_recur_id'] = $contributionRecurID;
1170 }
1171 //CRM-4555
1172 //if we decided status here and want to skip status
1173 //calculation in create( ); then need to pass 'skipStatusCal'.
1174 if ($updateStatusId) {
1175 $memParams['status_id'] = $updateStatusId;
1176 $memParams['skipStatusCal'] = TRUE;
1177 }
1178
1179 //since we are renewing,
1180 //make status override false.
1181 $memParams['is_override'] = FALSE;
1182
1183 //CRM-4027, create log w/ individual contact.
1184 if ($modifiedID) {
1185 // @todo this param is likely unused now.
1186 $memParams['is_for_organization'] = TRUE;
1187 }
1188 $params['modified_id'] = $modifiedID ?? $contactID;
1189
a1a9cf1f
EM
1190 $memParams['custom'] = $customFieldsFormatted;
1191 // Load all line items & process all in membership. Don't do in contribution.
1192 // Relevant tests in api_v3_ContributionPageTest.
a1a9cf1f
EM
1193 // @todo stop passing $ids (membership and userId may be set by this point)
1194 $membership = CRM_Member_BAO_Membership::create($memParams, $ids);
1195
1196 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1197 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
1198 $membership->find(TRUE);
1199
c92325a8 1200 return $membership;
a1a9cf1f
EM
1201 }
1202
ac4760c5
EM
1203 /**
1204 * @return string
1205 * @throws \CRM_Core_Exception
1206 */
1207 private function getFromEmailAddress(): string {
1208 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
1209 return "$domainEmail[0] <$domainEmail[1]>";
1210 }
1211
d2fc4c00
EM
1212 /**
1213 * Standardise the values in the row from profile-weirdness to civi-standard.
1214 *
1215 * The row uses odd field names such as financial_type rather than financial
1216 * type id. We standardise at this point.
1217 *
1218 * @param array $row
1219 *
1220 * @return array
1221 */
1222 private function standardiseRow(array $row): array {
1223 $renameFieldMapping = [
1224 'financial_type' => 'financial_type_id',
1225 'payment_instrument' => 'payment_instrument_id',
1226 'membership_source' => 'source',
1227 'membership_status' => 'status_id',
1228 ];
1229 foreach ($renameFieldMapping as $weirdProfileName => $betterName) {
1230 // Check if isset as some like payment instrument and source are optional.
1231 if (isset($row[$weirdProfileName]) && empty($row[$betterName])) {
1232 $row[$betterName] = $row[$weirdProfileName];
1233 unset($row[$weirdProfileName]);
1234 }
1235 }
1236
1237 // The latter format would be normal here - it's unclear if it is sometimes in the former format.
1238 $row['membership_type_id'] = $row['membership_type_id'] ?? $row['membership_type'][1];
1239 unset($row['membership_type']);
1240 // total_amount is required.
1241 $row['total_amount'] = (float) $row['total_amount'];
1242 return $row;
1243 }
1244
6a488035 1245}