No need for crm-button wrappers for real buttons
[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
18/**
ce064e4f 19 * This class provides the functionality for batch entry for contributions/memberships.
6a488035
TO
20 */
21class CRM_Batch_Form_Entry extends CRM_Core_Form {
22
23 /**
eceb18cc 24 * Maximum profile fields that will be displayed.
abd76e0d 25 *
62d3ee27 26 * @var int
6a488035
TO
27 */
28 protected $_rowCount = 1;
29
30 /**
eceb18cc 31 * Batch id.
abd76e0d 32 *
62d3ee27 33 * @var int
6a488035
TO
34 */
35 protected $_batchId;
36
37 /**
eceb18cc 38 * Batch information.
abd76e0d 39 *
62d3ee27 40 * @var array
6a488035 41 */
be2fb01f 42 protected $_batchInfo = [];
6a488035
TO
43
44 /**
eceb18cc 45 * Store the profile id associated with the batch type.
62d3ee27 46 * @var int
6a488035
TO
47 */
48 protected $_profileId;
49
50 public $_action;
8ef12e64 51
6a488035
TO
52 public $_mode;
53
54 public $_params;
55
6a488035 56 /**
fe482240 57 * When not to reset sort_name.
abd76e0d 58 *
62d3ee27 59 * @var bool
6a488035
TO
60 */
61 protected $_preserveDefault = TRUE;
62
63 /**
0880a9d0 64 * Contact fields.
abd76e0d 65 *
62d3ee27 66 * @var array
6a488035 67 */
be2fb01f 68 protected $_contactFields = [];
6a488035 69
afe349ef 70 /**
0880a9d0 71 * Fields array of fields in the batch profile.
abd76e0d 72 *
afe349ef 73 * (based on the uf_field table data)
74 * (this can't be protected as it is passed into the CRM_Contact_Form_Task_Batch::parseStreetAddress function
75 * (although a future refactoring might hopefully change that so it uses the api & the function is not
76 * required
abd76e0d 77 *
afe349ef 78 * @var array
79 */
be2fb01f 80 public $_fields = [];
353ffa53 81
cdd71d6b 82 /**
83 * Monetary fields that may be submitted.
84 *
85 * These should get a standardised format in the beginPostProcess function.
86 *
87 * These fields are common to many forms. Some may override this.
62d3ee27 88 * @var array
cdd71d6b 89 */
90 protected $submittableMoneyFields = ['total_amount', 'net_amount', 'non_deductible_amount', 'fee_amount'];
91
6a488035 92 /**
eceb18cc 93 * Build all the data structures needed to build the form.
abd76e0d 94 *
95 * @throws \CRM_Core_Exception
8ef12e64 96 */
00be9182 97 public function preProcess() {
6a488035
TO
98 $this->_batchId = CRM_Utils_Request::retrieve('id', 'Positive', $this, TRUE);
99
100 $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this, FALSE, 'browse');
8ef12e64 101
6a488035 102 if (empty($this->_batchInfo)) {
be2fb01f 103 $params = ['id' => $this->_batchId];
6a488035
TO
104 CRM_Batch_BAO_Batch::retrieve($params, $this->_batchInfo);
105
57465e2a 106 $this->assign('batchTotal', !empty($this->_batchInfo['total']) ? $this->_batchInfo['total'] : NULL);
6a488035
TO
107 $this->assign('batchType', $this->_batchInfo['type_id']);
108
109 // get the profile id associted with this batch type
110 $this->_profileId = CRM_Batch_BAO_Batch::getProfileId($this->_batchInfo['type_id']);
111 }
aefb0b79 112 CRM_Core_Resources::singleton()
353ffa53 113 ->addScriptFile('civicrm', 'templates/CRM/Batch/Form/Entry.js', 1, 'html-header')
be2fb01f
CW
114 ->addSetting(['batch' => ['type_id' => $this->_batchInfo['type_id']]])
115 ->addSetting(['setting' => ['monetaryThousandSeparator' => CRM_Core_Config::singleton()->monetaryThousandSeparator]])
116 ->addSetting(['setting' => ['monetaryDecimalPoint' => CRM_Core_Config::singleton()->monetaryDecimalPoint]]);
111f65f4 117
a5dfa653 118 $this->assign('defaultCurrencySymbol', CRM_Core_BAO_Country::defaultCurrencySymbol());
6a488035
TO
119 }
120
cbd44e94 121 /**
bf48aa29 122 * Set Batch ID.
123 *
124 * @param int $id
cbd44e94 125 */
123fe8fe 126 public function setBatchID($id) {
127 $this->_batchId = $id;
128 }
129
6a488035 130 /**
eceb18cc 131 * Build the form object.
abd76e0d 132 *
133 * @throws \CRM_Core_Exception
6a488035 134 */
00be9182 135 public function buildQuickForm() {
6a488035 136 if (!$this->_profileId) {
e22ec653 137 CRM_Core_Error::statusBounce(ts('Profile for bulk data entry is missing.'));
6a488035
TO
138 }
139
140 $this->addElement('hidden', 'batch_id', $this->_batchId);
141
4a413eb6 142 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
6a488035 143 // get the profile information
d556e751 144 if ($this->_batchInfo['type_id'] == $batchTypes['Contribution']) {
6a488035 145 CRM_Utils_System::setTitle(ts('Batch Data Entry for Contributions'));
6a488035 146 }
691df66d 147 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
6a488035 148 CRM_Utils_System::setTitle(ts('Batch Data Entry for Memberships'));
6a488035 149 }
691df66d
TO
150 elseif ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
151 CRM_Utils_System::setTitle(ts('Batch Data Entry for Pledge Payments'));
691df66d 152 }
abd76e0d 153
6a488035
TO
154 $this->_fields = CRM_Core_BAO_UFGroup::getFields($this->_profileId, FALSE, CRM_Core_Action::VIEW);
155
156 // remove file type field and then limit fields
157 $suppressFields = FALSE;
6a488035 158 foreach ($this->_fields as $name => $field) {
6454484c 159 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name) && $this->_fields[$name]['html_type'] == 'Autocomplete-Select') {
6a488035
TO
160 $suppressFields = TRUE;
161 unset($this->_fields[$name]);
162 }
163
164 //fix to reduce size as we are using this field in grid
165 if (is_array($field['attributes']) && $this->_fields[$name]['attributes']['size'] > 19) {
166 //shrink class to "form-text-medium"
167 $this->_fields[$name]['attributes']['size'] = 19;
168 }
169 }
170
be2fb01f 171 $this->addFormRule(['CRM_Batch_Form_Entry', 'formRule'], $this);
6a488035
TO
172
173 // add the force save button
174 $forceSave = $this->getButtonName('upload', 'force');
175
cbd83dde 176 $this->addElement('xbutton',
6a488035 177 $forceSave,
cbd83dde 178 ts('Ignore Mismatch & Process the Batch?'),
f7083334
AH
179 [
180 'type' => 'submit',
181 'value' => 1,
57c59c34 182 'class' => 'crm-button crm-button_qf_Entry_upload_force-save',
f7083334 183 ]
6a488035
TO
184 );
185
be2fb01f 186 $this->addButtons([
5d4fcf54
TO
187 [
188 'type' => 'upload',
189 'name' => ts('Validate & Process the Batch'),
190 'isDefault' => TRUE,
191 ],
192 [
193 'type' => 'cancel',
194 'name' => ts('Save & Continue Later'),
195 ],
196 ]);
6a488035
TO
197
198 $this->assign('rowCount', $this->_batchInfo['item_count'] + 1);
199
be2fb01f 200 $preserveDefaultsArray = [
353ffa53
TO
201 'first_name',
202 'last_name',
203 'middle_name',
6a488035
TO
204 'organization_name',
205 'household_name',
be2fb01f 206 ];
6a488035 207
be2fb01f
CW
208 $contactTypes = ['Contact', 'Individual', 'Household', 'Organization'];
209 $contactReturnProperties = [];
5056dc8e 210
6a488035 211 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
be2fb01f 212 $this->addEntityRef("primary_contact_id[{$rowNumber}]", '', [
5d4fcf54
TO
213 'create' => TRUE,
214 'placeholder' => ts('- select -'),
215 ]);
6a488035
TO
216
217 // special field specific to membership batch udpate
218 if ($this->_batchInfo['type_id'] == 2) {
be2fb01f 219 $options = [
6a488035
TO
220 1 => ts('Add Membership'),
221 2 => ts('Renew Membership'),
be2fb01f 222 ];
6a488035
TO
223 $this->add('select', "member_option[$rowNumber]", '', $options);
224 }
00f6e1a8 225 if ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
be2fb01f
CW
226 $options = ['' => '-select-'];
227 $optionTypes = [
04e6444d 228 '1' => ts('Adjust Pledge Payment Schedule?'),
229 '2' => ts('Adjust Total Pledge Amount?'),
be2fb01f 230 ];
8e2b1206 231 $this->add('select', "option_type[$rowNumber]", NULL, $optionTypes);
232 if (!empty($this->_batchId) && !empty($this->_batchInfo['data']) && !empty($rowNumber)) {
233 $dataValues = json_decode($this->_batchInfo['data'], TRUE);
5542b7c2 234 if (!empty($dataValues['values']['primary_contact_id'][$rowNumber])) {
235 $pledgeIDs = CRM_Pledge_BAO_Pledge::getContactPledges($dataValues['values']['primary_contact_id'][$rowNumber]);
236 foreach ($pledgeIDs as $pledgeID) {
237 $pledgePayment = CRM_Pledge_BAO_PledgePayment::getOldestPledgePayment($pledgeID);
be2fb01f 238 $options += [$pledgeID => CRM_Utils_Date::customFormat($pledgePayment['schedule_date'], '%m/%d/%Y') . ', ' . $pledgePayment['amount'] . ' ' . $pledgePayment['currency']];
5542b7c2 239 }
8e2b1206 240 }
241 }
5056dc8e 242
b8e805eb 243 $this->add('select', "open_pledges[$rowNumber]", '', $options);
691df66d 244 }
8e2b1206 245
6a488035
TO
246 foreach ($this->_fields as $name => $field) {
247 if (in_array($field['field_type'], $contactTypes)) {
57465e2a 248 $fld = explode('-', $field['name']);
5b1666f7 249 $contactReturnProperties[$field['name']] = $fld[0];
6a488035
TO
250 }
251 CRM_Core_BAO_UFGroup::buildProfile($this, $field, NULL, NULL, FALSE, FALSE, $rowNumber);
252
253 if (in_array($field['name'], $preserveDefaultsArray)) {
254 $this->_preserveDefault = FALSE;
255 }
256 }
257 }
75140351 258
3f8a2e90 259 // CRM-19477: Display Error for Batch Sizes Exceeding php.ini max_input_vars
260 // Notes: $this->_elementIndex gives an approximate count of the variables being sent
75140351 261 // An offset value is set to deal with additional vars that are likely passed.
3f8a2e90 262 // There may be a more accurate way to do this...
5d4fcf54
TO
263 // set an offset to account for other vars we are not counting
264 $offset = 50;
75140351 265 if ((count($this->_elementIndex) + $offset) > ini_get("max_input_vars")) {
6dabf459 266 // Avoiding 'ts' for obscure messages.
e22ec653 267 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 268 }
75140351 269
6a488035 270 $this->assign('fields', $this->_fields);
57465e2a 271 CRM_Core_Resources::singleton()
be2fb01f
CW
272 ->addSetting([
273 'contact' => [
353ffa53
TO
274 'return' => implode(',', $contactReturnProperties),
275 'fieldmap' => array_flip($contactReturnProperties),
be2fb01f
CW
276 ],
277 ]);
6a488035
TO
278
279 // don't set the status message when form is submitted.
280 $buttonName = $this->controller->getButtonName('submit');
281
282 if ($suppressFields && $buttonName != '_qf_Entry_next') {
8f878cd3 283 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
284 }
285 }
286
287 /**
eceb18cc 288 * Form validations.
6a488035 289 *
82d480a5
TO
290 * @param array $params
291 * Posted values of the form.
292 * @param array $files
293 * List of errors to be posted back to the form.
1620f0bc 294 * @param \CRM_Batch_Form_Entry $self
82d480a5 295 * Form object.
6a488035 296 *
a6c01b45
CW
297 * @return array
298 * list of errors to be posted back to the form
6a488035 299 */
00be9182 300 public static function formRule($params, $files, $self) {
be2fb01f 301 $errors = [];
4a413eb6 302 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
be2fb01f 303 $fields = [
4db803dd
CW
304 'total_amount' => ts('Amount'),
305 'financial_type' => ts('Financial Type'),
306 'payment_instrument' => ts('Payment Method'),
be2fb01f 307 ];
6a488035 308
0576b84b
SB
309 //CRM-16480 if contact is selected, validate financial type and amount field.
310 foreach ($params['field'] as $key => $value) {
47087bdc 311 if (isset($value['trxn_id'])) {
be2fb01f 312 if (0 < CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_contribution WHERE trxn_id = %1', [1 => [$value['trxn_id'], 'String']])) {
47087bdc 313 $errors["field[$key][trxn_id]"] = ts('Transaction ID must be unique within the database');
314 }
315 }
61f45887 316 foreach ($fields as $field => $label) {
dddb4c8c 317 if (!empty($params['primary_contact_id'][$key]) && empty($value[$field])) {
be2fb01f 318 $errors["field[$key][$field]"] = ts('%1 is a required field.', [1 => $label]);
dddb4c8c 319 }
0576b84b
SB
320 }
321 }
322
a7488080 323 if (!empty($params['_qf_Entry_upload_force'])) {
0576b84b
SB
324 if (!empty($errors)) {
325 return $errors;
326 }
6a488035
TO
327 return TRUE;
328 }
329
330 $batchTotal = 0;
331 foreach ($params['field'] as $key => $value) {
332 $batchTotal += $value['total_amount'];
333
5ee60152 334 //validate for soft credit fields
ccec9d6b 335 if (!empty($params['soft_credit_contact_id'][$key]) && empty($params['soft_credit_amount'][$key])) {
d1401e86 336 $errors["soft_credit_amount[$key]"] = ts('Please enter the soft credit amount.');
5ee60152 337 }
8cc574cf 338 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
339 $errors["soft_credit_amount[$key]"] = ts('Soft credit amount should not be greater than the total amount');
340 }
8ef12e64 341
6a488035 342 //membership type is required for membership batch entry
5056dc8e 343 if ($self->_batchInfo['type_id'] == $batchTypes['Membership']) {
a7488080 344 if (empty($value['membership_type'][1])) {
6a488035
TO
345 $errors["field[$key][membership_type]"] = ts('Membership type is a required field.');
346 }
347 }
348 }
b8e805eb 349 if ($self->_batchInfo['type_id'] == $batchTypes['Pledge Payment']) {
5056dc8e 350 foreach (array_unique($params["open_pledges"]) as $value) {
42724136 351 if (!empty($value)) {
352 $duplicateRows = array_keys($params["open_pledges"], $value);
353 }
354 if (!empty($duplicateRows) && count($duplicateRows) > 1) {
5056dc8e 355 foreach ($duplicateRows as $key) {
7f6a92ef 356 $errors["open_pledges[$key]"] = ts('You can not record two payments for the same pledge in a single batch.');
5056dc8e 357 }
358 }
359 }
360 }
28e8aa1b 361 if ((string) $batchTotal != $self->_batchInfo['total']) {
6a488035
TO
362 $self->assign('batchAmountMismatch', TRUE);
363 $errors['_qf_defaults'] = ts('Total for amounts entered below does not match the expected batch total.');
364 }
365
366 if (!empty($errors)) {
367 return $errors;
368 }
369
370 $self->assign('batchAmountMismatch', FALSE);
371 return TRUE;
372 }
373
374 /**
eceb18cc 375 * Override default cancel action.
6a488035 376 */
00be9182 377 public function cancelAction() {
6a488035
TO
378 // redirect to batch listing
379 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
380 CRM_Utils_System::civiExit();
381 }
382
383 /**
c490a46a 384 * Set default values for the form.
abd76e0d 385 *
386 * @throws \CRM_Core_Exception
6a488035 387 */
00be9182 388 public function setDefaultValues() {
6a488035
TO
389 if (empty($this->_fields)) {
390 return;
391 }
392
393 // for add mode set smart defaults
481a74f4 394 if ($this->_action & CRM_Core_Action::ADD) {
3d927ee7 395 $currentDate = date('Y-m-d H-i-s');
6a488035 396
363544d7 397 $completeStatus = CRM_Contribute_PseudoConstant::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
be2fb01f 398 $specialFields = [
b2c9a0e3 399 'membership_join_date' => date('Y-m-d'),
6a488035 400 'receive_date' => $currentDate,
21dfd5f5 401 'contribution_status_id' => $completeStatus,
be2fb01f 402 ];
6a488035
TO
403
404 for ($rowNumber = 1; $rowNumber <= $this->_batchInfo['item_count']; $rowNumber++) {
481a74f4 405 foreach ($specialFields as $key => $value) {
8ef12e64 406 $defaults['field'][$rowNumber][$key] = $value;
6a488035 407 }
8ef12e64 408 }
6a488035
TO
409 }
410 else {
6c97864e 411 // get the cached info from data column of civicrm_batch
412 $data = CRM_Core_DAO::getFieldValue('CRM_Batch_BAO_Batch', $this->_batchId, 'data');
413 $defaults = json_decode($data, TRUE);
c0d307ec 414 $defaults = $defaults['values'];
6a488035 415 }
6c97864e 416
6a488035
TO
417 return $defaults;
418 }
419
420 /**
eceb18cc 421 * Process the form after the input has been submitted and validated.
abd76e0d 422 *
423 * @throws \CRM_Core_Exception
424 * @throws \CiviCRM_API3_Exception
6a488035
TO
425 */
426 public function postProcess() {
427 $params = $this->controller->exportValues($this->_name);
6a488035 428 $params['actualBatchTotal'] = 0;
d556e751 429
430 // get the profile information
be2fb01f
CW
431 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
432 if (in_array($this->_batchInfo['type_id'], [$batchTypes['Pledge Payment'], $batchTypes['Contribution']])) {
6a488035
TO
433 $this->processContribution($params);
434 }
d556e751 435 elseif ($this->_batchInfo['type_id'] == $batchTypes['Membership']) {
6a488035
TO
436 $this->processMembership($params);
437 }
d556e751 438
6a488035 439 // update batch to close status
be2fb01f 440 $paramValues = [
6a488035
TO
441 'id' => $this->_batchId,
442 // close status
1a453756 443 'status_id' => CRM_Core_PseudoConstant::getKey('CRM_Batch_BAO_Batch', 'status_id', 'Closed'),
6a488035 444 'total' => $params['actualBatchTotal'],
be2fb01f 445 ];
6a488035
TO
446
447 CRM_Batch_BAO_Batch::create($paramValues);
448
6a488035
TO
449 // set success status
450 CRM_Core_Session::setStatus("", ts("Batch Processed."), "success");
451
452 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/batch', 'reset=1'));
453 }
454
455 /**
eceb18cc 456 * Process contribution records.
6a488035 457 *
82d480a5
TO
458 * @param array $params
459 * Associated array of submitted values.
6a488035 460 *
ce064e4f 461 * @return bool
abd76e0d 462 *
463 * @throws \CRM_Core_Exception
464 * @throws \CiviCRM_API3_Exception
6a488035
TO
465 */
466 private function processContribution(&$params) {
6a488035 467
cdd71d6b 468 foreach ($this->submittableMoneyFields as $moneyField) {
469 foreach ($params['field'] as $index => $fieldValues) {
470 if (isset($fieldValues[$moneyField])) {
471 $params['field'][$index][$moneyField] = CRM_Utils_Rule::cleanMoney($params['field'][$index][$moneyField]);
472 }
473 }
474 }
475 $params['actualBatchTotal'] = CRM_Utils_Rule::cleanMoney($params['actualBatchTotal']);
6a488035 476 // get the price set associated with offline contribution record.
9da8dc8c 477 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_contribution_amount', 'id', 'name');
478 $this->_priceSet = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
85020e43
EM
479 $priceFieldID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldID($this->_priceSet);
480 $priceFieldValueID = CRM_Price_BAO_PriceSet::getOnlyPriceFieldValueID($this->_priceSet);
6a488035 481
6a488035
TO
482 if (isset($params['field'])) {
483 foreach ($params['field'] as $key => $value) {
484 // if contact is not selected we should skip the row
ccec9d6b 485 if (empty($params['primary_contact_id'][$key])) {
6a488035
TO
486 continue;
487 }
488
9c1bc317 489 $value['contact_id'] = $params['primary_contact_id'][$key] ?? NULL;
6a488035
TO
490
491 // update contact information
492 $this->updateContactInfo($value);
493
5ee60152 494 //build soft credit params
ccec9d6b
CW
495 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
496 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
0689c15c 497 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
9e1854a1 498
499 //CRM-15350: if soft-credit-type profile field is disabled or removed then
500 //we choose configured SCT default value
501 if (!empty($params['soft_credit_type'][$key])) {
502 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
503 }
504 else {
505 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_OptionGroup::getDefaultValue("soft_credit_type");
506 }
6a488035
TO
507 }
508
b7714c80
AH
509 // Build PCP params
510 if (!empty($params['pcp_made_through_id'][$key])) {
511 $value['pcp']['pcp_made_through_id'] = $params['pcp_made_through_id'][$key];
512 $value['pcp']['pcp_display_in_roll'] = !empty($params['pcp_display_in_roll'][$key]);
513 if (!empty($params['pcp_roll_nickname'][$key])) {
514 $value['pcp']['pcp_roll_nickname'] = $params['pcp_roll_nickname'][$key];
515 }
516 if (!empty($params['pcp_personal_note'][$key])) {
517 $value['pcp']['pcp_personal_note'] = $params['pcp_personal_note'][$key];
518 }
519 }
520
6a488035 521 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($value,
df1f662a 522 NULL,
6a488035
TO
523 'Contribution'
524 );
525
a7488080 526 if (!empty($value['send_receipt'])) {
6a488035
TO
527 $value['receipt_date'] = date('Y-m-d His');
528 }
2e4a81d5 529 // these translations & date handling are required because we are calling BAO directly rather than the api
be2fb01f 530 $fieldTranslations = [
2e4a81d5
EM
531 'financial_type' => 'financial_type_id',
532 'payment_instrument' => 'payment_instrument_id',
533 'contribution_source' => 'source',
534 'contribution_note' => 'note',
80a67e92 535 'contribution_check_number' => 'check_number',
be2fb01f 536 ];
2e4a81d5 537 foreach ($fieldTranslations as $formField => $baoField) {
5542b7c2 538 if (isset($value[$formField])) {
2e4a81d5
EM
539 $value[$baoField] = $value[$formField];
540 }
541 unset($value[$formField]);
6a488035
TO
542 }
543
544 $params['actualBatchTotal'] += $value['total_amount'];
6a488035
TO
545 $value['batch_id'] = $this->_batchId;
546 $value['skipRecentView'] = TRUE;
547
548 // build line item params
691df66d 549 $this->_priceSet['fields'][$priceFieldID]['options'][$priceFieldValueID]['amount'] = $value['total_amount'];
86bfa4f6 550 $value['price_' . $priceFieldID] = 1;
6a488035 551
be2fb01f 552 $lineItem = [];
9da8dc8c 553 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'], $value, $lineItem[$priceSetId]);
6a488035 554
c039f658 555 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
556 // function to get correct amount level consistently. Remove setting of the amount level in
557 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
558 // to cover all variants.
6a488035
TO
559 unset($value['amount_level']);
560
2e4a81d5 561 //CRM-11529 for back office transactions
8ef12e64 562 //when financial_type_id is passed in form, update the
2e4a81d5 563 //line items with the financial type selected in form
c039f658 564 // @todo - create a price set or price field per financial type & simply choose the appropriate
565 // price field rather than working around the fact that each price_field is supposed to have a financial
566 // type & we are allowing that to be overridden.
8cc574cf 567 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
6a488035
TO
568 foreach ($lineItem[$priceSetId] as &$values) {
569 $values['financial_type_id'] = $value['financial_type_id'];
570 }
571 }
572 $value['line_item'] = $lineItem;
2f8a402e 573
6a488035 574 //finally call contribution create for all the magic
1273d77c 575 $contribution = CRM_Contribute_BAO_Contribution::create($value);
2f8a402e 576 // This code to retrieve the contribution has been moved here from the contribution create
577 // api. It may not be required.
578 $titleFields = [
579 'contact_id',
580 'total_amount',
581 'currency',
582 'financial_type_id',
583 ];
584 $retrieveRequired = 0;
585 foreach ($titleFields as $titleField) {
586 if (!isset($contribution->$titleField)) {
587 $retrieveRequired = 1;
588 break;
589 }
590 }
591 if ($retrieveRequired == 1) {
592 $contribution->find(TRUE);
593 }
4a413eb6 594 $batchTypes = CRM_Core_PseudoConstant::get('CRM_Batch_DAO_Batch', 'type_id', ['flip' => 1], 'validate');
34b568c4 595 if (!empty($this->_batchInfo['type_id']) && ($this->_batchInfo['type_id'] == $batchTypes['Pledge Payment'])) {
04e6444d 596 $adjustTotalAmount = FALSE;
5056dc8e 597 if (isset($params['option_type'][$key])) {
598 if ($params['option_type'][$key] == 2) {
599 $adjustTotalAmount = TRUE;
600 }
04e6444d 601 }
ce70f330 602 $pledgeId = $params['open_pledges'][$key];
5056dc8e 603 if (is_numeric($pledgeId)) {
604 $result = CRM_Pledge_BAO_PledgePayment::getPledgePayments($pledgeId);
605 $pledgePaymentId = 0;
481a74f4 606 foreach ($result as $key => $values) {
5056dc8e 607 if ($values['status'] != 'Completed') {
608 $pledgePaymentId = $values['id'];
609 break;
610 }
04e6444d 611 }
5056dc8e 612 CRM_Core_DAO::setFieldValue('CRM_Pledge_DAO_PledgePayment', $pledgePaymentId, 'contribution_id', $contribution->id);
613 CRM_Pledge_BAO_PledgePayment::updatePledgePaymentStatus($pledgeId,
be2fb01f 614 [$pledgePaymentId],
5056dc8e 615 $contribution->contribution_status_id,
616 NULL,
617 $contribution->total_amount,
618 $adjustTotalAmount
619 );
04e6444d 620 }
04e6444d 621 }
5056dc8e 622
6a488035 623 //process premiums
a7488080 624 if (!empty($value['product_name'])) {
6a488035
TO
625 if ($value['product_name'][0] > 0) {
626 list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
627
628 $value['hidden_Premium'] = 1;
629 $value['product_option'] = CRM_Utils_Array::value(
630 $value['product_name'][1],
631 $options[$value['product_name'][0]]
632 );
633
be2fb01f 634 $premiumParams = [
6a488035
TO
635 'product_id' => $value['product_name'][0],
636 'contribution_id' => $contribution->id,
637 'product_option' => $value['product_option'],
638 'quantity' => 1,
be2fb01f 639 ];
6a488035
TO
640 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
641 }
642 }
643 // end of premium
644
645 //send receipt mail.
5056dc8e 646 if ($contribution->id && !empty($value['send_receipt'])) {
691df66d
TO
647 // add the domain email id
648 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
649 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
650 $value['from_email_address'] = $domainEmail;
651 $value['contribution_id'] = $contribution->id;
43f77a2c 652 if (!empty($value['soft_credit'])) {
653 $value = array_merge($value, CRM_Contribute_BAO_ContributionSoft::getSoftContribution($contribution->id));
654 }
481a74f4 655 CRM_Contribute_Form_AdditionalInfo::emailReceipt($this, $value);
6a488035
TO
656 }
657 }
658 }
2e4a81d5 659 return TRUE;
6a488035 660 }
6a488035
TO
661
662 /**
eceb18cc 663 * Process membership records.
6a488035 664 *
82d480a5
TO
665 * @param array $params
666 * Associated array of submitted values.
6a488035 667 *
6a488035 668 *
2e4a81d5 669 * @return bool
6a488035
TO
670 */
671 private function processMembership(&$params) {
6a488035 672
fd4b9293 673 // get the price set associated with offline membership
9da8dc8c 674 $priceSetId = CRM_Core_DAO::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
675 $this->_priceSet = $priceSets = current(CRM_Price_BAO_PriceSet::getSetDetail($priceSetId));
6a488035
TO
676
677 if (isset($params['field'])) {
04b40eab 678 // @todo - most of the wrangling in this function is because the api is not being used, especially date stuff.
be2fb01f 679 $customFields = [];
6a488035 680 foreach ($params['field'] as $key => $value) {
5471eacc 681 foreach ($value as $fieldKey => $fieldValue) {
682 if (isset($this->_fields[$fieldKey]) && $this->_fields[$fieldKey]['data_type'] === 'Money') {
683 $value[$fieldKey] = CRM_Utils_Rule::cleanMoney($fieldValue);
684 }
685 }
6a488035 686 // if contact is not selected we should skip the row
ccec9d6b 687 if (empty($params['primary_contact_id'][$key])) {
6a488035
TO
688 continue;
689 }
690
9c1bc317 691 $value['contact_id'] = $params['primary_contact_id'][$key] ?? NULL;
6a488035
TO
692
693 // update contact information
694 $this->updateContactInfo($value);
695
696 $membershipTypeId = $value['membership_type_id'] = $value['membership_type'][1];
697
a7488080 698 if (!empty($value['send_receipt'])) {
6a488035
TO
699 $value['receipt_date'] = date('Y-m-d His');
700 }
701
a7488080 702 if (!empty($value['membership_source'])) {
6a488035
TO
703 $value['source'] = $value['membership_source'];
704 }
705
706 unset($value['membership_source']);
707
708 //Get the membership status
a7488080 709 if (!empty($value['membership_status'])) {
6a488035
TO
710 $value['status_id'] = $value['membership_status'];
711 unset($value['membership_status']);
712 }
713
714 if (empty($customFields)) {
715 // membership type custom data
716 $customFields = CRM_Core_BAO_CustomField::getFields('Membership', FALSE, FALSE, $membershipTypeId);
717
718 $customFields = CRM_Utils_Array::crmArrayMerge($customFields,
719 CRM_Core_BAO_CustomField::getFields('Membership',
720 FALSE, FALSE, NULL, NULL, TRUE
721 )
722 );
723 }
724
725 //check for custom data
726 $value['custom'] = CRM_Core_BAO_CustomField::postProcess($params['field'][$key],
6a488035
TO
727 $key,
728 'Membership',
729 $membershipTypeId
730 );
731
a7488080 732 if (!empty($value['financial_type'])) {
6a488035
TO
733 $value['financial_type_id'] = $value['financial_type'];
734 }
735
a7488080 736 if (!empty($value['payment_instrument'])) {
6a488035
TO
737 $value['payment_instrument_id'] = $value['payment_instrument'];
738 }
739
740 // handle soft credit
9e1854a1 741 if (!empty($params['soft_credit_contact_id'][$key]) && !empty($params['soft_credit_amount'][$key])) {
ccec9d6b 742 $value['soft_credit'][$key]['contact_id'] = $params['soft_credit_contact_id'][$key];
0689c15c 743 $value['soft_credit'][$key]['amount'] = CRM_Utils_Rule::cleanMoney($params['soft_credit_amount'][$key]);
9e1854a1 744
745 //CRM-15350: if soft-credit-type profile field is disabled or removed then
746 //we choose Gift as default value as per Gift Membership rule
747 if (!empty($params['soft_credit_type'][$key])) {
748 $value['soft_credit'][$key]['soft_credit_type_id'] = $params['soft_credit_type'][$key];
749 }
750 else {
1a453756 751 $value['soft_credit'][$key]['soft_credit_type_id'] = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'Gift');
9e1854a1 752 }
6a488035 753 }
42bcf2d6
SL
754 if (!empty($value['total_amount'])) {
755 $value['total_amount'] = (float) $value['total_amount'];
756 }
6a488035 757
42bcf2d6 758 $params['actualBatchTotal'] += $value['total_amount'];
6a488035
TO
759
760 unset($value['financial_type']);
761 unset($value['payment_instrument']);
762
763 $value['batch_id'] = $this->_batchId;
764 $value['skipRecentView'] = TRUE;
765
766 // make entry in line item for contribution
8ef12e64 767
be2fb01f 768 $editedFieldParams = [
6a488035 769 'price_set_id' => $priceSetId,
21dfd5f5 770 'name' => $value['membership_type'][0],
be2fb01f 771 ];
6a488035 772
be2fb01f 773 $editedResults = [];
9da8dc8c 774 CRM_Price_BAO_PriceField::retrieve($editedFieldParams, $editedResults);
6a488035
TO
775
776 if (!empty($editedResults)) {
777 unset($this->_priceSet['fields']);
778 $this->_priceSet['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
779 unset($this->_priceSet['fields'][$editedResults['id']]['options']);
780 $fid = $editedResults['id'];
be2fb01f 781 $editedFieldParams = [
6a488035 782 'price_field_id' => $editedResults['id'],
21dfd5f5 783 'membership_type_id' => $value['membership_type_id'],
be2fb01f 784 ];
6a488035 785
be2fb01f 786 $editedResults = [];
9da8dc8c 787 CRM_Price_BAO_PriceFieldValue::retrieve($editedFieldParams, $editedResults);
6a488035 788 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
a7488080 789 if (!empty($value['total_amount'])) {
6a488035
TO
790 $this->_priceSet['fields'][$fid]['options'][$editedResults['id']]['amount'] = $value['total_amount'];
791 }
792
793 $fieldID = key($this->_priceSet['fields']);
794 $value['price_' . $fieldID] = $editedResults['id'];
795
be2fb01f 796 $lineItem = [];
9da8dc8c 797 CRM_Price_BAO_PriceSet::processAmount($this->_priceSet['fields'],
6a488035
TO
798 $value, $lineItem[$priceSetId]
799 );
800
8ef12e64 801 //CRM-11529 for backoffice transactions
802 //when financial_type_id is passed in form, update the
6a488035 803 //lineitems with the financial type selected in form
8cc574cf 804 if (!empty($value['financial_type_id']) && !empty($lineItem[$priceSetId])) {
6a488035
TO
805 foreach ($lineItem[$priceSetId] as &$values) {
806 $values['financial_type_id'] = $value['financial_type_id'];
807 }
808 }
8ef12e64 809
6a488035
TO
810 $value['lineItems'] = $lineItem;
811 $value['processPriceSet'] = TRUE;
812 }
813 // end of contribution related section
814
815 unset($value['membership_type']);
8ef12e64 816
691df66d 817 $value['is_renew'] = FALSE;
481a74f4 818 if (!empty($params['member_option']) && CRM_Utils_Array::value($key, $params['member_option']) == 2) {
61767a1d
EM
819
820 // The following parameter setting may be obsolete.
6a488035 821 $this->_params = $params;
691df66d 822 $value['is_renew'] = TRUE;
9c1bc317 823 $isPayLater = $params['is_pay_later'] ?? NULL;
61767a1d
EM
824 $campaignId = NULL;
825 if (isset($this->_values) && is_array($this->_values) && !empty($this->_values)) {
9c1bc317 826 $campaignId = $this->_params['campaign_id'] ?? NULL;
61767a1d 827 if (!array_key_exists('campaign_id', $this->_params)) {
9c1bc317 828 $campaignId = $this->_values['campaign_id'] ?? NULL;
61767a1d
EM
829 }
830 }
04b40eab 831
be2fb01f 832 $formDates = [
6b409353
CW
833 'end_date' => $value['membership_end_date'] ?? NULL,
834 'start_date' => $value['membership_start_date'] ?? NULL,
be2fb01f 835 ];
9c1bc317 836 $membershipSource = $value['source'] ?? NULL;
356bfcaf 837 list($membership) = CRM_Member_BAO_Membership::processMembership(
61767a1d 838 $value['contact_id'], $value['membership_type_id'], FALSE,
55d094e7 839 //$numTerms should be default to 1.
840 NULL, NULL, $value['custom'], 1, NULL, FALSE,
620ce374 841 NULL, $membershipSource, $isPayLater, $campaignId, $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);
8ef12e64 850 }
6a488035 851 else {
be2fb01f 852 $dateTypes = [
b2c9a0e3 853 'membership_join_date' => 'joinDate',
04b40eab 854 'membership_start_date' => 'startDate',
855 'membership_end_date' => 'endDate',
be2fb01f 856 ];
04b40eab 857
be2fb01f 858 $dates = [
04b40eab 859 'join_date',
860 'start_date',
861 'end_date',
862 'reminder_date',
be2fb01f 863 ];
04b40eab 864 foreach ($dateTypes as $dateField => $dateVariable) {
865 $$dateVariable = CRM_Utils_Date::processDate($value[$dateField]);
9c1bc317 866 $fDate[$dateField] = $value[$dateField] ?? NULL;
04b40eab 867 }
868
be2fb01f 869 $calcDates = [];
04b40eab 870 $calcDates[$membershipTypeId] = CRM_Member_BAO_MembershipType::getDatesForMembershipType($membershipTypeId,
871 $joinDate, $startDate, $endDate
872 );
873
874 foreach ($calcDates as $memType => $calcDate) {
875 foreach ($dates as $d) {
876 //first give priority to form values then calDates.
9c1bc317 877 $date = $value[$d] ?? NULL;
04b40eab 878 if (!$date) {
9c1bc317 879 $date = $calcDate[$d] ?? NULL;
04b40eab 880 }
881
882 $value[$d] = CRM_Utils_Date::processDate($date);
883 }
884 }
885
886 unset($value['membership_start_date']);
887 unset($value['membership_end_date']);
be2fb01f 888 $ids = [];
f57cb50c 889 // @todo stop passing empty $ids
04b40eab 890 $membership = CRM_Member_BAO_Membership::create($value, $ids);
6a488035
TO
891 }
892
893 //process premiums
a7488080 894 if (!empty($value['product_name'])) {
6a488035
TO
895 if ($value['product_name'][0] > 0) {
896 list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo();
897
898 $value['hidden_Premium'] = 1;
899 $value['product_option'] = CRM_Utils_Array::value(
900 $value['product_name'][1],
901 $options[$value['product_name'][0]]
902 );
903
be2fb01f 904 $premiumParams = [
6a488035 905 'product_id' => $value['product_name'][0],
5056dc8e 906 'contribution_id' => CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id'),
6a488035
TO
907 'product_option' => $value['product_option'],
908 'quantity' => 1,
be2fb01f 909 ];
6a488035
TO
910 CRM_Contribute_BAO_Contribution::addPremium($premiumParams);
911 }
912 }
913 // end of premium
914
915 //send receipt mail.
481a74f4 916 if ($membership->id && !empty($value['send_receipt'])) {
6a488035 917
691df66d
TO
918 // add the domain email id
919 $domainEmail = CRM_Core_BAO_Domain::getNameAndEmail();
920 $domainEmail = "$domainEmail[0] <$domainEmail[1]>";
6a488035 921
691df66d 922 $value['from_email_address'] = $domainEmail;
353ffa53 923 $value['membership_id'] = $membership->id;
691df66d 924 $value['contribution_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment', $membership->id, 'contribution_id', 'membership_id');
481a74f4 925 CRM_Member_Form_Membership::emailReceipt($this, $value, $membership);
6a488035
TO
926 }
927 }
928 }
afe349ef 929 return TRUE;
6a488035
TO
930 }
931
932 /**
eceb18cc 933 * Update contact information.
6a488035 934 *
82d480a5
TO
935 * @param array $value
936 * Associated array of submitted values.
6a488035
TO
937 */
938 private function updateContactInfo(&$value) {
939 $value['preserveDBName'] = $this->_preserveDefault;
940
941 //parse street address, CRM-7768
942 CRM_Contact_Form_Task_Batch::parseStreetAddress($value, $this);
943
944 CRM_Contact_BAO_Contact::createProfileContact($value, $this->_fields,
945 $value['contact_id']
946 );
947 }
cab024d4 948
afe349ef 949 /**
ce064e4f 950 * Function exists purely for unit testing purposes.
951 *
952 * If you feel tempted to use this in live code then it probably means there is some functionality
953 * that needs to be moved out of the form layer
cab024d4 954 *
4c16123d 955 * @param array $params
cab024d4
EM
956 *
957 * @return bool
afe349ef 958 */
00be9182 959 public function testProcessMembership($params) {
afe349ef 960 return $this->processMembership($params);
961 }
cab024d4
EM
962
963 /**
ce064e4f 964 * Function exists purely for unit testing purposes.
965 *
966 * If you feel tempted to use this in live code then it probably means there is some functionality
967 * that needs to be moved out of the form layer.
cab024d4
EM
968 *
969 * @param array $params
970 *
971 * @return bool
abd76e0d 972 *
973 * @throws \CRM_Core_Exception
974 * @throws \CiviCRM_API3_Exception
cab024d4 975 */
00be9182 976 public function testProcessContribution($params) {
cab024d4
EM
977 return $this->processContribution($params);
978 }
96025800 979
6a488035 980}