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