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