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